repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
ruinianxu/sentence-transformers
|
[
"b4ab6f0378ea1cb0c33a60163f0aabba6ac0a477"
] |
[
"examples/training/sts/training_gt_rt_exonly_simple.py"
] |
[
"\"\"\"\nThis examples trains BERT (or any other transformer model like RoBERTa, DistilBERT etc.) for the STSbenchmark from scratch. It generates sentence embeddings\nthat can be compared using cosine-similarity to measure the similarity.\n\nUsage:\npython training_nli.py\n\nOR\npython training_nli.py pretrained_transformer_model_name\n\"\"\"\nfrom torch.utils.data import DataLoader\nimport math\nfrom sentence_transformers import SentenceTransformer, LoggingHandler, losses, models, util\nfrom sentence_transformers.evaluation import EmbeddingSimilarityEvaluator\nfrom sentence_transformers.readers import InputExample\nimport logging\nfrom datetime import datetime\nimport sys\nimport os\nimport gzip\nimport csv\nimport numpy as np\n\n#### Just some code to print debug information to stdout\nlogging.basicConfig(format='%(asctime)s - %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n level=logging.INFO,\n handlers=[LoggingHandler()])\n#### /print debug information to stdout\n\n\n#Check if dataset exsist. If not, download and extract it\ndataset_path = '/home/ruinian/IVALab/Project/TaskGrounding/sentence-transformers/datasets/gt_rt_exonly_simple_small_sample.csv'\n\n#You can specify any huggingface/transformers pre-trained model here, for example, bert-base-uncased, roberta-base, xlm-roberta-base\nmodel_name = sys.argv[1] if len(sys.argv) > 1 else 'distilbert-base-uncased'\n\n# Read the dataset\ntrain_batch_size = 16\nnum_epochs = 4\nmodel_save_path = 'output/training_stsbenchmark_'+model_name.replace(\"/\", \"-\")+'-'+datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")\n\n# Use Huggingface/transformers model (like BERT, RoBERTa, XLNet, XLM-R) for mapping tokens to embeddings\nword_embedding_model = models.Transformer(model_name)\n\n# Apply mean pooling to get one fixed sized sentence vector\npooling_model = models.Pooling(word_embedding_model.get_word_embedding_dimension(),\n pooling_mode_mean_tokens=True,\n pooling_mode_cls_token=False,\n pooling_mode_max_tokens=False)\n\nmodel = SentenceTransformer(modules=[word_embedding_model, pooling_model])\n\n# Convert the dataset to a DataLoader ready for training\nlogging.info(\"Read GT RT train dataset\")\n\ntrain_samples = []\ndev_samples = []\ntest_samples = []\n# with gzip.open(sts_dataset_path, 'rt', encoding='utf8') as fIn:\naverage_scores = 0\nnum_samples = 0\nwith open(dataset_path, newline='') as csvfile:\n reader = csv.DictReader(csvfile, delimiter='\\t', quoting=csv.QUOTE_NONE)\n for row in reader:\n score = float(row['score']) / 5.0 # Normalize score to range 0 ... 1\n # inp_example = InputExample(texts=[row['sentence1'], row['sentence2']], label=score)\n # label = np.random.uniform(low=0.99, high=1.0)\n inp_example = InputExample(texts=[row['sentence1'], row['sentence2']], label=score)\n\n if row['split'] == 'dev':\n dev_samples.append(inp_example)\n elif row['split'] == 'test':\n test_samples.append(inp_example)\n else:\n train_samples.append(inp_example)\n\ntrain_dataloader = DataLoader(train_samples, shuffle=True, batch_size=train_batch_size)\ntrain_loss = losses.CosineSimilarityLoss(model=model)\n\n\nlogging.info(\"Read GT RT dev dataset\")\nevaluator = EmbeddingSimilarityEvaluator.from_input_examples(dev_samples, name='sts-dev')\n\n\n# Configure the training. We skip evaluation in this example\nwarmup_steps = math.ceil(len(train_dataloader) * num_epochs * 0.1) #10% of train data for warm-up\nlogging.info(\"Warmup-steps: {}\".format(warmup_steps))\n\n\n# Train the model\nmodel.fit(train_objectives=[(train_dataloader, train_loss)],\n evaluator=evaluator,\n epochs=num_epochs,\n evaluation_steps=5000,\n warmup_steps=warmup_steps,\n output_path=model_save_path,\n optimizer_params = {'lr': 2e-5})\n\n\n##############################################################################\n#\n# Load the stored model and evaluate its performance on STS benchmark dataset\n#\n##############################################################################\nmodel = SentenceTransformer(model_save_path)\ntest_evaluator = EmbeddingSimilarityEvaluator.from_input_examples(test_samples, name='sts-test')\ntest_evaluator(model, output_path=model_save_path)\n"
] |
[
[
"torch.utils.data.DataLoader"
]
] |
xavialex/Instance-Segmentation
|
[
"7ad73ed8b352d8ffefe4265b2469949daae5e209"
] |
[
"instance_segmentation_webcam.py"
] |
[
"from pathlib import Path\nimport cv2\nimport time\nimport numpy as np\nimport tensorflow as tf\n\nfrom object_detection.utils import label_map_util\nfrom object_detection.utils import visualization_utils as vis_util\nfrom object_detection.utils import ops as utils_ops\n\nCWD_PATH = Path('.')\nTF_MODELS_PATH = Path('../TensorFlow Object Detection Models/trained_models')\n# Path to frozen detection graph. This is the actual model that is used for the object detection\nMODEL_NAME = 'mask_rcnn_inception_v2_coco_2018_01_28'\nPATH_TO_CKPT = TF_MODELS_PATH / MODEL_NAME / 'frozen_inference_graph.pb'\n\n# List of the strings that is used to add correct label for each box\nPATH_TO_LABELS = CWD_PATH / 'object_detection' / 'data' / 'mscoco_label_map.pbtxt'\n\nNUM_CLASSES = 90\n\n# Loading label map\nlabel_map = label_map_util.load_labelmap(str(PATH_TO_LABELS))\ncategories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES,\n use_display_name=True)\ncategory_index = label_map_util.create_category_index(categories)\n\ndef model_load_into_memory():\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(str(PATH_TO_CKPT), 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n \n return detection_graph\n\ndef run_inference_for_single_image(image, sess, graph, class_id=None):\n \"\"\"Feed forward an image into the object detection model.\n \n Args:\n image (ndarray): Input image in numpy format (OpenCV format).\n sess: TF session.\n graph: Object detection model loaded before.\n class_id (list): Optional. Id's of the classes you want to detect. \n Refer to mscoco_label_map.pbtxt' to find out more.\n \n Returns:\n output_dict (dict): Contains the info related to the detections.\n \n \"\"\"\n # Get handles to input and output tensors\n ops = tf.get_default_graph().get_operations()\n all_tensor_names = {output.name for op in ops for output in op.outputs}\n tensor_dict = {}\n \n for key in ['num_detections', 'detection_boxes', 'detection_scores', \n 'detection_classes', 'detection_masks']:\n tensor_name = key + ':0'\n if tensor_name in all_tensor_names:\n tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(tensor_name)\n \n if 'detection_masks' in tensor_dict:\n # The following processing is only for single image\n detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])\n detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])\n # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.\n real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)\n detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])\n detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])\n detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(\n detection_masks, detection_boxes, image.shape[0], image.shape[1])\n detection_masks_reframed = tf.cast(\n tf.greater(detection_masks_reframed, 0.5), tf.uint8)\n # Follow the convention by adding back the batch dimension\n tensor_dict['detection_masks'] = tf.expand_dims(detection_masks_reframed, 0)\n \n image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')\n\n # Run inference\n output_dict = sess.run(tensor_dict,\n feed_dict={image_tensor: np.expand_dims(image, 0)})\n \n # All outputs are float32 numpy arrays, so convert types as appropriate\n output_dict['num_detections'] = int(output_dict['num_detections'][0])\n output_dict['detection_classes'] = output_dict['detection_classes'][0].astype(np.uint8)\n output_dict['detection_boxes'] = output_dict['detection_boxes'][0]\n output_dict['detection_scores'] = output_dict['detection_scores'][0]\n if 'detection_masks' in output_dict:\n output_dict['detection_masks'] = output_dict['detection_masks'][0].astype(np.float32)\n \n if class_id is not None:\n discrimine_class(class_id, output_dict)\n \n return output_dict\n\ndef discrimine_class(class_id, output_dict):\n \"\"\"Take just one class instances in the image of interest\n \n Args:\n class_id (int): Id's of the classes you want to detect. Refer to \n mscoco_label_map.pbtxt' to find out more.\n output_dict (dict): Output if the model once an image is processed.\n \n Returns:\n output_dict (dict): Modified dictionary which just delivers the\n specified class detections.\n \n \"\"\"\n total_observations = 0 # Total observations per frame\n for i in range(output_dict['detection_classes'].size):\n if output_dict['detection_classes'][i] in class_id and output_dict['detection_scores'][i]>=0.5:\n # The detection is from the desired category and with enough confidence\n total_observations += 1\n elif output_dict['detection_classes'][i] not in class_id:\n # As this is a not desired detection, the score is artificially lowered\n output_dict['detection_scores'][i] = 0.02\n print(\"######################### \" + str(total_observations) + \" ########################\")\n \ndef visualize_results(image, output_dict):\n \"\"\"Returns the resulting image after being passed to the model.\n \n Args:\n image (ndarray): Original image given to the model.\n output_dict (dict): Dictionary with all the information provided by the model.\n \n Returns:\n image (ndarray): Visualization of the results form above.\n \n \"\"\"\n vis_util.visualize_boxes_and_labels_on_image_array(\n image,\n output_dict['detection_boxes'],\n output_dict['detection_classes'],\n output_dict['detection_scores'],\n category_index,\n instance_masks=output_dict.get('detection_masks'),\n use_normalized_coordinates=True,\n line_thickness=4)\n \n return image\n\n \ndef main():\n video_capture = cv2.VideoCapture(0)\n detection_graph = model_load_into_memory()\n try:\n with detection_graph.as_default():\n with tf.Session(graph=detection_graph) as sess:\n while True: \n # Camera detection loop\n _, frame = video_capture.read()\n cv2.imshow('Entrada', frame)\n # Change color gammut to feed the frame into the network\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n t = time.time()\n output = run_inference_for_single_image(frame, sess, detection_graph, [1, 44])\n processed_image = visualize_results(frame, output)\n cv2.imshow('Video', cv2.cvtColor(processed_image, cv2.COLOR_BGR2RGB))\n print('Elapsed time: {:.2f}'.format(time.time() - t))\n \n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n \n except KeyboardInterrupt: \n pass\n \n print(\"Ending resources\")\n cv2.destroyAllWindows()\n video_capture.release()\n \n\nif __name__ == '__main__':\n main()\n "
] |
[
[
"tensorflow.Graph",
"tensorflow.import_graph_def",
"numpy.expand_dims",
"tensorflow.greater",
"tensorflow.slice",
"tensorflow.cast",
"tensorflow.squeeze",
"tensorflow.expand_dims",
"tensorflow.Session",
"tensorflow.get_default_graph",
"tensorflow.GraphDef"
]
] |
omidsakhi/non_progressive_stylegan
|
[
"4a9c41a279fd10065764cf297f5925a74c164e5c"
] |
[
"models.py"
] |
[
"import tensorflow as tf\nimport ops\n\ndef discriminator(x, is_training=True, scope='Discriminator'):\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n\n x = tf.concat(tf.split(x, 2, 0), axis=3)\n\n fn = 64 \n\n x = ops.conv2d_down('256-128', x, fn, 5, 'NHWC')\n x = ops.lrelu(x)\n\n x = ops.conv2d_down('128-64', x, fn * 2, 5, 'NHWC')\n x = ops.lrelu(x)\n\n x = ops.conv2d_down('64-32', x, fn * 4, 5, 'NHWC')\n x = ops.lrelu(x)\n\n x = ops.conv2d_down('32-16', x, fn * 4, 5, 'NHWC')\n x = ops.lrelu(x)\n\n x = ops.conv2d_down('16-8', x, fn * 4, 5, 'NHWC')\n x = ops.lrelu(x)\n \n x = ops.minibatch_stddev_layer(x, 'NHWC')\n\n x = ops.conv2d_down('8-4', x, fn * 8, 5, 'NHWC')\n x = ops.lrelu(x)\n\n x = ops.conv2d('4', x, 1, 1, 'NHWC', gain=1.0)\n\n return x\n\ndef gblock_top(z1, z2, ch_dim, name, lr_mult1=1.0, lr_mult2=1.0):\n with tf.variable_scope(name):\n batch_size = int(z1.get_shape()[0])\n top8 = tf.get_variable('top', shape=[1, 8, 8, ch_dim], dtype=tf.float32)\n top8 = ops._lr_mult(lr_mult2)(top8)\n x = tf.tile(top8, [batch_size, 1, 1, 1])\n x = ops.lrelu(ops.adaptive_instance_norm('top_bn', x, z1, 'NHWC', lr_mult=lr_mult2)) \n x = ops.conv2d(\"conv_2\", x, ch_dim, 3, 'NHWC', has_bias=False, lr_mult=lr_mult1)\n x = ops.lrelu(ops.adaptive_instance_norm('bn_2', x, z2, 'NHWC', lr_mult=lr_mult1)) \n return x\n\ndef gblock_up(x, z1, z2, ch_dim, kernel_size, name, lr_mult1=1.0, lr_mult2=1.0):\n with tf.variable_scope(name): \n x = ops.upscale2d(x, 'NHWC')\n x = ops.conv2d(\"conv_1\", x, ch_dim, kernel_size, 'NHWC', has_bias=False, lr_mult=lr_mult2)\n x = ops.lrelu(ops.adaptive_instance_norm('bn_1', x, z1, 'NHWC', lr_mult=lr_mult2)) \n x = ops.conv2d(\"conv_2\", x, ch_dim, kernel_size, 'NHWC', has_bias=False, lr_mult=lr_mult1)\n x = ops.lrelu(ops.adaptive_instance_norm('bn_2', x, z2, 'NHWC', lr_mult=lr_mult1))\n return x\n\ndef mapping(z, scope='Generator'):\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE): \n \n fn = 32\n steps = 500\n\n z = ops.dense('fc', z, fn * 4, 'NC', lr_mult=1.0/(16.0 * steps)) \n z = ops.relu(z)\n \n z0 = ops.dense('fc-0', z, fn * 4, 'NC', lr_mult=1.0/(15.0 * steps)) \n z0 = ops.relu(z0)\n\n z1 = ops.dense('fc-1', z, fn * 4, 'NC', lr_mult=1.0/(15.0 * steps)) \n z1 = ops.relu(z1)\n\n z00 = ops.dense('fc-00', z0, fn * 4, 'NC', lr_mult=1.0/(14.0 * steps)) \n z00 = ops.relu(z00)\n\n z01 = ops.dense('fc-01', z0, fn * 4, 'NC', lr_mult=1.0/(14.0 * steps)) \n z01 = ops.relu(z01)\n\n z10 = ops.dense('fc-10', z1, fn * 4, 'NC', lr_mult=1.0/(14.0 * steps)) \n z10 = ops.relu(z10)\n\n z11 = ops.dense('fc-11', z1, fn * 4, 'NC', lr_mult=1.0/(14.0 * steps)) \n z11 = ops.relu(z11)\n\n return z00, z01, z10, z11\n\ndef generator(z00, z01, z10, z11, is_training, scope='Generator'): \n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE): \n \n fn = 32\n steps = 500\n\n x = gblock_top(z00,z00, fn * 8, 'top', lr_mult1=1.0/(12.0 * steps), lr_mult2=1.0/(13.0 * steps))\n x = gblock_up(x, z00,z01, fn * 8, 3, '8-16', lr_mult1=1.0/(10.0 * steps), lr_mult2=1.0/(11.0 * steps))\n x = gblock_up(x, z01,z01, fn * 4, 3, '16-32', lr_mult1=1.0/(8.0 * steps), lr_mult2=1.0/(9.0 * steps))\n x = gblock_up(x, z10,z10, fn * 4, 3, '32-64', lr_mult1=1.0/(6.0 * steps), lr_mult2=1.0/(7.0 * steps))\n x = gblock_up(x, z10,z11, fn * 2, 3, '64-128', lr_mult1=1.0/(4.0 * steps), lr_mult2=1.0/(5.0 * steps))\n x = gblock_up(x, z11,z11, fn, 3, '128-256', lr_mult1=1.0/(2.0 * steps), lr_mult2=1.0/(3.0 * steps))\n x = ops.conv2d('gout', x, 3, 1, 'NHWC', gain=1.0, lr_mult=1.0/(1.0 * steps))\n\n x = tf.nn.tanh(x)\n\n return x"
] |
[
[
"tensorflow.get_variable",
"tensorflow.nn.tanh",
"tensorflow.variable_scope",
"tensorflow.split",
"tensorflow.tile"
]
] |
AndrewKinsman/rasa
|
[
"810d1c2f52261b3704b0b77b7fcb8c63eafaeb5e"
] |
[
"rasa/utils/common.py"
] |
[
"import logging\nimport os\nimport shutil\nfrom types import TracebackType\nfrom typing import Any, Callable, Dict, List, Text, Optional, Type\n\nimport rasa.core.utils\nimport rasa.utils.io\nfrom rasa.constants import (\n GLOBAL_USER_CONFIG_PATH,\n DEFAULT_LOG_LEVEL,\n ENV_LOG_LEVEL,\n DEFAULT_LOG_LEVEL_LIBRARIES,\n ENV_LOG_LEVEL_LIBRARIES,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass TempDirectoryPath(str):\n \"\"\"Represents a path to an temporary directory. When used as a context\n manager, it erases the contents of the directory on exit.\n\n \"\"\"\n\n def __enter__(self) -> \"TempDirectoryPath\":\n return self\n\n def __exit__(\n self,\n _exc: Optional[Type[BaseException]],\n _value: Optional[Exception],\n _tb: Optional[TracebackType],\n ) -> bool:\n if os.path.exists(self):\n shutil.rmtree(self)\n\n\ndef arguments_of(func: Callable) -> List[Text]:\n \"\"\"Return the parameters of the function `func` as a list of names.\"\"\"\n import inspect\n\n return list(inspect.signature(func).parameters.keys())\n\n\ndef read_global_config() -> Dict[Text, Any]:\n \"\"\"Read global Rasa configuration.\"\"\"\n # noinspection PyBroadException\n try:\n return rasa.utils.io.read_config_file(GLOBAL_USER_CONFIG_PATH)\n except Exception:\n # if things go south we pretend there is no config\n return {}\n\n\ndef set_log_level(log_level: Optional[int] = None):\n \"\"\"Set log level of Rasa and Tensorflow either to the provided log level or\n to the log level specified in the environment variable 'LOG_LEVEL'. If none is set\n a default log level will be used.\"\"\"\n import logging\n\n if not log_level:\n log_level = os.environ.get(ENV_LOG_LEVEL, DEFAULT_LOG_LEVEL)\n log_level = logging.getLevelName(log_level)\n\n logging.getLogger(\"rasa\").setLevel(log_level)\n\n update_tensorflow_log_level()\n update_asyncio_log_level()\n update_apscheduler_log_level()\n\n os.environ[ENV_LOG_LEVEL] = logging.getLevelName(log_level)\n\n\ndef update_apscheduler_log_level() -> None:\n log_level = os.environ.get(ENV_LOG_LEVEL_LIBRARIES, DEFAULT_LOG_LEVEL_LIBRARIES)\n\n apscheduler_loggers = [\n \"apscheduler\",\n \"apscheduler.scheduler\",\n \"apscheduler.executors\",\n \"apscheduler.executors.default\",\n ]\n\n for logger_name in apscheduler_loggers:\n logging.getLogger(logger_name).setLevel(log_level)\n logging.getLogger(logger_name).propagate = False\n\n\ndef update_tensorflow_log_level() -> None:\n \"\"\"Set the log level of Tensorflow to the log level specified in the environment\n variable 'LOG_LEVEL_LIBRARIES'.\"\"\"\n import tensorflow as tf\n\n log_level = os.environ.get(ENV_LOG_LEVEL_LIBRARIES, DEFAULT_LOG_LEVEL_LIBRARIES)\n\n os.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"2\" # disables AVX2 FMA warnings (CPU support)\n if log_level == \"DEBUG\":\n tf_log_level = tf.compat.v1.logging.DEBUG\n elif log_level == \"INFO\":\n tf_log_level = tf.compat.v1.logging.INFO\n elif log_level == \"WARNING\":\n tf_log_level = tf.compat.v1.logging.WARN\n else:\n tf_log_level = tf.compat.v1.logging.ERROR\n\n tf.compat.v1.logging.set_verbosity(tf_log_level)\n logging.getLogger(\"tensorflow\").propagate = False\n\n\ndef update_sanic_log_level(log_file: Optional[Text] = None):\n \"\"\"Set the log level of sanic loggers to the log level specified in the environment\n variable 'LOG_LEVEL_LIBRARIES'.\"\"\"\n from sanic.log import logger, error_logger, access_logger\n\n log_level = os.environ.get(ENV_LOG_LEVEL_LIBRARIES, DEFAULT_LOG_LEVEL_LIBRARIES)\n\n logger.setLevel(log_level)\n error_logger.setLevel(log_level)\n access_logger.setLevel(log_level)\n\n logger.propagate = False\n error_logger.propagate = False\n access_logger.propagate = False\n\n if log_file is not None:\n formatter = logging.Formatter(\"%(asctime)s [%(levelname)-5.5s] %(message)s\")\n file_handler = logging.FileHandler(log_file)\n file_handler.setFormatter(formatter)\n\n logger.addHandler(file_handler)\n error_logger.addHandler(file_handler)\n access_logger.addHandler(file_handler)\n\n\ndef update_asyncio_log_level() -> None:\n \"\"\"Set the log level of asyncio to the log level specified in the environment\n variable 'LOG_LEVEL_LIBRARIES'.\"\"\"\n log_level = os.environ.get(ENV_LOG_LEVEL_LIBRARIES, DEFAULT_LOG_LEVEL_LIBRARIES)\n logging.getLogger(\"asyncio\").setLevel(log_level)\n\n\ndef obtain_verbosity() -> int:\n \"\"\"Returns a verbosity level according to the set log level.\"\"\"\n log_level = os.environ.get(ENV_LOG_LEVEL, DEFAULT_LOG_LEVEL)\n\n verbosity = 0\n if log_level == \"DEBUG\":\n verbosity = 2\n if log_level == \"INFO\":\n verbosity = 1\n\n return verbosity\n\n\ndef is_logging_disabled() -> bool:\n \"\"\"Returns true, if log level is set to WARNING or ERROR, false otherwise.\"\"\"\n log_level = os.environ.get(ENV_LOG_LEVEL, DEFAULT_LOG_LEVEL)\n\n return log_level == \"ERROR\" or log_level == \"WARNING\"\n\n\ndef sort_list_of_dicts_by_first_key(dicts: List[Dict]) -> List[Dict]:\n \"\"\"Sorts a list of dictionaries by their first key.\"\"\"\n return sorted(dicts, key=lambda d: list(d.keys())[0])\n\n\n# noinspection PyUnresolvedReferences\ndef class_from_module_path(\n module_path: Text, lookup_path: Optional[Text] = None\n) -> Any:\n \"\"\"Given the module name and path of a class, tries to retrieve the class.\n\n The loaded class can be used to instantiate new objects. \"\"\"\n import importlib\n\n # load the module, will raise ImportError if module cannot be loaded\n if \".\" in module_path:\n module_name, _, class_name = module_path.rpartition(\".\")\n m = importlib.import_module(module_name)\n # get the class, will raise AttributeError if class cannot be found\n return getattr(m, class_name)\n else:\n module = globals().get(module_path, locals().get(module_path))\n if module is not None:\n return module\n\n if lookup_path:\n # last resort: try to import the class from the lookup path\n m = importlib.import_module(lookup_path)\n return getattr(m, module_path)\n else:\n raise ImportError(f\"Cannot retrieve class from path {module_path}.\")\n\n\ndef minimal_kwargs(\n kwargs: Dict[Text, Any], func: Callable, excluded_keys: Optional[List] = None\n) -> Dict[Text, Any]:\n \"\"\"Returns only the kwargs which are required by a function. Keys, contained in\n the exception list, are not included.\n\n Args:\n kwargs: All available kwargs.\n func: The function which should be called.\n excluded_keys: Keys to exclude from the result.\n\n Returns:\n Subset of kwargs which are accepted by `func`.\n\n \"\"\"\n\n excluded_keys = excluded_keys or []\n\n possible_arguments = arguments_of(func)\n\n return {\n k: v\n for k, v in kwargs.items()\n if k in possible_arguments and k not in excluded_keys\n }\n\n\ndef write_global_config_value(name: Text, value: Any) -> None:\n \"\"\"Read global Rasa configuration.\"\"\"\n\n try:\n os.makedirs(os.path.dirname(GLOBAL_USER_CONFIG_PATH), exist_ok=True)\n\n c = read_global_config()\n c[name] = value\n rasa.core.utils.dump_obj_as_yaml_to_file(GLOBAL_USER_CONFIG_PATH, c)\n except Exception as e:\n logger.warning(f\"Failed to write global config. Error: {e}. Skipping.\")\n\n\ndef read_global_config_value(name: Text, unavailable_ok: bool = True) -> Any:\n \"\"\"Read a value from the global Rasa configuration.\"\"\"\n\n def not_found():\n if unavailable_ok:\n return None\n else:\n raise ValueError(f\"Configuration '{name}' key not found.\")\n\n if not os.path.exists(GLOBAL_USER_CONFIG_PATH):\n return not_found()\n\n c = read_global_config()\n\n if name in c:\n return c[name]\n else:\n return not_found()\n\n\ndef mark_as_experimental_feature(feature_name: Text) -> None:\n \"\"\"Warns users that they are using an experimental feature.\"\"\"\n\n logger.warning(\n f\"The {feature_name} is currently experimental and might change or be \"\n \"removed in the future 🔬 Please share your feedback on it in the \"\n \"forum (https://forum.rasa.com) to help us make this feature \"\n \"ready for production.\"\n )\n\n\ndef lazy_property(function: Callable) -> Any:\n \"\"\"Allows to avoid recomputing a property over and over.\n\n The result gets stored in a local var. Computation of the property\n will happen once, on the first call of the property. All\n succeeding calls will use the value stored in the private property.\"\"\"\n\n attr_name = \"_lazy_\" + function.__name__\n\n @property\n def _lazyprop(self):\n if not hasattr(self, attr_name):\n setattr(self, attr_name, function(self))\n return getattr(self, attr_name)\n\n return _lazyprop\n"
] |
[
[
"tensorflow.compat.v1.logging.set_verbosity"
]
] |
seguri/machine-learning-for-financial-analysis
|
[
"3747461ec093629d3dae9bc88195d74672b00c6b"
] |
[
"CAPM.py"
] |
[
"#!/usr/bin/env python\n# coding: utf-8\n\n# # Capital Asset Pricing Model\n\n# ## Milestone 1\n\n# In[65]:\n\n\nget_ipython().run_line_magic('reload_ext', 'dotenv')\nget_ipython().run_line_magic('dotenv', '')\nget_ipython().run_line_magic('matplotlib', 'inline')\n\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport statsmodels.api as sm\nimport yfinance as yf\nfrom fredapi import Fred\n\nsns.set()\n\nFRED_API_KEY = os.getenv('FRED_API_KEY')\n\n\n# Download the closing prices of the desired symbols.\n\n# In[44]:\n\n\nstocks_symbols = ['AAPL', 'IBM', 'MSFT', 'INTC', '^GSPC']\nstocks = yf.download(stocks_symbols, start='2021-01-01', end='2021-04-01')\nstocks = stocks['Close']\nstocks = stocks.dropna()\nstocks = stocks.rename(columns={'^GSPC': 'GSPC'})\nstocks.describe()\n\n\n# Search for risk free rate data in the Federal Reserve Economic Data:\n\n# In[45]:\n\n\nfred = Fred(api_key=FRED_API_KEY)\nfred.search('risk free')\n\n\n# We are interested in `DGS3MO`, as it is a government-issued and widely applicable rate.\n\n# In[46]:\n\n\nrisk_free = fred.get_series('DGS3MO')\nrisk_free = risk_free['2021-01-01':'2021-04-01']\n\n\n# ## Milestone 2\n\n# The purpose of this milestone is to calculate excess returns. To do that, we need:\n# - calculate stock returns as percentage\n# - convert risk free rate to daily value\n# - subtract each other\n# \n# But first, some visualizations. Here are the trends of the downloaded stocks:\n\n# In[47]:\n\n\nfig, axes = plt.subplots(5, 1, sharex=True, figsize=(9, 8))\nfor i in range(5):\n sns.lineplot(data=stocks.iloc[:, i], ax=axes[i])\n\n\n# Let's also visualize the correlation between stocks. See how similar are the trends for Intel and SP500. Apple on the other hand is quite different.\n\n# In[48]:\n\n\nsns.heatmap(stocks.corr(), annot=True)\n\n\n# Let's start now start the journey to calculate excess returns. We start with the stock returns. Pandas provide a function `pct_change` to calculate those. We will just need to drop the first value as it will be `NaN` (as it cannot be compared to prior element).\n\n# In[49]:\n\n\nstock_returns = stocks.pct_change()\nstock_returns = stock_returns.dropna()\nstock_returns\n\n\n# We've already downloaded `risk_free` data in Milestone 1. It spans over 3 months. Let's make it a daily rate and also delete the last row, because it goes one day over the end of our stocks data.\n\n# In[50]:\n\n\nrisk_free_daily = risk_free / 90\nrisk_free_daily = risk_free_daily.dropna()\nrisk_free_daily = risk_free_daily.iloc[:-1]\nsns.lineplot(data=risk_free_daily)\n\n\n# In[51]:\n\n\nexcess_returns = stock_returns.sub(risk_free_daily, axis=0)\nexcess_returns\n\n\n# ## Milestone 3\n\n# In this milestone, we calculate the CAPM of our stocks with the help of the `statsmodels` library.\n\n# In[68]:\n\n\nendog = excess_returns['AAPL']\nexog = sm.add_constant(excess_returns['GSPC'])\nCAPM_AAPL = sm.OLS(endog, exog).fit()\n\n\n# In[74]:\n\n\nX = excess_returns['IBM']\ny = sm.add_constant(excess_returns['GSPC'])\nCAPM_IBM = sm.OLS(X, y).fit()\n\n\n# In[79]:\n\n\nX = excess_returns['INTC']\ny = sm.add_constant(excess_returns['GSPC'])\nCAPM_INTC = sm.OLS(X, y).fit()\n\n\n# In[80]:\n\n\nX = excess_returns['MSFT']\ny = sm.add_constant(excess_returns['GSPC'])\nCAPM_MSFT = sm.OLS(X, y).fit()\n\n\n# ## Useful links\n# \n# - [Risk Free Rate and Fama French factors](https://bizlib247.wordpress.com/2013/01/18/risk-free-rate-and-fama-french-factors/)\n# - [`endog`, `exog`, what’s that?](https://www.statsmodels.org/stable/endog_exog.html)\n# - [Ordinary Least Squares linear regression](https://www.statsmodels.org/stable/generated/statsmodels.regression.linear_model.OLS.html#statsmodels.regression.linear_model.OLS)\n# - [How to Version Control Jupyter Notebooks](https://nextjournal.com/schmudde/how-to-version-control-jupyter)\n# \n"
] |
[
[
"matplotlib.pyplot.subplots"
]
] |
royukira/estimator
|
[
"64a11cddd0b17308cd60040d8487074ce9a9264f"
] |
[
"tensorflow_estimator/python/estimator/canned/linear.py"
] |
[
"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Linear Estimators.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\n\nimport six\n\nfrom tensorflow.python.feature_column import feature_column\nfrom tensorflow.python.feature_column import feature_column_lib\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.keras.optimizer_v2 import ftrl as ftrl_v2\nfrom tensorflow.python.keras.utils import losses_utils\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn\nfrom tensorflow.python.ops import partitioned_variables\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables as variable_ops\nfrom tensorflow.python.ops.losses import losses\nfrom tensorflow.python.summary import summary\nfrom tensorflow.python.training import ftrl\nfrom tensorflow.python.training import session_run_hook\nfrom tensorflow.python.training import training\nfrom tensorflow.python.training import training_util\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util.tf_export import estimator_export\nfrom tensorflow_estimator.python.estimator import estimator\nfrom tensorflow_estimator.python.estimator.canned import head as head_lib\nfrom tensorflow_estimator.python.estimator.canned import optimizers\nfrom tensorflow_estimator.python.estimator.canned.linear_optimizer.python.utils import sdca_ops\nfrom tensorflow_estimator.python.estimator.head import binary_class_head\nfrom tensorflow_estimator.python.estimator.head import head_utils\nfrom tensorflow_estimator.python.estimator.head import regression_head\nfrom tensorflow_estimator.python.estimator.mode_keys import ModeKeys\n\n# The default learning rate of 0.2 is a historical artifact of the initial\n# implementation, but seems a reasonable choice.\n_LEARNING_RATE = 0.2\n\n\n@estimator_export('estimator.experimental.LinearSDCA')\nclass LinearSDCA(object):\n \"\"\"Stochastic Dual Coordinate Ascent helper for linear estimators.\n\n Objects of this class are intended to be provided as the optimizer argument\n (though LinearSDCA objects do not implement the `tf.train.Optimizer` interface)\n when creating `tf.estimator.LinearClassifier` or `tf.estimator.LinearRegressor`.\n\n SDCA can only be used with `LinearClassifier` and `LinearRegressor` under the\n following conditions:\n\n - Feature columns are of type V2.\n - Multivalent categorical columns are not normalized. In other words the\n `sparse_combiner` argument in the estimator constructor should be \"sum\".\n - For classification: binary label.\n - For regression: one-dimensional label.\n\n Example usage:\n\n ```python\n real_feature_column = numeric_column(...)\n sparse_feature_column = categorical_column_with_hash_bucket(...)\n linear_sdca = tf.estimator.experimental.LinearSDCA(\n example_id_column='example_id',\n num_loss_partitions=1,\n num_table_shards=1,\n symmetric_l2_regularization=2.0)\n classifier = tf.estimator.LinearClassifier(\n feature_columns=[real_feature_column, sparse_feature_column],\n weight_column=...,\n optimizer=linear_sdca)\n classifier.train(input_fn_train, steps=50)\n classifier.evaluate(input_fn=input_fn_eval)\n ```\n\n Here the expectation is that the `input_fn_*` functions passed to train and\n evaluate return a pair (dict, label_tensor) where dict has `example_id_column`\n as `key` whose value is a `Tensor` of shape [batch_size] and dtype string.\n num_loss_partitions defines sigma' in eq (11) of [3]. Convergence of (global)\n loss is guaranteed if `num_loss_partitions` is larger or equal to the product\n `(#concurrent train ops/per worker) x (#workers)`. Larger values for\n `num_loss_partitions` lead to slower convergence. The recommended value for\n `num_loss_partitions` in `tf.estimator` (where currently there is one process\n per worker) is the number of workers running the train steps. It defaults to 1\n (single machine).\n `num_table_shards` defines the number of shards for the internal state\n table, typically set to match the number of parameter servers for large\n data sets.\n\n The SDCA algorithm was originally introduced in [1] and it was followed by\n the L1 proximal step [2], a distributed version [3] and adaptive sampling [4].\n [1] www.jmlr.org/papers/volume14/shalev-shwartz13a/shalev-shwartz13a.pdf\n [2] https://arxiv.org/pdf/1309.2375.pdf\n [3] https://arxiv.org/pdf/1502.03508.pdf\n [4] https://arxiv.org/pdf/1502.08053.pdf\n Details specific to this implementation are provided in:\n https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/canned/linear_optimizer/doc/sdca.ipynb\n \"\"\"\n\n def __init__(self,\n example_id_column,\n num_loss_partitions=1,\n num_table_shards=None,\n symmetric_l1_regularization=0.0,\n symmetric_l2_regularization=1.0,\n adaptive=False):\n \"\"\"Construct a new SDCA optimizer for linear estimators.\n\n Args:\n example_id_column: The column name containing the example ids.\n num_loss_partitions: Number of workers.\n num_table_shards: Number of shards of the internal state table, typically\n set to match the number of parameter servers.\n symmetric_l1_regularization: A float value, must be greater than or\n equal to zero.\n symmetric_l2_regularization: A float value, must be greater than zero and\n should typically be greater than 1.\n adaptive: A boolean indicating whether to use adaptive sampling.\n \"\"\"\n\n self._example_id_column = example_id_column\n self._num_loss_partitions = num_loss_partitions\n self._num_table_shards = num_table_shards\n self._symmetric_l1_regularization = symmetric_l1_regularization\n self._symmetric_l2_regularization = symmetric_l2_regularization\n self._adaptive = adaptive\n\n def _prune_and_unique_sparse_ids(self, id_weight_pair):\n \"\"\"Remove duplicate and negative ids in a sparse tendor.\"\"\"\n\n id_tensor = id_weight_pair.id_tensor\n if id_weight_pair.weight_tensor:\n weight_tensor = id_weight_pair.weight_tensor.values\n else:\n weight_tensor = array_ops.ones(\n [array_ops.shape(id_tensor.indices)[0]], dtypes.float32)\n\n example_ids = array_ops.reshape(id_tensor.indices[:, 0], [-1])\n flat_ids = math_ops.cast(\n array_ops.reshape(id_tensor.values, [-1]), dtype=dtypes.int64)\n # Prune invalid IDs (< 0) from the flat_ids, example_ids, and\n # weight_tensor. These can come from looking up an OOV entry in the\n # vocabulary (default value being -1).\n is_id_valid = math_ops.greater_equal(flat_ids, 0)\n flat_ids = array_ops.boolean_mask(flat_ids, is_id_valid)\n example_ids = array_ops.boolean_mask(example_ids, is_id_valid)\n weight_tensor = array_ops.boolean_mask(weight_tensor, is_id_valid)\n\n projection_length = math_ops.reduce_max(flat_ids) + 1\n # project ids based on example ids so that we can dedup ids that\n # occur multiple times for a single example.\n projected_ids = projection_length * example_ids + flat_ids\n\n # Remove any redundant ids.\n ids, idx = array_ops.unique(projected_ids)\n # Keep only one example id per duplicated ids.\n example_ids_filtered = math_ops.unsorted_segment_min(\n example_ids, idx,\n array_ops.shape(ids)[0])\n\n # reproject ids back feature id space.\n reproject_ids = (ids - projection_length * example_ids_filtered)\n\n weights = array_ops.reshape(\n math_ops.unsorted_segment_sum(weight_tensor, idx,\n array_ops.shape(ids)[0]), [-1])\n return sdca_ops._SparseFeatureColumn( # pylint: disable=protected-access\n example_ids_filtered, reproject_ids, weights)\n\n def get_train_step(self, state_manager, weight_column_name, loss_type,\n feature_columns, features, targets, bias_var, global_step):\n \"\"\"Returns the training operation of an SdcaModel optimizer.\"\"\"\n\n batch_size = array_ops.shape(targets)[0]\n cache = feature_column_lib.FeatureTransformationCache(features)\n\n # Iterate over all feature columns and create appropriate lists for dense\n # and sparse features as well as dense and sparse weights (variables) for\n # SDCA.\n dense_features, dense_feature_weights = [], []\n sparse_feature_with_values, sparse_feature_with_values_weights = [], []\n for column in sorted(feature_columns, key=lambda x: x.name):\n if isinstance(column, feature_column_lib.CategoricalColumn):\n id_weight_pair = column.get_sparse_tensors(cache, state_manager)\n sparse_feature_with_values.append(\n self._prune_and_unique_sparse_ids(id_weight_pair))\n # If a partitioner was used during variable creation, we will have a\n # list of Variables here larger than 1.\n sparse_feature_with_values_weights.append(\n state_manager.get_variable(column, 'weights'))\n elif isinstance(column, feature_column_lib.DenseColumn):\n if column.variable_shape.ndims != 1:\n raise ValueError('Column %s has rank %d, larger than 1.' % (\n type(column).__name__, column.variable_shape.ndims))\n dense_features.append(column.get_dense_tensor(cache, state_manager))\n # For real valued columns, the variables list contains exactly one\n # element.\n dense_feature_weights.append(\n state_manager.get_variable(column, 'weights'))\n else:\n raise ValueError('LinearSDCA does not support column type %s.' %\n type(column).__name__)\n\n # Add the bias column\n dense_features.append(array_ops.ones([batch_size, 1]))\n dense_feature_weights.append(bias_var)\n\n example_weights = array_ops.reshape(\n features[weight_column_name],\n shape=[-1]) if weight_column_name else array_ops.ones([batch_size])\n example_ids = features[self._example_id_column]\n training_examples = dict(\n sparse_features=sparse_feature_with_values,\n dense_features=dense_features,\n example_labels=math_ops.to_float(\n array_ops.reshape(targets, shape=[-1])),\n example_weights=example_weights,\n example_ids=example_ids)\n training_variables = dict(\n sparse_features_weights=sparse_feature_with_values_weights,\n dense_features_weights=dense_feature_weights)\n sdca_model = sdca_ops._SDCAModel( # pylint: disable=protected-access\n examples=training_examples,\n variables=training_variables,\n options=dict(\n symmetric_l1_regularization=self._symmetric_l1_regularization,\n symmetric_l2_regularization=self._symmetric_l2_regularization,\n adaptive=self._adaptive,\n num_loss_partitions=self._num_loss_partitions,\n num_table_shards=self._num_table_shards,\n loss_type=loss_type))\n train_op = sdca_model.minimize(global_step=global_step)\n return sdca_model, train_op\n\n\ndef _get_default_optimizer_v2(feature_columns):\n learning_rate = min(_LEARNING_RATE, 1.0 / math.sqrt(len(feature_columns)))\n return ftrl_v2.Ftrl(learning_rate=learning_rate)\n\n\ndef _get_default_optimizer(feature_columns):\n learning_rate = min(_LEARNING_RATE, 1.0 / math.sqrt(len(feature_columns)))\n return ftrl.FtrlOptimizer(learning_rate=learning_rate)\n\n\ndef _get_expanded_variable_list(var_list):\n \"\"\"Given an iterable of variables, expands them if they are partitioned.\n\n Args:\n var_list: An iterable of variables.\n\n Returns:\n A list of variables where each partitioned variable is expanded to its\n components.\n \"\"\"\n returned_list = []\n for variable in var_list:\n if (isinstance(variable, variable_ops.Variable) or\n resource_variable_ops.is_resource_variable(variable) or\n isinstance(variable, ops.Tensor)):\n returned_list.append(variable) # Single variable/tensor case.\n else: # Must be a PartitionedVariable, so convert into a list.\n returned_list.extend(list(variable))\n return returned_list\n\n\n# TODO(rohanj): Consider making this a public utility method.\ndef _compute_fraction_of_zero(variables):\n \"\"\"Given a linear variables list, compute the fraction of zero weights.\n\n Args:\n variables: A list or list of list of variables\n\n Returns:\n The fraction of zeros (sparsity) in the linear model.\n \"\"\"\n with ops.name_scope('zero_fraction'):\n variables = nest.flatten(variables)\n\n with ops.name_scope('total_size'):\n sizes = [array_ops.size(x, out_type=dtypes.int64) for x in variables]\n total_size_int64 = math_ops.add_n(sizes)\n with ops.name_scope('total_zero'):\n total_zero_float32 = math_ops.add_n([\n control_flow_ops.cond(\n math_ops.equal(size, constant_op.constant(0, dtype=dtypes.int64)),\n true_fn=lambda: constant_op.constant(0, dtype=dtypes.float32),\n false_fn=lambda: nn.zero_fraction(x) * math_ops.cast(\n size, dtype=dtypes.float32),\n name='zero_count') for x, size in zip(variables, sizes)\n ])\n\n with ops.name_scope('compute'):\n total_size_float32 = math_ops.cast(\n total_size_int64, dtype=dtypes.float32, name='float32_size')\n zero_fraction_or_nan = total_zero_float32 / total_size_float32\n\n zero_fraction_or_nan = array_ops.identity(\n zero_fraction_or_nan, name='zero_fraction_or_nan')\n return zero_fraction_or_nan\n\n\ndef linear_logit_fn_builder_v2(units, feature_columns, sparse_combiner='sum'):\n \"\"\"Function builder for a linear logit_fn.\n\n Args:\n units: An int indicating the dimension of the logit layer.\n feature_columns: An iterable containing all the feature columns used by\n the model.\n sparse_combiner: A string specifying how to reduce if a categorical column\n is multivalent. One of \"mean\", \"sqrtn\", and \"sum\".\n\n Returns:\n A logit_fn (see below).\n\n \"\"\"\n\n def linear_logit_fn(features):\n \"\"\"Linear model logit_fn.\n\n Args:\n features: This is the first item returned from the `input_fn`\n passed to `train`, `evaluate`, and `predict`. This should be a\n single `Tensor` or `dict` of same.\n\n Returns:\n A `Tensor` representing the logits.\n \"\"\"\n if not feature_column_lib.is_feature_column_v2(feature_columns):\n raise ValueError(\n 'Received a feature column from TensorFlow v1, but this is a '\n 'TensorFlow v2 Estimator. Please either use v2 feature columns '\n '(accessible via tf.feature_column.* in TF 2.x) with this '\n 'Estimator, or switch to a v1 Estimator for use with v1 feature '\n 'columns (accessible via tf.compat.v1.estimator.* and '\n 'tf.compat.v1.feature_column.*, respectively.')\n\n linear_model = feature_column_lib.LinearModel(\n feature_columns=feature_columns,\n units=units,\n sparse_combiner=sparse_combiner,\n name='linear_model')\n logits = linear_model(features)\n bias = linear_model.bias\n\n # We'd like to get all the non-bias variables associated with this\n # LinearModel.\n # TODO(rohanj): Figure out how to get shared embedding weights variable\n # here.\n variables = linear_model.variables\n variables.remove(bias)\n\n # Expand (potential) Partitioned variables\n bias = _get_expanded_variable_list([bias])\n variables = _get_expanded_variable_list(variables)\n\n if units > 1:\n summary.histogram('bias', bias)\n else:\n # If units == 1, the bias value is a length-1 list of a scalar Tensor,\n # so we should provide a scalar summary.\n summary.scalar('bias', bias[0][0])\n summary.scalar('fraction_of_zero_weights',\n _compute_fraction_of_zero(variables))\n return logits\n\n return linear_logit_fn\n\n\n@estimator_export(v1=['estimator.experimental.linear_logit_fn_builder'])\ndef linear_logit_fn_builder(units, feature_columns, sparse_combiner='sum'):\n \"\"\"Function builder for a linear logit_fn.\n\n Args:\n units: An int indicating the dimension of the logit layer.\n feature_columns: An iterable containing all the feature columns used by\n the model.\n sparse_combiner: A string specifying how to reduce if a categorical column\n is multivalent. One of \"mean\", \"sqrtn\", and \"sum\".\n\n Returns:\n A logit_fn (see below).\n\n \"\"\"\n\n def linear_logit_fn(features):\n \"\"\"Linear model logit_fn.\n\n Args:\n features: This is the first item returned from the `input_fn`\n passed to `train`, `evaluate`, and `predict`. This should be a\n single `Tensor` or `dict` of same.\n\n Returns:\n A `Tensor` representing the logits.\n \"\"\"\n if feature_column_lib.is_feature_column_v2(feature_columns):\n linear_model = feature_column_lib.LinearModel(\n feature_columns=feature_columns,\n units=units,\n sparse_combiner=sparse_combiner,\n name='linear_model')\n logits = linear_model(features)\n\n # We'd like to get all the non-bias variables associated with this\n # LinearModel.\n # TODO(rohanj): Figure out how to get shared embedding weights variable\n # here.\n bias = linear_model.bias\n variables = linear_model.variables\n # Expand (potential) Partitioned variables\n bias = _get_expanded_variable_list([bias])\n variables = _get_expanded_variable_list(variables)\n variables = [var for var in variables if var not in bias]\n\n # Expand (potential) Partitioned variables\n bias = _get_expanded_variable_list([bias])\n else:\n linear_model = feature_column._LinearModel( # pylint: disable=protected-access\n feature_columns=feature_columns,\n units=units,\n sparse_combiner=sparse_combiner,\n name='linear_model')\n logits = linear_model(features)\n cols_to_vars = linear_model.cols_to_vars()\n bias = cols_to_vars.pop('bias')\n variables = cols_to_vars.values()\n variables = _get_expanded_variable_list(variables)\n\n if units > 1:\n summary.histogram('bias', bias)\n else:\n # If units == 1, the bias value is a length-1 list of a scalar Tensor,\n # so we should provide a scalar summary.\n summary.scalar('bias', bias[0][0])\n summary.scalar('fraction_of_zero_weights',\n _compute_fraction_of_zero(variables))\n return logits\n\n return linear_logit_fn\n\n\ndef _sdca_model_fn(features, labels, mode, head, feature_columns, optimizer):\n \"\"\"A model_fn for linear models that use the SDCA optimizer.\n\n Args:\n features: dict of `Tensor`.\n labels: `Tensor` of shape `[batch_size]`.\n mode: Defines whether this is training, evaluation or prediction.\n See `ModeKeys`.\n head: A `Head` instance.\n feature_columns: An iterable containing all the feature columns used by\n the model.\n optimizer: a `LinearSDCA` instance.\n\n Returns:\n An `EstimatorSpec` instance.\n\n Raises:\n ValueError: mode or params are invalid, or features has the wrong type.\n \"\"\"\n assert feature_column_lib.is_feature_column_v2(feature_columns)\n if isinstance(head,\n (binary_class_head.BinaryClassHead,\n head_lib._BinaryLogisticHeadWithSigmoidCrossEntropyLoss)): # pylint: disable=protected-access\n loss_type = 'logistic_loss'\n elif isinstance(head, (regression_head.RegressionHead,\n head_lib._RegressionHeadWithMeanSquaredErrorLoss)): # pylint: disable=protected-access\n assert head.logits_dimension == 1\n loss_type = 'squared_loss'\n else:\n raise ValueError('Unsupported head type: {}'.format(head))\n\n # The default name for LinearModel.\n linear_model_name = 'linear_model'\n\n # Name scope has no effect on variables in LinearModel, as it uses\n # tf.get_variables() for variable creation. So we modify the model name to\n # keep the variable names the same for checkpoint backward compatibility in\n # canned Linear v2.\n if isinstance(head, (binary_class_head.BinaryClassHead,\n regression_head.RegressionHead)):\n linear_model_name = 'linear/linear_model'\n\n linear_model = feature_column_lib.LinearModel(\n feature_columns=feature_columns, units=1, sparse_combiner='sum',\n name=linear_model_name)\n logits = linear_model(features)\n\n # We'd like to get all the non-bias variables associated with this\n # LinearModel.\n # TODO(rohanj): Figure out how to get shared embedding weights variable\n # here.\n bias = linear_model.bias\n variables = linear_model.variables\n # Expand (potential) Partitioned variables\n bias = _get_expanded_variable_list([bias])\n variables = _get_expanded_variable_list(variables)\n variables = [var for var in variables if var not in bias]\n\n summary.scalar('bias', bias[0][0])\n summary.scalar('fraction_of_zero_weights',\n _compute_fraction_of_zero(variables))\n\n if mode == ModeKeys.TRAIN:\n sdca_model, train_op = optimizer.get_train_step(\n linear_model.layer._state_manager, # pylint: disable=protected-access\n head._weight_column, # pylint: disable=protected-access\n loss_type,\n feature_columns,\n features,\n labels,\n linear_model.bias,\n training.get_global_step())\n\n update_weights_hook = _SDCAUpdateWeightsHook(sdca_model, train_op)\n\n model_fn_ops = head.create_estimator_spec(\n features=features,\n mode=mode,\n labels=labels,\n train_op_fn=lambda unused_loss_fn: train_op,\n logits=logits)\n return model_fn_ops._replace(training_chief_hooks=(\n model_fn_ops.training_chief_hooks + (update_weights_hook,)))\n else:\n return head.create_estimator_spec(\n features=features,\n mode=mode,\n labels=labels,\n logits=logits)\n\n\nclass _SDCAUpdateWeightsHook(session_run_hook.SessionRunHook):\n \"\"\"SessionRunHook to update and shrink SDCA model weights.\"\"\"\n\n def __init__(self, sdca_model, train_op):\n self._sdca_model = sdca_model\n self._train_op = train_op\n\n def begin(self):\n \"\"\"Construct the update_weights op.\n\n The op is implicitly added to the default graph.\n \"\"\"\n self._update_op = self._sdca_model.update_weights(self._train_op)\n\n def before_run(self, run_context):\n \"\"\"Return the update_weights op so that it is executed during this run.\"\"\"\n return session_run_hook.SessionRunArgs(self._update_op)\n\n\ndef _linear_model_fn_builder_v2(units, feature_columns, sparse_combiner='sum',\n features=None):\n \"\"\"Function builder for a linear model_fn.\n\n Args:\n units: An int indicating the dimension of the logit layer.\n feature_columns: An iterable containing all the feature columns used by\n the model.\n sparse_combiner: A string specifying how to reduce if a categorical column\n is multivalent. One of \"mean\", \"sqrtn\", and \"sum\".\n features: This is the first item returned from the `input_fn`\n passed to `train`, `evaluate`, and `predict`. This should be a\n single `Tensor` or `dict` of same.\n\n Returns:\n A `Tensor` representing the logits.\n A list of trainable variables.\n\n \"\"\"\n if not feature_column_lib.is_feature_column_v2(feature_columns):\n raise ValueError(\n 'Received a feature column from TensorFlow v1, but this is a '\n 'TensorFlow v2 Estimator. Please either use v2 feature columns '\n '(accessible via tf.feature_column.* in TF 2.x) with this '\n 'Estimator, or switch to a v1 Estimator for use with v1 feature '\n 'columns (accessible via tf.compat.v1.estimator.* and '\n 'tf.compat.v1.feature_column.*, respectively.')\n\n # Name scope has no effect on variables in LinearModel, as it uses\n # tf.get_variables() for variable creation. So we modify the model name to\n # keep the variable names the same for checkpoint backward compatibility.\n linear_model = feature_column_lib.LinearModel(\n feature_columns=feature_columns,\n units=units,\n sparse_combiner=sparse_combiner,\n name='linear/linear_model')\n logits = linear_model(features)\n bias = linear_model.bias\n\n # We'd like to get all the non-bias variables associated with this\n # LinearModel.\n # TODO(rohanj): Figure out how to get shared embedding weights variable\n # here.\n variables = linear_model.variables\n variables.remove(bias)\n\n if units > 1:\n summary.histogram('bias', bias)\n else:\n # If units == 1, the bias value is a length-1 list of a scalar Tensor,\n # so we should provide a scalar summary.\n summary.scalar('bias', bias[0])\n summary.scalar('fraction_of_zero_weights',\n _compute_fraction_of_zero(variables))\n\n return logits, linear_model.variables\n\n\ndef _linear_model_fn_v2(features,\n labels,\n mode,\n head,\n feature_columns,\n optimizer,\n config,\n sparse_combiner='sum'):\n \"\"\"A model_fn for linear models that use a gradient-based optimizer.\n\n Args:\n features: dict of `Tensor`.\n labels: `Tensor` of shape `[batch_size, logits_dimension]`.\n mode: Defines whether this is training, evaluation or prediction. See\n `ModeKeys`.\n head: A `Head` instance.\n feature_columns: An iterable containing all the feature columns used by the\n model.\n optimizer: string, `Optimizer` object, or callable that defines the\n optimizer to use for training. If `None`, will use a FTRL optimizer.\n config: `RunConfig` object to configure the runtime settings.\n sparse_combiner: A string specifying how to reduce if a categorical column\n is multivalent. One of \"mean\", \"sqrtn\", and \"sum\".\n\n Returns:\n An `EstimatorSpec` instance.\n\n Raises:\n ValueError: mode or params are invalid, or features has the wrong type.\n \"\"\"\n if not isinstance(features, dict):\n raise ValueError('features should be a dictionary of `Tensor`s. '\n 'Given type: {}'.format(type(features)))\n\n del config\n\n if isinstance(optimizer, LinearSDCA):\n assert sparse_combiner == 'sum'\n return _sdca_model_fn(features, labels, mode, head, feature_columns,\n optimizer)\n else:\n logits, trainable_variables = _linear_model_fn_builder_v2(\n units=head.logits_dimension,\n feature_columns=feature_columns,\n sparse_combiner=sparse_combiner,\n features=features)\n\n # In TRAIN mode, create optimizer and assign global_step variable to\n # optimizer.iterations to make global_step increased correctly, as Hooks\n # relies on global step as step counter.\n if mode == ModeKeys.TRAIN:\n optimizer = optimizers.get_optimizer_instance_v2(\n optimizer or _get_default_optimizer_v2(feature_columns),\n learning_rate=_LEARNING_RATE)\n optimizer.iterations = training_util.get_or_create_global_step()\n\n return head.create_estimator_spec(\n features=features,\n mode=mode,\n labels=labels,\n optimizer=optimizer,\n trainable_variables=trainable_variables,\n logits=logits)\n\n\ndef _linear_model_fn(features, labels, mode, head, feature_columns, optimizer,\n partitioner, config, sparse_combiner='sum'):\n \"\"\"A model_fn for linear models that use a gradient-based optimizer.\n\n Args:\n features: dict of `Tensor`.\n labels: `Tensor` of shape `[batch_size, logits_dimension]`.\n mode: Defines whether this is training, evaluation or prediction.\n See `ModeKeys`.\n head: A `Head` instance.\n feature_columns: An iterable containing all the feature columns used by\n the model.\n optimizer: string, `Optimizer` object, or callable that defines the\n optimizer to use for training. If `None`, will use a FTRL optimizer.\n partitioner: Partitioner for variables.\n config: `RunConfig` object to configure the runtime settings.\n sparse_combiner: A string specifying how to reduce if a categorical column\n is multivalent. One of \"mean\", \"sqrtn\", and \"sum\".\n\n Returns:\n An `EstimatorSpec` instance.\n\n Raises:\n ValueError: mode or params are invalid, or features has the wrong type.\n \"\"\"\n if not isinstance(features, dict):\n raise ValueError('features should be a dictionary of `Tensor`s. '\n 'Given type: {}'.format(type(features)))\n\n num_ps_replicas = config.num_ps_replicas if config else 0\n\n partitioner = partitioner or (\n partitioned_variables.min_max_variable_partitioner(\n max_partitions=num_ps_replicas,\n min_slice_size=64 << 20))\n\n with variable_scope.variable_scope(\n 'linear',\n values=tuple(six.itervalues(features)),\n partitioner=partitioner):\n\n if isinstance(optimizer, LinearSDCA):\n assert sparse_combiner == 'sum'\n return _sdca_model_fn(\n features, labels, mode, head, feature_columns, optimizer)\n else:\n logit_fn = linear_logit_fn_builder(\n units=head.logits_dimension, feature_columns=feature_columns,\n sparse_combiner=sparse_combiner,\n )\n logits = logit_fn(features=features)\n\n optimizer = optimizers.get_optimizer_instance(\n optimizer or _get_default_optimizer(feature_columns),\n learning_rate=_LEARNING_RATE)\n\n return head.create_estimator_spec(\n features=features,\n mode=mode,\n labels=labels,\n optimizer=optimizer,\n logits=logits)\n\n\ndef _validate_linear_sdca_optimizer_for_linear_classifier(\n feature_columns,\n n_classes,\n optimizer,\n sparse_combiner):\n \"\"\"Helper function for the initialization of LinearClassifier.\"\"\"\n if isinstance(optimizer, LinearSDCA):\n if sparse_combiner != 'sum':\n raise ValueError('sparse_combiner must be \"sum\" when optimizer '\n 'is a LinearSDCA object.')\n if not feature_column_lib.is_feature_column_v2(feature_columns):\n raise ValueError('V2 feature columns required when optimizer '\n 'is a LinearSDCA object.')\n if n_classes > 2:\n raise ValueError('LinearSDCA cannot be used in a multi-class setting.')\n\n\n@estimator_export('estimator.LinearClassifier', v1=[])\nclass LinearClassifierV2(estimator.EstimatorV2):\n \"\"\"Linear classifier model.\n\n Train a linear model to classify instances into one of multiple possible\n classes. When number of possible classes is 2, this is binary classification.\n\n Example:\n\n ```python\n categorical_column_a = categorical_column_with_hash_bucket(...)\n categorical_column_b = categorical_column_with_hash_bucket(...)\n\n categorical_feature_a_x_categorical_feature_b = crossed_column(...)\n\n # Estimator using the default optimizer.\n estimator = tf.estimator.LinearClassifier(\n feature_columns=[categorical_column_a,\n categorical_feature_a_x_categorical_feature_b])\n\n # Or estimator using the FTRL optimizer with regularization.\n estimator = tf.estimator.LinearClassifier(\n feature_columns=[categorical_column_a,\n categorical_feature_a_x_categorical_feature_b],\n optimizer=tf.keras.optimizers.Ftrl(\n learning_rate=0.1,\n l1_regularization_strength=0.001\n ))\n\n # Or estimator using an optimizer with a learning rate decay.\n estimator = tf.estimator.LinearClassifier(\n feature_columns=[categorical_column_a,\n categorical_feature_a_x_categorical_feature_b],\n optimizer=lambda: tf.keras.optimizers.Ftrl(\n learning_rate=tf.exponential_decay(\n learning_rate=0.1,\n global_step=tf.get_global_step(),\n decay_steps=10000,\n decay_rate=0.96))\n\n # Or estimator with warm-starting from a previous checkpoint.\n estimator = tf.estimator.LinearClassifier(\n feature_columns=[categorical_column_a,\n categorical_feature_a_x_categorical_feature_b],\n warm_start_from=\"/path/to/checkpoint/dir\")\n\n\n # Input builders\n def input_fn_train:\n # Returns tf.data.Dataset of (x, y) tuple where y represents label's class\n # index.\n pass\n def input_fn_eval:\n # Returns tf.data.Dataset of (x, y) tuple where y represents label's class\n # index.\n pass\n def input_fn_predict:\n # Returns tf.data.Dataset of (x, None) tuple.\n pass\n estimator.train(input_fn=input_fn_train)\n metrics = estimator.evaluate(input_fn=input_fn_eval)\n predictions = estimator.predict(input_fn=input_fn_predict)\n ```\n\n Input of `train` and `evaluate` should have following features,\n otherwise there will be a `KeyError`:\n\n * if `weight_column` is not `None`, a feature with `key=weight_column` whose\n value is a `Tensor`.\n * for each `column` in `feature_columns`:\n - if `column` is a `SparseColumn`, a feature with `key=column.name`\n whose `value` is a `SparseTensor`.\n - if `column` is a `WeightedSparseColumn`, two features: the first with\n `key` the id column name, the second with `key` the weight column name.\n Both features' `value` must be a `SparseTensor`.\n - if `column` is a `RealValuedColumn`, a feature with `key=column.name`\n whose `value` is a `Tensor`.\n\n Loss is calculated by using softmax cross entropy.\n\n @compatibility(eager)\n Estimators can be used while eager execution is enabled. Note that `input_fn`\n and all hooks are executed inside a graph context, so they have to be written\n to be compatible with graph mode. Note that `input_fn` code using `tf.data`\n generally works in both graph and eager modes.\n @end_compatibility\n \"\"\"\n\n def __init__(self,\n feature_columns,\n model_dir=None,\n n_classes=2,\n weight_column=None,\n label_vocabulary=None,\n optimizer='Ftrl',\n config=None,\n warm_start_from=None,\n loss_reduction=losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE,\n sparse_combiner='sum'):\n \"\"\"Construct a `LinearClassifier` estimator object.\n\n Args:\n feature_columns: An iterable containing all the feature columns used by\n the model. All items in the set should be instances of classes derived\n from `FeatureColumn`.\n model_dir: Directory to save model parameters, graph and etc. This can\n also be used to load checkpoints from the directory into a estimator\n to continue training a previously saved model.\n n_classes: number of label classes. Default is binary classification.\n Note that class labels are integers representing the class index (i.e.\n values from 0 to n_classes-1). For arbitrary label values (e.g. string\n labels), convert to class indices first.\n weight_column: A string or a `_NumericColumn` created by\n `tf.feature_column.numeric_column` defining feature column representing\n weights. It is used to down weight or boost examples during training. It\n will be multiplied by the loss of the example. If it is a string, it is\n used as a key to fetch weight tensor from the `features`. If it is a\n `_NumericColumn`, raw tensor is fetched by key `weight_column.key`,\n then weight_column.normalizer_fn is applied on it to get weight tensor.\n label_vocabulary: A list of strings represents possible label values. If\n given, labels must be string type and have any value in\n `label_vocabulary`. If it is not given, that means labels are\n already encoded as integer or float within [0, 1] for `n_classes=2` and\n encoded as integer values in {0, 1,..., n_classes-1} for `n_classes`>2 .\n Also there will be errors if vocabulary is not provided and labels are\n string.\n optimizer: An instance of `tf.keras.optimizers.*` or\n `tf.estimator.experimental.LinearSDCA` used to train the model. Can\n also be a string (one of 'Adagrad', 'Adam', 'Ftrl', 'RMSProp', 'SGD'),\n or callable. Defaults to FTRL optimizer.\n config: `RunConfig` object to configure the runtime settings.\n warm_start_from: A string filepath to a checkpoint to warm-start from, or\n a `WarmStartSettings` object to fully configure warm-starting. If the\n string filepath is provided instead of a `WarmStartSettings`, then all\n weights and biases are warm-started, and it is assumed that vocabularies\n and Tensor names are unchanged.\n loss_reduction: One of `tf.losses.Reduction` except `NONE`. Describes how\n to reduce training loss over batch. Defaults to `SUM_OVER_BATCH_SIZE`.\n sparse_combiner: A string specifying how to reduce if a categorical column\n is multivalent. One of \"mean\", \"sqrtn\", and \"sum\" -- these are\n effectively different ways to do example-level normalization, which can\n be useful for bag-of-words features. for more details, see\n `tf.feature_column.linear_model`.\n\n Returns:\n A `LinearClassifier` estimator.\n\n Raises:\n ValueError: if n_classes < 2.\n \"\"\"\n _validate_linear_sdca_optimizer_for_linear_classifier(\n feature_columns=feature_columns,\n n_classes=n_classes,\n optimizer=optimizer,\n sparse_combiner=sparse_combiner)\n estimator._canned_estimator_api_gauge.get_cell('Classifier').set('Linear') # pylint: disable=protected-access\n\n head = head_utils.binary_or_multi_class_head(\n n_classes, weight_column=weight_column,\n label_vocabulary=label_vocabulary,\n loss_reduction=loss_reduction)\n\n def _model_fn(features, labels, mode, config):\n \"\"\"Call the defined shared _linear_model_fn.\"\"\"\n return _linear_model_fn_v2(\n features=features,\n labels=labels,\n mode=mode,\n head=head,\n feature_columns=tuple(feature_columns or []),\n optimizer=optimizer,\n config=config,\n sparse_combiner=sparse_combiner)\n\n super(LinearClassifierV2, self).__init__(\n model_fn=_model_fn,\n model_dir=model_dir,\n config=config,\n warm_start_from=warm_start_from)\n\n\n@estimator_export(v1=['estimator.LinearClassifier']) # pylint: disable=missing-docstring\nclass LinearClassifier(estimator.Estimator):\n __doc__ = LinearClassifierV2.__doc__.replace('SUM_OVER_BATCH_SIZE', 'SUM')\n\n def __init__(self,\n feature_columns,\n model_dir=None,\n n_classes=2,\n weight_column=None,\n label_vocabulary=None,\n optimizer='Ftrl',\n config=None,\n partitioner=None,\n warm_start_from=None,\n loss_reduction=losses.Reduction.SUM,\n sparse_combiner='sum'):\n _validate_linear_sdca_optimizer_for_linear_classifier(\n feature_columns=feature_columns,\n n_classes=n_classes,\n optimizer=optimizer,\n sparse_combiner=sparse_combiner)\n estimator._canned_estimator_api_gauge.get_cell('Classifier').set('Linear') # pylint: disable=protected-access\n\n head = head_lib._binary_logistic_or_multi_class_head( # pylint: disable=protected-access\n n_classes, weight_column, label_vocabulary, loss_reduction)\n\n def _model_fn(features, labels, mode, config):\n \"\"\"Call the defined shared _linear_model_fn.\"\"\"\n return _linear_model_fn(\n features=features,\n labels=labels,\n mode=mode,\n head=head,\n feature_columns=tuple(feature_columns or []),\n optimizer=optimizer,\n partitioner=partitioner,\n config=config,\n sparse_combiner=sparse_combiner)\n\n super(LinearClassifier, self).__init__(\n model_fn=_model_fn,\n model_dir=model_dir,\n config=config,\n warm_start_from=warm_start_from)\n\n\n@estimator_export('estimator.LinearEstimator', v1=[])\nclass LinearEstimatorV2(estimator.EstimatorV2):\n \"\"\"An estimator for TensorFlow linear models with user-specified head.\n\n Example:\n\n ```python\n categorical_column_a = categorical_column_with_hash_bucket(...)\n categorical_column_b = categorical_column_with_hash_bucket(...)\n\n categorical_feature_a_x_categorical_feature_b = crossed_column(...)\n\n # Estimator using the default optimizer.\n estimator = tf.estimator.LinearEstimator(\n head=tf.estimator.MultiLabelHead(n_classes=3),\n feature_columns=[categorical_column_a,\n categorical_feature_a_x_categorical_feature_b])\n\n # Or estimator using an optimizer with a learning rate decay.\n estimator = tf.estimator.LinearEstimator(\n head=tf.estimator.MultiLabelHead(n_classes=3),\n feature_columns=[categorical_column_a,\n categorical_feature_a_x_categorical_feature_b],\n optimizer=lambda: tf.keras.optimizers.Ftrl(\n learning_rate=tf.compat.v1.train.exponential_decay(\n learning_rate=0.1,\n global_step=tf.compat.v1.train.get_global_step(),\n decay_steps=10000,\n decay_rate=0.96))\n\n # Or estimator using the FTRL optimizer with regularization.\n estimator = LinearEstimator(\n head=tf.contrib.estimator.multi_label_head(n_classes=3),\n feature_columns=[categorical_column_a,\n categorical_feature_a_x_categorical_feature_b])\n optimizer=tf.keras.optimizers.Ftrl(\n learning_rate=0.1,\n l1_regularization_strength=0.001\n ))\n\n def input_fn_train:\n # Returns tf.data.Dataset of (x, y) tuple where y represents label's class\n # index.\n pass\n def input_fn_eval:\n # Returns tf.data.Dataset of (x, y) tuple where y represents label's class\n # index.\n pass\n def input_fn_predict:\n # Returns tf.data.Dataset of (x, None) tuple.\n pass\n estimator.train(input_fn=input_fn_train, steps=100)\n metrics = estimator.evaluate(input_fn=input_fn_eval, steps=10)\n predictions = estimator.predict(input_fn=input_fn_predict)\n ```\n\n Input of `train` and `evaluate` should have following features,\n otherwise there will be a `KeyError`:\n\n * if `weight_column` is not `None`, a feature with `key=weight_column` whose\n value is a `Tensor`.\n * for each `column` in `feature_columns`:\n - if `column` is a `CategoricalColumn`, a feature with `key=column.name`\n whose `value` is a `SparseTensor`.\n - if `column` is a `WeightedCategoricalColumn`, two features: the first\n with `key` the id column name, the second with `key` the weight column\n name. Both features' `value` must be a `SparseTensor`.\n - if `column` is a `DenseColumn`, a feature with `key=column.name`\n whose `value` is a `Tensor`.\n\n Loss and predicted output are determined by the specified head.\n\n @compatibility(eager)\n Estimators can be used while eager execution is enabled. Note that `input_fn`\n and all hooks are executed inside a graph context, so they have to be written\n to be compatible with graph mode. Note that `input_fn` code using `tf.data`\n generally works in both graph and eager modes.\n @end_compatibility\n \"\"\"\n\n def __init__(self,\n head,\n feature_columns,\n model_dir=None,\n optimizer='Ftrl',\n config=None,\n sparse_combiner='sum'):\n \"\"\"Initializes a `LinearEstimator` instance.\n\n Args:\n head: A `Head` instance constructed with a method such as\n `tf.estimator.MultiLabelHead`.\n feature_columns: An iterable containing all the feature columns used by\n the model. All items in the set should be instances of classes derived\n from `FeatureColumn`.\n model_dir: Directory to save model parameters, graph and etc. This can\n also be used to load checkpoints from the directory into a estimator\n to continue training a previously saved model.\n optimizer: An instance of `tf.keras.optimizers.*` used to train the model.\n Can also be a string (one of 'Adagrad', 'Adam', 'Ftrl', 'RMSProp',\n 'SGD'), or callable. Defaults to FTRL optimizer.\n config: `RunConfig` object to configure the runtime settings.\n sparse_combiner: A string specifying how to reduce if a categorical column\n is multivalent. One of \"mean\", \"sqrtn\", and \"sum\" -- these are\n effectively different ways to do example-level normalization, which can\n be useful for bag-of-words features. for more details, see\n `tf.feature_column.linear_model`.\n \"\"\"\n def _model_fn(features, labels, mode, config):\n return _linear_model_fn_v2(\n features=features,\n labels=labels,\n mode=mode,\n head=head,\n feature_columns=tuple(feature_columns or []),\n optimizer=optimizer,\n config=config,\n sparse_combiner=sparse_combiner)\n\n estimator._canned_estimator_api_gauge.get_cell('Estimator').set('Linear') # pylint: disable=protected-access\n super(LinearEstimatorV2, self).__init__(\n model_fn=_model_fn, model_dir=model_dir, config=config)\n\n\n@estimator_export(v1=['estimator.LinearEstimator']) # pylint: disable=missing-docstring\nclass LinearEstimator(estimator.Estimator):\n __doc__ = LinearEstimatorV2.__doc__\n\n def __init__(self,\n head,\n feature_columns,\n model_dir=None,\n optimizer='Ftrl',\n config=None,\n partitioner=None,\n sparse_combiner='sum'):\n \"\"\"Initializes a `LinearEstimator` instance.\n\n Args:\n head: A `_Head` instance constructed with a method such as\n `tf.contrib.estimator.multi_label_head`.\n feature_columns: An iterable containing all the feature columns used by\n the model. All items in the set should be instances of classes derived\n from `FeatureColumn`.\n model_dir: Directory to save model parameters, graph and etc. This can\n also be used to load checkpoints from the directory into a estimator\n to continue training a previously saved model.\n optimizer: An instance of `tf.Optimizer` used to train the model. Can also\n be a string (one of 'Adagrad', 'Adam', 'Ftrl', 'RMSProp', 'SGD'), or\n callable. Defaults to FTRL optimizer.\n config: `RunConfig` object to configure the runtime settings.\n partitioner: Optional. Partitioner for input layer.\n sparse_combiner: A string specifying how to reduce if a categorical column\n is multivalent. One of \"mean\", \"sqrtn\", and \"sum\" -- these are\n effectively different ways to do example-level normalization, which can\n be useful for bag-of-words features. for more details, see\n `tf.feature_column.linear_model`.\n \"\"\"\n def _model_fn(features, labels, mode, config):\n return _linear_model_fn(\n features=features,\n labels=labels,\n mode=mode,\n head=head,\n feature_columns=tuple(feature_columns or []),\n optimizer=optimizer,\n partitioner=partitioner,\n config=config,\n sparse_combiner=sparse_combiner)\n\n estimator._canned_estimator_api_gauge.get_cell('Estimator').set('Linear') # pylint: disable=protected-access\n super(LinearEstimator, self).__init__(\n model_fn=_model_fn, model_dir=model_dir, config=config)\n\n\ndef _validate_linear_sdca_optimizer_for_linear_regressor(\n feature_columns,\n label_dimension,\n optimizer,\n sparse_combiner):\n \"\"\"Helper function for the initialization of LinearRegressor.\"\"\"\n if isinstance(optimizer, LinearSDCA):\n if sparse_combiner != 'sum':\n raise ValueError('sparse_combiner must be \"sum\" when optimizer '\n 'is a LinearSDCA object.')\n if not feature_column_lib.is_feature_column_v2(feature_columns):\n raise ValueError('V2 feature columns required when optimizer '\n 'is a LinearSDCA object.')\n if label_dimension > 1:\n raise ValueError('LinearSDCA can only be used with one-dimensional '\n 'label.')\n\n\n@estimator_export('estimator.LinearRegressor', v1=[])\nclass LinearRegressorV2(estimator.EstimatorV2):\n \"\"\"An estimator for TensorFlow Linear regression problems.\n\n Train a linear regression model to predict label value given observation of\n feature values.\n\n Example:\n\n ```python\n categorical_column_a = categorical_column_with_hash_bucket(...)\n categorical_column_b = categorical_column_with_hash_bucket(...)\n\n categorical_feature_a_x_categorical_feature_b = crossed_column(...)\n\n # Estimator using the default optimizer.\n estimator = tf.estimator.LinearRegressor(\n feature_columns=[categorical_column_a,\n categorical_feature_a_x_categorical_feature_b])\n\n # Or estimator using the FTRL optimizer with regularization.\n estimator = tf.estimator.LinearRegressor(\n feature_columns=[categorical_column_a,\n categorical_feature_a_x_categorical_feature_b],\n optimizer=tf.keras.optimizers.Ftrl(\n learning_rate=0.1,\n l1_regularization_strength=0.001\n ))\n\n # Or estimator using an optimizer with a learning rate decay.\n estimator = tf.estimator.LinearRegressor(\n feature_columns=[categorical_column_a,\n categorical_feature_a_x_categorical_feature_b],\n optimizer=lambda: tf.keras.optimizers.Ftrl(\n learning_rate=tf.compat.v1.train.exponential_decay(\n learning_rate=0.1,\n global_step=tf.compat.v1.train.get_global_step(),\n decay_steps=10000,\n decay_rate=0.96))\n\n # Or estimator with warm-starting from a previous checkpoint.\n estimator = tf.estimator.LinearRegressor(\n feature_columns=[categorical_column_a,\n categorical_feature_a_x_categorical_feature_b],\n warm_start_from=\"/path/to/checkpoint/dir\")\n\n\n # Input builders\n def input_fn_train:\n # Returns tf.data.Dataset of (x, y) tuple where y represents label's class\n # index.\n pass\n def input_fn_eval:\n # Returns tf.data.Dataset of (x, y) tuple where y represents label's class\n # index.\n pass\n def input_fn_predict:\n # Returns tf.data.Dataset of (x, None) tuple.\n pass\n estimator.train(input_fn=input_fn_train)\n metrics = estimator.evaluate(input_fn=input_fn_eval)\n predictions = estimator.predict(input_fn=input_fn_predict)\n ```\n\n Input of `train` and `evaluate` should have following features,\n otherwise there will be a KeyError:\n\n * if `weight_column` is not `None`, a feature with `key=weight_column` whose\n value is a `Tensor`.\n * for each `column` in `feature_columns`:\n - if `column` is a `SparseColumn`, a feature with `key=column.name`\n whose `value` is a `SparseTensor`.\n - if `column` is a `WeightedSparseColumn`, two features: the first with\n `key` the id column name, the second with `key` the weight column name.\n Both features' `value` must be a `SparseTensor`.\n - if `column` is a `RealValuedColumn`, a feature with `key=column.name`\n whose `value` is a `Tensor`.\n\n Loss is calculated by using mean squared error.\n\n @compatibility(eager)\n Estimators can be used while eager execution is enabled. Note that `input_fn`\n and all hooks are executed inside a graph context, so they have to be written\n to be compatible with graph mode. Note that `input_fn` code using `tf.data`\n generally works in both graph and eager modes.\n @end_compatibility\n \"\"\"\n\n def __init__(self,\n feature_columns,\n model_dir=None,\n label_dimension=1,\n weight_column=None,\n optimizer='Ftrl',\n config=None,\n warm_start_from=None,\n loss_reduction=losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE,\n sparse_combiner='sum'):\n \"\"\"Initializes a `LinearRegressor` instance.\n\n Args:\n feature_columns: An iterable containing all the feature columns used by\n the model. All items in the set should be instances of classes derived\n from `FeatureColumn`.\n model_dir: Directory to save model parameters, graph and etc. This can\n also be used to load checkpoints from the directory into a estimator to\n continue training a previously saved model.\n label_dimension: Number of regression targets per example. This is the\n size of the last dimension of the labels and logits `Tensor` objects\n (typically, these have shape `[batch_size, label_dimension]`).\n weight_column: A string or a `NumericColumn` created by\n `tf.feature_column.numeric_column` defining feature column representing\n weights. It is used to down weight or boost examples during training. It\n will be multiplied by the loss of the example. If it is a string, it is\n used as a key to fetch weight tensor from the `features`. If it is a\n `NumericColumn`, raw tensor is fetched by key `weight_column.key`, then\n weight_column.normalizer_fn is applied on it to get weight tensor.\n optimizer: An instance of `tf.keras.optimizers.*` or\n `tf.estimator.experimental.LinearSDCA` used to train the model. Can also\n be a string (one of 'Adagrad', 'Adam', 'Ftrl', 'RMSProp', 'SGD'), or\n callable. Defaults to FTRL optimizer.\n config: `RunConfig` object to configure the runtime settings.\n warm_start_from: A string filepath to a checkpoint to warm-start from, or\n a `WarmStartSettings` object to fully configure warm-starting. If the\n string filepath is provided instead of a `WarmStartSettings`, then all\n weights and biases are warm-started, and it is assumed that vocabularies\n and Tensor names are unchanged.\n loss_reduction: One of `tf.losses.Reduction` except `NONE`. Describes how\n to reduce training loss over batch. Defaults to `SUM`.\n sparse_combiner: A string specifying how to reduce if a categorical column\n is multivalent. One of \"mean\", \"sqrtn\", and \"sum\" -- these are\n effectively different ways to do example-level normalization, which can\n be useful for bag-of-words features. for more details, see\n `tf.feature_column.linear_model`.\n \"\"\"\n _validate_linear_sdca_optimizer_for_linear_regressor(\n feature_columns=feature_columns,\n label_dimension=label_dimension,\n optimizer=optimizer,\n sparse_combiner=sparse_combiner)\n\n head = regression_head.RegressionHead(\n label_dimension=label_dimension,\n weight_column=weight_column,\n loss_reduction=loss_reduction)\n estimator._canned_estimator_api_gauge.get_cell('Regressor').set('Linear') # pylint: disable=protected-access\n\n def _model_fn(features, labels, mode, config):\n \"\"\"Call the defined shared _linear_model_fn.\"\"\"\n return _linear_model_fn_v2(\n features=features,\n labels=labels,\n mode=mode,\n head=head,\n feature_columns=tuple(feature_columns or []),\n optimizer=optimizer,\n config=config,\n sparse_combiner=sparse_combiner)\n\n super(LinearRegressorV2, self).__init__(\n model_fn=_model_fn,\n model_dir=model_dir,\n config=config,\n warm_start_from=warm_start_from)\n\n\n@estimator_export(v1=['estimator.LinearRegressor']) # pylint: disable=missing-docstring\nclass LinearRegressor(estimator.Estimator):\n __doc__ = LinearRegressorV2.__doc__.replace('SUM_OVER_BATCH_SIZE', 'SUM')\n\n def __init__(self,\n feature_columns,\n model_dir=None,\n label_dimension=1,\n weight_column=None,\n optimizer='Ftrl',\n config=None,\n partitioner=None,\n warm_start_from=None,\n loss_reduction=losses.Reduction.SUM,\n sparse_combiner='sum'):\n _validate_linear_sdca_optimizer_for_linear_regressor(\n feature_columns=feature_columns,\n label_dimension=label_dimension,\n optimizer=optimizer,\n sparse_combiner=sparse_combiner)\n\n head = head_lib._regression_head( # pylint: disable=protected-access\n label_dimension=label_dimension,\n weight_column=weight_column,\n loss_reduction=loss_reduction)\n estimator._canned_estimator_api_gauge.get_cell('Regressor').set('Linear') # pylint: disable=protected-access\n\n def _model_fn(features, labels, mode, config):\n \"\"\"Call the defined shared _linear_model_fn.\"\"\"\n return _linear_model_fn(\n features=features,\n labels=labels,\n mode=mode,\n head=head,\n feature_columns=tuple(feature_columns or []),\n optimizer=optimizer,\n partitioner=partitioner,\n config=config,\n sparse_combiner=sparse_combiner)\n\n super(LinearRegressor, self).__init__(\n model_fn=_model_fn,\n model_dir=model_dir,\n config=config,\n warm_start_from=warm_start_from)\n"
] |
[
[
"tensorflow.python.keras.optimizer_v2.ftrl.Ftrl",
"tensorflow.python.ops.math_ops.greater_equal",
"tensorflow.python.ops.array_ops.shape",
"tensorflow.python.ops.math_ops.reduce_max",
"tensorflow.python.summary.summary.scalar",
"tensorflow.python.summary.summary.histogram",
"tensorflow.python.feature_column.feature_column._LinearModel",
"tensorflow.python.training.ftrl.FtrlOptimizer",
"tensorflow.python.ops.nn.zero_fraction",
"tensorflow.python.ops.array_ops.identity",
"tensorflow.python.training.training.get_global_step",
"tensorflow.python.util.tf_export.estimator_export",
"tensorflow.python.feature_column.feature_column_lib.FeatureTransformationCache",
"tensorflow.python.ops.array_ops.size",
"tensorflow.python.ops.array_ops.ones",
"tensorflow.python.ops.array_ops.unique",
"tensorflow.python.ops.math_ops.cast",
"tensorflow.python.feature_column.feature_column_lib.is_feature_column_v2",
"tensorflow.python.ops.math_ops.add_n",
"tensorflow.python.training.training_util.get_or_create_global_step",
"tensorflow.python.ops.array_ops.reshape",
"tensorflow.python.framework.ops.name_scope",
"tensorflow.python.ops.partitioned_variables.min_max_variable_partitioner",
"tensorflow.python.feature_column.feature_column_lib.LinearModel",
"tensorflow.python.ops.array_ops.boolean_mask",
"tensorflow.python.ops.resource_variable_ops.is_resource_variable",
"tensorflow.python.training.session_run_hook.SessionRunArgs",
"tensorflow.python.util.nest.flatten",
"tensorflow.python.framework.constant_op.constant"
]
] |
SAP-samples/dwc-fedml
|
[
"39ea8cefc31741c4ec37eb6c0d70dd48e7c034ba"
] |
[
"Azure/sample-notebooks/LinearRegression/Scikit-Learn-Linear-Regression/train_script.py"
] |
[
"import os\nimport time\nimport pandas as pd\nimport argparse\nfrom sklearn import __version__ as sklearnver\nimport joblib\n\nfrom sklearn.linear_model import LinearRegression\nimport numpy as np\nfrom fedml_azure import DbConnection\nfrom sklearn.model_selection import train_test_split\nimport json\n\n\n# https://eforexcel.com/wp/downloads-18-sample-csv-files-data-sets-for-testing-sales/\n############################## Global variables ##############################\nwith open('config.json', 'r') as f:\n config = json.load(f)\n \nfeature_columns_names = [\n 'Units_Sold', 'Unit_Price', 'Unit_Cost',\n 'Total_Revenue', 'Total_Cost']\n\nlabel_column = 'Total_Profit'\n\nfeature_columns_dtype = {\n 'Units_Sold': \"int64\",\n 'Unit_Price': \"float64\",\n 'Unit_Cost': \"float64\",\n 'Total_Revenue': \"float64\",\n 'Total_Cost': \"float64\"}\n\nlabel_column_dtype = {'Total_Profit': \"float64\"}\n\n############################## Helper Functions ##############################\ndef get_data(table_name):\n db = DbConnection()\n start_time = time.time()\n query='select * from '+config['schema']+'.'+table_name\n data = db.execute_query(query)\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n data = pd.DataFrame(data[0], columns=data[1])\n data = data[['Units_Sold', 'Unit_Price', 'Unit_Cost', 'Total_Revenue', 'Total_Cost', 'Total_Profit']]\n return data\n\n############################## Required Functions ##############################\ndef store_model(model_file_name,model_output):\n print('storing the model....')\n os.makedirs('./outputs', exist_ok=True)\n with open(model_file_name, 'wb') as file:\n joblib.dump(value=model_output, filename='outputs/' + model_file_name)\n\n############################## Training Script Part ##############################\n\nparser = argparse.ArgumentParser()\n\n# AzureML specific arguments. Defaults are set in the environment variables.\nparser.add_argument('--model_file_name', type=str)\nparser.add_argument('--table_name', type=str)\n\nargs = parser.parse_args()\n\nprint('\\n\\n********* Handling Data - Splitting into Train and Test *********n\\n')\ndata = get_data(args.table_name) #getting data from DWC\ny = data[label_column]\n\ndata.drop(label_column, axis=1, inplace=True)\n\nprint(np.shape(data), np.shape(y))\n\nX_train, X_test, y_train, y_test = train_test_split(data, y, test_size=0.3)\n\nprint('\\n\\n****************************X_train and X_test****************************\\n\\n')\nprint(X_train)\nprint('\\n\\n')\nprint(X_test)\n\nprint('\\n\\n****************************y_train and y_test****************************\\n\\n')\nprint(y_train)\nprint('\\n\\n')\nprint(y_test)\n\n#Train the LinearRegression model using the fit method\nmodel = LinearRegression().fit(X_train, y_train)\n\nscore = model.score(X_test, y_test)\n\nprint('\\n\\n\\nScore for fit: ' + str(score) + '\\n\\n')\n\n#Save the model to the location specified by args.model_dir\nstore_model(args.model_file_name,model)\n\nprint(\"saved model!\")\n"
] |
[
[
"sklearn.linear_model.LinearRegression",
"numpy.shape",
"sklearn.model_selection.train_test_split",
"pandas.DataFrame"
]
] |
dfm/mapping_stellar_surfaces
|
[
"52d4ba1a726c65868e4a1290a801fe046fb2155f"
] |
[
"paper2/figures/latitude_pdf.py"
] |
[
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom starry_process import StarryProcess, gauss2beta, beta2gauss\nimport theano\nimport theano.tensor as tt\nfrom scipy.stats import norm\nimport os\n\nphi = np.linspace(-90, 90, 1000)\na = tt.dscalar()\nb = tt.dscalar()\npdf = theano.function([a, b], StarryProcess(a=a, b=b).latitude.pdf(phi))\n\npdf_gauss = lambda mu, sig: 0.5 * (\n norm.pdf(phi, mu, sig) + norm.pdf(phi, -mu, sig)\n)\n\nsig = [1, 5, 10, 40]\nmu = [0, 30, 60, 85]\n\nfig, ax = plt.subplots(len(mu), len(sig), figsize=(12, 8), sharex=True)\n\n\nfor i in range(len(sig)):\n for j in range(len(mu)):\n ax[i, j].plot(phi, pdf(*gauss2beta(mu[j], sig[i])), \"C0-\")\n\n if mu[j] == 0 and sig[i] == 40:\n ax[i, j].plot(\n phi, 0.5 * np.pi / 180 * np.cos(phi * np.pi / 180), \"C1--\"\n )\n ax[i, j].set_facecolor(\"#1f77b422\")\n else:\n ax[i, j].plot(phi, pdf_gauss(mu[j], sig[i]), \"C1--\", lw=1)\n\n ax[i, j].annotate(\n r\"$a = {:.2f}$\".format(gauss2beta(mu[j], sig[i])[0])\n + \"\\n\"\n + r\"$b = {:.2f}$\".format(gauss2beta(mu[j], sig[i])[1]),\n xy=(0, 1),\n xytext=(5, -5),\n xycoords=\"axes fraction\",\n textcoords=\"offset points\",\n va=\"top\",\n ha=\"left\",\n fontsize=7,\n )\n\nfor i in range(len(sig)):\n ax[i, 0].get_shared_y_axes().join(*ax[i])\n for j in range(1, len(mu)):\n ax[i, j].set_yticklabels([])\n ax[i, 0].set_ylabel(\"probability density\", fontsize=8)\n for tick in ax[i, 0].yaxis.get_major_ticks():\n tick.label.set_fontsize(8)\n ax[i, 0].annotate(\n r\"$\\sigma_\\phi = {}^\\circ$\".format(sig[i]),\n xy=(0, 0.5),\n xytext=(-55, 0),\n xycoords=\"axes fraction\",\n textcoords=\"offset points\",\n va=\"center\",\n ha=\"right\",\n fontsize=18,\n clip_on=False,\n rotation=90,\n )\n\nfor j in range(len(mu)):\n xticks = [-90, -60, -30, 0, 30, 60, 90]\n ax[-1, j].set_xticks(xticks)\n ax[-1, j].set_xticklabels(\n [r\"{}$^\\circ$\".format(abs(tick)) for tick in xticks]\n )\n ax[-1, j].set_xlabel(\"latitude\", fontsize=10)\n for tick in ax[-1, j].xaxis.get_major_ticks():\n tick.label.set_fontsize(8)\n\n ax[0, j].set_title(\n r\"$\\mu_\\phi = {}^\\circ$\".format(mu[j]), fontsize=18, y=1.05\n )\n\nfor axis in ax.flatten():\n axis.margins(0, None)\n\nfig.align_ylabels(ax[:, 0])\n\n# We're done\nfig.savefig(\n os.path.abspath(__file__).replace(\".py\", \".pdf\"), bbox_inches=\"tight\"\n)\n"
] |
[
[
"scipy.stats.norm.pdf",
"numpy.cos",
"numpy.linspace"
]
] |
quic-sendilk/aimet
|
[
"c6ffd3c31c290fe0913b50831d58534f6df61d76"
] |
[
"TrainingExtensions/torch/test/python/test_utils.py"
] |
[
"# /usr/bin/env python3.5\n# -*- mode: python -*-\n# =============================================================================\n# @@-COPYRIGHT-START-@@\n#\n# Copyright (c) 2017-2018, Qualcomm Innovation Center, Inc. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its contributors\n# may be used to endorse or promote products derived from this software\n# without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n# SPDX-License-Identifier: BSD-3-Clause\n#\n# @@-COPYRIGHT-END-@@\n# =============================================================================\n\nimport unittest.mock\n\nimport torch\nimport torchvision\n\nfrom aimet_common.utils import round_up_to_multiplicity, round_down_to_multiplicity\nfrom aimet_torch.utils import replace_modules_of_type1_with_type2, replace_modules_with_instances_of_new_type, \\\n get_ordered_list_of_modules, get_ordered_list_of_conv_modules, get_reused_modules, change_tensor_device_placement\nfrom aimet_torch.defs import PassThroughOp\nfrom aimet_torch.examples.test_models import ModelWithReusedNodes\n\n\nclass TestTrainingExtensionsUtils(unittest.TestCase):\n\n def test_round_up_to_higher_multiplicity(self):\n self.assertEqual(round_up_to_multiplicity(8, 3, 32), 8)\n self.assertEqual(round_up_to_multiplicity(8, 13, 32), 16)\n self.assertEqual(round_up_to_multiplicity(8, 17, 32), 24)\n self.assertEqual(round_up_to_multiplicity(8, 29, 32), 32)\n\n def test_round_down_to_lower_multiplicity(self):\n self.assertEqual(round_down_to_multiplicity(8, 3), 3)\n self.assertEqual(round_down_to_multiplicity(8, 13), 8)\n self.assertEqual(round_down_to_multiplicity(8, 17), 16)\n self.assertEqual(round_down_to_multiplicity(8, 29), 24)\n self.assertEqual(round_down_to_multiplicity(8, 16), 8)\n self.assertEqual(round_down_to_multiplicity(32, 64), 32)\n\n def test_replace_relu_with_relu6(self):\n model = torchvision.models.resnet18()\n model.eval()\n\n replace_modules_of_type1_with_type2(model, torch.nn.ReLU, torch.nn.ReLU6)\n\n # check - no ReLU modules left in the model anymore\n for module in model.modules():\n self.assertTrue(not isinstance(module, torch.nn.ReLU))\n\n # sanity-check: forward pass continues to work\n with torch.no_grad():\n x = torch.rand(1, 3, 224, 224)\n output = model(x)\n\n def test_replace_some_bns_with_passthrough(self):\n model = torchvision.models.resnet18()\n model.eval()\n\n replace_modules_with_instances_of_new_type(model, [model.layer1[0].bn1, model.layer1[1].bn1],\n PassThroughOp)\n\n # check - given modules have been replaced\n self.assertTrue(isinstance(model.layer1[0].bn1, PassThroughOp))\n self.assertTrue(isinstance(model.layer1[1].bn1, PassThroughOp))\n\n # check - other bn layers have not been modified\n self.assertFalse(isinstance(model.layer1[0].bn2, PassThroughOp))\n self.assertFalse(isinstance(model.layer1[1].bn2, PassThroughOp))\n\n # sanity-check: forward pass continues to work\n with torch.no_grad():\n x = torch.rand(1, 3, 224, 224)\n output = model(x)\n\n def test_get_ordered_ops(self):\n model = torchvision.models.resnet18(pretrained=False)\n model.eval()\n\n all_ops = get_ordered_list_of_modules(model, (1, 3, 224, 224))\n conv_ops = get_ordered_list_of_conv_modules(model, (1, 3, 224, 224))\n\n self.assertEqual(60, len(all_ops))\n self.assertEqual(20, len(conv_ops))\n for _, module in conv_ops:\n self.assertTrue(isinstance(module, torch.nn.Conv2d))\n\n def test_get_reused_modules(self):\n \"\"\" Test get_reused_modules utility \"\"\"\n model = ModelWithReusedNodes()\n inp_shape = (1, 3, 32, 32)\n reused_modules = get_reused_modules(model, inp_shape)\n self.assertEqual(1, len(reused_modules))\n self.assertEqual(reused_modules[0][1], model.relu1)\n\n def test_change_tensor_device(self):\n\n # 1) test only tensor on CPU and GPU\n\n random_tensor = torch.rand(2, 2)\n random_tensor_new = change_tensor_device_placement(random_tensor, device=torch.device('cuda:0'))\n\n self.assertEqual(random_tensor.device, torch.device('cpu'))\n self.assertEqual(random_tensor_new.device, torch.device('cuda:0'))\n\n random_tensor = torch.rand(2, 2).to(device='cuda:0')\n random_tensor_new = change_tensor_device_placement(random_tensor, device=torch.device('cpu'))\n\n self.assertEqual(random_tensor.device, torch.device('cuda:0'))\n self.assertEqual(random_tensor_new.device, torch.device('cpu'))\n\n # 2) list of tensors\n\n random_tensor = [\n torch.rand(2, 2),\n torch.rand(2, 2),\n torch.rand(2, 2)\n ]\n\n random_tensor_new = change_tensor_device_placement(random_tensor, device=torch.device('cuda:0'))\n\n for item in random_tensor_new:\n self.assertEqual(item.device, torch.device('cuda:0'))\n\n self.assertEqual(len(random_tensor), len(random_tensor_new))\n\n random_tensor = [\n torch.rand(2, 2).to(device='cuda:0'),\n torch.rand(2, 2).to(device='cuda:0'),\n torch.rand(2, 2).to(device='cuda:0')\n ]\n\n random_tensor_new = change_tensor_device_placement(random_tensor, device=torch.device('cpu'))\n\n for item in random_tensor_new:\n self.assertEqual(item.device, torch.device('cpu'))\n\n self.assertEqual(len(random_tensor), len(random_tensor_new))\n\n # 3) list of list of tenors\n\n random_tensor = [\n [torch.rand(1, 1), torch.rand(1, 1)],\n [torch.rand(2, 2), torch.rand(2, 2), torch.rand(2, 2), torch.rand(2, 2)],\n torch.rand(2, 2)\n ]\n\n random_tensor_new = change_tensor_device_placement(random_tensor, device=torch.device('cuda:0'))\n\n self.assertEqual(random_tensor_new[0][0].device, torch.device('cuda:0'))\n self.assertEqual(random_tensor_new[0][1].device, torch.device('cuda:0'))\n self.assertEqual(random_tensor_new[1][0].device, torch.device('cuda:0'))\n self.assertEqual(random_tensor_new[1][1].device, torch.device('cuda:0'))\n self.assertEqual(random_tensor_new[1][2].device, torch.device('cuda:0'))\n self.assertEqual(random_tensor_new[1][3].device, torch.device('cuda:0'))\n self.assertEqual(random_tensor_new[2].device, torch.device('cuda:0'))\n\n self.assertEqual(len(random_tensor), len(random_tensor_new))\n\n # 4) tuple of tensors\n random_tensor = (\n [torch.rand(1, 1), torch.rand(1, 1)],\n [torch.rand(2, 2), torch.rand(2, 2), torch.rand(2, 2), torch.rand(2, 2)],\n (torch.rand(2, 2), torch.rand(2, 2), torch.rand(2, 2), torch.rand(2, 2)),\n )\n random_tensor_new = change_tensor_device_placement(random_tensor, device=torch.device('cuda:0'))\n\n self.assertEqual(random_tensor_new[0][0].device, torch.device('cuda:0'))\n self.assertEqual(random_tensor_new[0][1].device, torch.device('cuda:0'))\n self.assertEqual(random_tensor_new[1][0].device, torch.device('cuda:0'))\n self.assertEqual(random_tensor_new[1][1].device, torch.device('cuda:0'))\n self.assertEqual(random_tensor_new[1][2].device, torch.device('cuda:0'))\n self.assertEqual(random_tensor_new[1][3].device, torch.device('cuda:0'))\n self.assertEqual(random_tensor_new[2][0].device, torch.device('cuda:0'))\n self.assertEqual(random_tensor_new[2][1].device, torch.device('cuda:0'))\n self.assertEqual(random_tensor_new[2][2].device, torch.device('cuda:0'))\n self.assertEqual(random_tensor_new[2][3].device, torch.device('cuda:0'))\n\n self.assertEqual(len(random_tensor), len(random_tensor_new))\n self.assertTrue(isinstance(random_tensor_new, tuple))\n self.assertTrue(isinstance(random_tensor_new[0], list))\n self.assertTrue(isinstance(random_tensor_new[1], list))\n self.assertTrue(isinstance(random_tensor_new[2], tuple))\n\n # 4) tuple of tuple of tenors\n\n random_tensor = (\n (torch.rand(1, 1), torch.rand(1, 1)),\n torch.rand(2, 2),\n torch.rand(2, 2)\n )\n\n random_tensor_new = change_tensor_device_placement(random_tensor, device=torch.device('cuda:0'))\n\n self.assertEqual(random_tensor_new[0][0].device, torch.device('cuda:0'))\n self.assertEqual(random_tensor_new[0][1].device, torch.device('cuda:0'))\n self.assertEqual(random_tensor_new[1].device, torch.device('cuda:0'))\n self.assertEqual(random_tensor_new[2].device, torch.device('cuda:0'))\n\n self.assertEqual(len(random_tensor), len(random_tensor_new))\n self.assertTrue(isinstance(random_tensor_new, tuple))\n self.assertTrue(isinstance(random_tensor_new[0], tuple))\n"
] |
[
[
"torch.device",
"torch.no_grad",
"torch.rand"
]
] |
haigh1510/TensorFlow2.0-Examples
|
[
"f99fcef22caa2758b5eefce10ee789384345506d"
] |
[
"4-Object_Detection/MTCNN/utils.py"
] |
[
"#! /usr/bin/env python\n# coding=utf-8\n#================================================================\n# Copyright (C) 2019 * Ltd. All rights reserved.\n#\n# Editor : VIM\n# File name : utils.py\n# Author : YunYang1994\n# Created date: 2019-10-27 01:18:15\n# Description :\n#\n#================================================================\n\nimport cv2\nimport numpy as np\n\n\ndef detect_face(img, minsize, pnet, rnet, onet, threshold, factor):\n \"\"\"Detects faces in an image, and returns bounding boxes and points for them.\n img: input image\n minsize: minimum faces' size\n pnet, rnet, onet: caffemodel\n threshold: threshold=[th1, th2, th3], th1-3 are three steps's threshold\n factor: the factor used to create a scaling pyramid of face sizes to detect in the image.\n \"\"\"\n factor_count=0\n total_boxes=np.empty((0,9))\n points=np.empty(0)\n h=img.shape[0]\n w=img.shape[1]\n minl=np.amin([h, w])\n m=12.0/minsize\n minl=minl*m\n # create scale pyramid\n scales=[]\n while minl>=12:\n scales += [m*np.power(factor, factor_count)]\n minl = minl*factor\n factor_count += 1\n\n # first stage\n for scale in scales:\n hs=int(np.ceil(h*scale))\n ws=int(np.ceil(w*scale))\n im_data = imresample(img, (hs, ws))\n im_data = (im_data-127.5)*0.0078125\n img_x = np.expand_dims(im_data, 0)\n img_y = np.transpose(img_x, (0,2,1,3))\n out = pnet(img_y)\n out0 = np.transpose(out[0], (0,2,1,3))\n out1 = np.transpose(out[1], (0,2,1,3))\n\n boxes, _ = generateBoundingBox(out1[0,:,:,1].copy(), out0[0,:,:,:].copy(), scale, threshold[0])\n\n # inter-scale nms\n pick = nms(boxes.copy(), 0.5, 'Union')\n if boxes.size>0 and pick.size>0:\n boxes = boxes[pick,:]\n total_boxes = np.append(total_boxes, boxes, axis=0)\n\n numbox = total_boxes.shape[0]\n if numbox>0:\n pick = nms(total_boxes.copy(), 0.7, 'Union')\n total_boxes = total_boxes[pick,:]\n regw = total_boxes[:,2]-total_boxes[:,0]\n regh = total_boxes[:,3]-total_boxes[:,1]\n qq1 = total_boxes[:,0]+total_boxes[:,5]*regw\n qq2 = total_boxes[:,1]+total_boxes[:,6]*regh\n qq3 = total_boxes[:,2]+total_boxes[:,7]*regw\n qq4 = total_boxes[:,3]+total_boxes[:,8]*regh\n total_boxes = np.transpose(np.vstack([qq1, qq2, qq3, qq4, total_boxes[:,4]]))\n total_boxes = rerec(total_boxes.copy())\n total_boxes[:,0:4] = np.fix(total_boxes[:,0:4]).astype(np.int32)\n dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph = pad(total_boxes.copy(), w, h)\n\n numbox = total_boxes.shape[0]\n if numbox>0:\n # second stage\n tempimg = np.zeros((24,24,3,numbox))\n for k in range(0,numbox):\n tmp = np.zeros((int(tmph[k]),int(tmpw[k]),3))\n tmp[dy[k]-1:edy[k],dx[k]-1:edx[k],:] = img[y[k]-1:ey[k],x[k]-1:ex[k],:]\n if tmp.shape[0]>0 and tmp.shape[1]>0 or tmp.shape[0]==0 and tmp.shape[1]==0:\n tempimg[:,:,:,k] = imresample(tmp, (24, 24))\n else:\n return np.empty()\n tempimg = (tempimg-127.5)*0.0078125\n tempimg1 = np.transpose(tempimg, (3,1,0,2))\n out = rnet(tempimg1)\n out0 = np.transpose(out[0])\n out1 = np.transpose(out[1])\n score = out1[1,:]\n ipass = np.where(score>threshold[1])\n total_boxes = np.hstack([total_boxes[ipass[0],0:4].copy(), np.expand_dims(score[ipass].copy(),1)])\n mv = out0[:,ipass[0]]\n if total_boxes.shape[0]>0:\n pick = nms(total_boxes, 0.7, 'Union')\n total_boxes = total_boxes[pick,:]\n total_boxes = bbreg(total_boxes.copy(), np.transpose(mv[:,pick]))\n total_boxes = rerec(total_boxes.copy())\n\n numbox = total_boxes.shape[0]\n if numbox>0:\n # third stage\n total_boxes = np.fix(total_boxes).astype(np.int32)\n dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph = pad(total_boxes.copy(), w, h)\n tempimg = np.zeros((48,48,3,numbox))\n for k in range(0,numbox):\n tmp = np.zeros((int(tmph[k]),int(tmpw[k]),3))\n tmp[dy[k]-1:edy[k],dx[k]-1:edx[k],:] = img[y[k]-1:ey[k],x[k]-1:ex[k],:]\n if tmp.shape[0]>0 and tmp.shape[1]>0 or tmp.shape[0]==0 and tmp.shape[1]==0:\n tempimg[:,:,:,k] = imresample(tmp, (48, 48))\n else:\n return np.empty()\n tempimg = (tempimg-127.5)*0.0078125\n tempimg1 = np.transpose(tempimg, (3,1,0,2))\n out = onet(tempimg1)\n out0 = np.transpose(out[0])\n out1 = np.transpose(out[1])\n out2 = np.transpose(out[2])\n score = out2[1,:]\n points = out1\n ipass = np.where(score>threshold[2])\n points = points[:,ipass[0]]\n total_boxes = np.hstack([total_boxes[ipass[0],0:4].copy(), np.expand_dims(score[ipass].copy(),1)])\n mv = out0[:,ipass[0]]\n\n w = total_boxes[:,2]-total_boxes[:,0]+1\n h = total_boxes[:,3]-total_boxes[:,1]+1\n points[0:5,:] = np.tile(w,(5, 1))*points[0:5,:] + np.tile(total_boxes[:,0],(5, 1))-1\n points[5:10,:] = np.tile(h,(5, 1))*points[5:10,:] + np.tile(total_boxes[:,1],(5, 1))-1\n if total_boxes.shape[0]>0:\n total_boxes = bbreg(total_boxes.copy(), np.transpose(mv))\n pick = nms(total_boxes.copy(), 0.7, 'Min')\n total_boxes = total_boxes[pick,:]\n points = points[:,pick]\n\n return total_boxes, points\n\ndef bbreg(boundingbox,reg):\n \"\"\"Calibrate bounding boxes\"\"\"\n if reg.shape[1]==1:\n reg = np.reshape(reg, (reg.shape[2], reg.shape[3]))\n\n w = boundingbox[:,2]-boundingbox[:,0]+1\n h = boundingbox[:,3]-boundingbox[:,1]+1\n b1 = boundingbox[:,0]+reg[:,0]*w\n b2 = boundingbox[:,1]+reg[:,1]*h\n b3 = boundingbox[:,2]+reg[:,2]*w\n b4 = boundingbox[:,3]+reg[:,3]*h\n boundingbox[:,0:4] = np.transpose(np.vstack([b1, b2, b3, b4 ]))\n return boundingbox\n\ndef generateBoundingBox(imap, reg, scale, t):\n \"\"\"Use heatmap to generate bounding boxes\"\"\"\n stride=2\n cellsize=12\n\n imap = np.transpose(imap)\n dx1 = np.transpose(reg[:,:,0])\n dy1 = np.transpose(reg[:,:,1])\n dx2 = np.transpose(reg[:,:,2])\n dy2 = np.transpose(reg[:,:,3])\n y, x = np.where(imap >= t)\n if y.shape[0]==1:\n dx1 = np.flipud(dx1)\n dy1 = np.flipud(dy1)\n dx2 = np.flipud(dx2)\n dy2 = np.flipud(dy2)\n score = imap[(y,x)]\n reg = np.transpose(np.vstack([ dx1[(y,x)], dy1[(y,x)], dx2[(y,x)], dy2[(y,x)] ]))\n if reg.size==0:\n reg = np.empty((0,3))\n bb = np.transpose(np.vstack([y,x]))\n q1 = np.fix((stride*bb+1)/scale)\n q2 = np.fix((stride*bb+cellsize-1+1)/scale)\n boundingbox = np.hstack([q1, q2, np.expand_dims(score,1), reg])\n return boundingbox, reg\n\n# function pick = nms(boxes,threshold,type)\ndef nms(boxes, threshold, method):\n if boxes.size==0:\n return np.empty((0,3))\n x1 = boxes[:,0]\n y1 = boxes[:,1]\n x2 = boxes[:,2]\n y2 = boxes[:,3]\n s = boxes[:,4]\n area = (x2-x1+1) * (y2-y1+1)\n I = np.argsort(s)\n pick = np.zeros_like(s, dtype=np.int16)\n counter = 0\n while I.size>0:\n i = I[-1]\n pick[counter] = i\n counter += 1\n idx = I[0:-1]\n xx1 = np.maximum(x1[i], x1[idx])\n yy1 = np.maximum(y1[i], y1[idx])\n xx2 = np.minimum(x2[i], x2[idx])\n yy2 = np.minimum(y2[i], y2[idx])\n w = np.maximum(0.0, xx2-xx1+1)\n h = np.maximum(0.0, yy2-yy1+1)\n inter = w * h\n if method is 'Min':\n o = inter / np.minimum(area[i], area[idx])\n else:\n o = inter / (area[i] + area[idx] - inter)\n I = I[np.where(o<=threshold)]\n pick = pick[0:counter]\n return pick\n\n# function [dy edy dx edx y ey x ex tmpw tmph] = pad(total_boxes,w,h)\ndef pad(total_boxes, w, h):\n \"\"\"Compute the padding coordinates (pad the bounding boxes to square)\"\"\"\n tmpw = (total_boxes[:,2]-total_boxes[:,0]+1).astype(np.int32)\n tmph = (total_boxes[:,3]-total_boxes[:,1]+1).astype(np.int32)\n numbox = total_boxes.shape[0]\n\n dx = np.ones((numbox), dtype=np.int32)\n dy = np.ones((numbox), dtype=np.int32)\n edx = tmpw.copy().astype(np.int32)\n edy = tmph.copy().astype(np.int32)\n\n x = total_boxes[:,0].copy().astype(np.int32)\n y = total_boxes[:,1].copy().astype(np.int32)\n ex = total_boxes[:,2].copy().astype(np.int32)\n ey = total_boxes[:,3].copy().astype(np.int32)\n\n tmp = np.where(ex>w)\n edx.flat[tmp] = np.expand_dims(-ex[tmp]+w+tmpw[tmp],1)\n ex[tmp] = w\n\n tmp = np.where(ey>h)\n edy.flat[tmp] = np.expand_dims(-ey[tmp]+h+tmph[tmp],1)\n ey[tmp] = h\n\n tmp = np.where(x<1)\n dx.flat[tmp] = np.expand_dims(2-x[tmp],1)\n x[tmp] = 1\n\n tmp = np.where(y<1)\n dy.flat[tmp] = np.expand_dims(2-y[tmp],1)\n y[tmp] = 1\n\n return dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph\n\n# function [bboxA] = rerec(bboxA)\ndef rerec(bboxA):\n \"\"\"Convert bboxA to square.\"\"\"\n h = bboxA[:,3]-bboxA[:,1]\n w = bboxA[:,2]-bboxA[:,0]\n l = np.maximum(w, h)\n bboxA[:,0] = bboxA[:,0]+w*0.5-l*0.5\n bboxA[:,1] = bboxA[:,1]+h*0.5-l*0.5\n bboxA[:,2:4] = bboxA[:,0:2] + np.transpose(np.tile(l,(2,1)))\n return bboxA\n\ndef imresample(img, sz):\n im_data = cv2.resize(img, (sz[1], sz[0]), interpolation=cv2.INTER_AREA) #@UndefinedVariable\n return im_data\n"
] |
[
[
"numpy.expand_dims",
"numpy.minimum",
"numpy.flipud",
"numpy.zeros_like",
"numpy.fix",
"numpy.where",
"numpy.reshape",
"numpy.ceil",
"numpy.zeros",
"numpy.power",
"numpy.amin",
"numpy.append",
"numpy.transpose",
"numpy.argsort",
"numpy.maximum",
"numpy.tile",
"numpy.empty",
"numpy.ones",
"numpy.vstack"
]
] |
Nicolas-Reyland/OCR-Sudoku-Solver
|
[
"d5950cf4935c7ca9ae0ff2ce54178ce0eb08c75d"
] |
[
"trainnn-converter.py"
] |
[
"#!/usr/bin/env python3\nfrom __future__ import annotations\nfrom PIL import Image\nimport numpy as np\nimport os, sys\n\nbase_img_fn = lambda fp: int(os.path.basename(fp)[0])\n\ndef convert_img(img_path: str) -> str:\n img = Image.open(img_path)\n if img.size != (28, 28):\n print(f'resizing: {img_path}')\n img = img.resize((28, 28))\n arr = np.asarray(img)\n if arr.shape[-1] == 3 or arr.shape[-1] == 4:\n fn = lambda rgb: np.mean(rgb[:3])\n arr = np.apply_along_axis(fn, 2, arr)\n arr = arr.reshape(784)\n arr /= 255\n return ' '.join(map(str, arr)) + '\\n'\n\ndef convert_n(n: int) -> str:\n m = [0.0] * 9\n m[n - 1] = 1.0\n return ' '.join(map(str, m)) + '\\n'\n\ndef convert_dir(dir_path, data_path, img_fn = base_img_fn) -> None:\n files = list(map(lambda f: os.path.join(dir_path, f), os.listdir(dir_path)))\n N = len(files)\n inputs = map(convert_img, files)\n outputs = map(lambda fp: convert_n(base_img_fn(fp)), files)\n with open(data_path + 'data.in', 'w') as f:\n f.write(f\"{N} 2 28 28 1\\n\")\n for i,input_ in enumerate(inputs):\n # if i % 100 == 0: print(f\"done {i}/{N}\")\n f.write(input_)\n with open(data_path + 'data.out', 'w') as f:\n f.write(f\"{N} 1 9 1 1\\n\")\n for i,output in enumerate(outputs):\n # if i % 100 == 0: print(f\"done {i}/{N}\")\n f.write(output)\n\n\nif __name__ == \"__main__\":\n args = sys.argv[1:]\n if len(args) != 2:\n sys.stderr.write(\"Usage: ./trainnn-converter.py directory-path data-prefix\\n\")\n exit(1)\n convert_dir(*args)\n\n"
] |
[
[
"numpy.asarray",
"numpy.apply_along_axis",
"numpy.mean"
]
] |
xinrongl/mmdetection
|
[
"c6aaf04b36b7d30da039a490192b30794617fdcc"
] |
[
"tools/slice_image.py"
] |
[
"import numpy as np\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\n\ndef crop(image, return_array=False, shape=(3, 3), plot=True, figsize=(10, 10)):\n \"\"\"\n Slice image into multiple images.\n Params: \n image: str/pathlib object, image directory\n return_array: bool, if true, return sliced images as np.array\n plot: bool, if true, plot sliced images\n shape: tuple (nrows, ncols), number of images the raw input will be sliced into\n figsize: tuple\n Return: list of np.array contained sliced images\n \"\"\"\n im_np = np.array(Image.open(image))\n M = im_np.shape[0]//shape[0]\n N = im_np.shape[1]//shape[1]\n \n tiles = [im_np[x:x+M,y:y+N] for x in range(0,im_np.shape[0],M) for y in range(0,im_np.shape[1],N)]\n if plot:\n fig, axs = plt.subplots(nrows=shape[0], ncols=shape[1], figsize=figsize)\n axs = axs.flatten()\n for tile, ax in zip(tiles, axs):\n ax.imshow(tile)\n plt.show()\n if return_array:\n return tiles\n return None\n\n\n\ndef reconstruct(images, return_array=False, shape=(3, 3), plot=True, figsize=(10, 10)):\n \"\"\"\n Reversed outputs from crop and combined with to a single image. \n \"\"\"\n img = np.vstack([np.column_stack(tiles[i: i+shape[1]]) for i in range(0, len(images), shape[1])])\n if plot:\n fig, ax = plt.subplots(figsize=figsize)\n ax.imshow(img)\n plt.show()\n if return_array:\n return img\n return None\n"
] |
[
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplots",
"numpy.column_stack"
]
] |
Purg/SMQTK
|
[
"705a2b2979935ed129aac7db578571c4ae1343e7"
] |
[
"tests/algorithms/nn_index/test_NNI_FLANN.py"
] |
[
"from __future__ import division, print_function\nimport mock\nimport random\nimport unittest\n\nimport numpy\nimport pytest\n\nfrom smqtk.algorithms import NearestNeighborsIndex\nfrom smqtk.algorithms.nn_index.flann import FlannNearestNeighborsIndex\nfrom smqtk.representation.descriptor_element.local_elements import \\\n DescriptorMemoryElement\nfrom smqtk.utils.configuration import configuration_test_helper\n\n\n# Don't bother running tests of the class is not usable\[email protected](not FlannNearestNeighborsIndex.is_usable(),\n reason=\"FlannNearestNeighborsIndex does not report as \"\n \"usable.\")\nclass TestFlannIndex (unittest.TestCase):\n\n RAND_SEED = 42\n\n def _make_inst(self, dist_method):\n \"\"\"\n Make an instance of FlannNearestNeighborsIndex\n \"\"\"\n return FlannNearestNeighborsIndex(distance_method=dist_method,\n random_seed=self.RAND_SEED)\n\n def test_impl_findable(self):\n # Already here because the implementation is reporting itself as\n # usable.\n self.assertIn(FlannNearestNeighborsIndex,\n NearestNeighborsIndex.get_impls())\n\n def test_configuration(self):\n index_filepath = '/index_filepath'\n para_filepath = '/param_fp'\n descr_cache_fp = '/descrcachefp'\n\n c = FlannNearestNeighborsIndex(\n index_uri=index_filepath,\n parameters_uri=para_filepath,\n descriptor_cache_uri=descr_cache_fp,\n distance_method='hik', random_seed=42,\n )\n for inst in configuration_test_helper(c): # type: FlannNearestNeighborsIndex\n assert inst._index_uri == index_filepath\n assert inst._index_param_uri == para_filepath\n assert inst._descr_cache_uri == descr_cache_fp\n assert inst._distance_method == 'hik'\n assert inst._rand_seed == 42\n\n def test_has_model_data_no_uris(self):\n f = FlannNearestNeighborsIndex()\n self.assertFalse(f._has_model_data())\n\n def test_has_model_data_empty_elements(self):\n f = FlannNearestNeighborsIndex('', '', '')\n self.assertFalse(f._has_model_data())\n\n def test_load_flann_model_empty_data_elements(self):\n # Construct index with valid, but empty, data URIs instances\n empty_data = 'base64://'\n f = FlannNearestNeighborsIndex(empty_data, empty_data, empty_data)\n # Load method should do nothing but set PID since given data was\n # empty.\n f._load_flann_model()\n self.assertIsNone(f._descr_cache)\n self.assertIsNone(f._flann)\n self.assertIsNone(f._flann_build_params)\n self.assertIsNotNone(f._pid)\n\n @mock.patch(\"smqtk.algorithms.nn_index.flann\"\n \".FlannNearestNeighborsIndex._load_flann_model\")\n def test_has_model_data_valid_uris(self, _m_flann_lfm):\n # Mocking flann data loading that occurs in constructor when given\n # non-empty URI targets\n f = FlannNearestNeighborsIndex(\n 'base64://bW9kZWxEYXRh', # 'modelData'\n 'base64://cGFyYW1EYXRh', # 'paramData'\n 'base64://ZGVzY3JEYXRh', # 'descrData'\n )\n self.assertTrue(f._has_model_data())\n\n def test_build_index_one(self):\n d = DescriptorMemoryElement('test', 0)\n d.set_vector(numpy.zeros(8, float))\n index = self._make_inst('euclidean')\n index.build_index([d])\n self.assertListEqual(\n index._descr_cache,\n [d]\n )\n self.assertIsNotNone(index._flann)\n self.assertIsInstance(index._flann_build_params, dict)\n\n def test_build_index_with_cache(self):\n # Empty memory data elements for storage\n empty_data = 'base64://'\n f = FlannNearestNeighborsIndex(empty_data, empty_data, empty_data)\n # Internal elements should initialize have zero-length byte values\n self.assertEqual(len(f._index_elem.get_bytes()), 0)\n self.assertEqual(len(f._index_param_elem.get_bytes()), 0)\n self.assertEqual(len(f._descr_cache_elem.get_bytes()), 0)\n\n # Make unit vectors, one for each feature dimension.\n dim = 8\n test_descriptors = []\n for i in range(dim):\n v = numpy.zeros(dim, float)\n v[i] = 1.\n d = DescriptorMemoryElement('unit', i)\n d.set_vector(v)\n test_descriptors.append(d)\n\n f.build_index(test_descriptors)\n\n # Internal elements should not have non-zero byte values.\n self.assertGreater(len(f._index_elem.get_bytes()), 0)\n self.assertGreater(len(f._index_param_elem.get_bytes()), 0)\n self.assertGreater(len(f._descr_cache_elem.get_bytes()), 0)\n\n def test_update_index(self):\n # Build index with one descriptor, then \"update\" with a second\n # different descriptor checking that the new cache contains both.\n d1 = DescriptorMemoryElement('test', 0)\n d1.set_vector(numpy.zeros(8))\n d2 = DescriptorMemoryElement('test', 1)\n d2.set_vector(numpy.ones(8))\n\n index = self._make_inst('euclidean')\n index.build_index([d1])\n self.assertEqual(index.count(), 1)\n self.assertSetEqual(set(index._descr_cache), {d1})\n\n index.update_index([d2])\n self.assertEqual(index.count(), 2)\n self.assertSetEqual(set(index._descr_cache), {d1, d2})\n\n def test_nn_known_descriptors_euclidean_unit(self):\n dim = 5\n\n ###\n # Unit vectors -- Equal distance\n #\n index = self._make_inst('euclidean')\n test_descriptors = []\n for i in range(dim):\n v = numpy.zeros(dim, float)\n v[i] = 1.\n d = DescriptorMemoryElement('unit', i)\n d.set_vector(v)\n test_descriptors.append(d)\n index.build_index(test_descriptors)\n # query descriptor -- zero vector\n # -> all modeled descriptors should be equally distance (unit\n # corners)\n q = DescriptorMemoryElement('query', 0)\n q.set_vector(numpy.zeros(dim, float))\n r, dists = index.nn(q, dim)\n # All dists should be 1.0, r order doesn't matter\n for d in dists:\n self.assertEqual(d, 1.)\n\n def test_nn_known_descriptors_euclidean_ordered(self):\n index = self._make_inst('euclidean')\n\n # make vectors to return in a known euclidean distance order\n i = 10\n test_descriptors = []\n for j in range(i):\n d = DescriptorMemoryElement('ordered', j)\n d.set_vector(numpy.array([j, j*2], float))\n test_descriptors.append(d)\n random.shuffle(test_descriptors)\n index.build_index(test_descriptors)\n\n # Since descriptors were build in increasing distance from (0,0),\n # returned descriptors for a query of [0,0] should be in index\n # order.\n q = DescriptorMemoryElement('query', 99)\n q.set_vector(numpy.array([0, 0], float))\n r, dists = index.nn(q, i)\n for j, d, dist in zip(range(i), r, dists):\n self.assertEqual(d.uuid(), j)\n numpy.testing.assert_equal(d.vector(), [j, j*2])\n\n def test_nn_known_descriptors_hik_unit(self):\n dim = 5\n\n ###\n # Unit vectors - Equal distance\n #\n index = self._make_inst('hik')\n test_descriptors = []\n for i in range(dim):\n v = numpy.zeros(dim, float)\n v[i] = 1.\n d = DescriptorMemoryElement('unit', i)\n d.set_vector(v)\n test_descriptors.append(d)\n index.build_index(test_descriptors)\n # query with zero vector\n # -> all modeled descriptors have no intersection, dists should be\n # 1.0, or maximum distance by histogram intersection.\n q = DescriptorMemoryElement('query', 0)\n q.set_vector(numpy.zeros(dim, float))\n r, dists = index.nn(q, dim)\n # All dists should be 1.0, r order doesn't matter\n for d in dists:\n self.assertEqual(d, 1.)\n\n # query with index element\n q = test_descriptors[3]\n r, dists = index.nn(q, 1)\n self.assertEqual(r[0], q)\n self.assertEqual(dists[0], 0.)\n\n r, dists = index.nn(q, dim)\n self.assertEqual(r[0], q)\n self.assertEqual(dists[0], 0.)\n\n def test_build_index_no_descriptors(self):\n f = FlannNearestNeighborsIndex()\n self.assertRaises(\n ValueError,\n f.build_index, []\n )\n\n def test_build_index(self):\n # Empty memory data elements for storage\n empty_data = 'base64://'\n f = FlannNearestNeighborsIndex(empty_data, empty_data, empty_data)\n # Internal elements should initialize have zero-length byte values\n self.assertEqual(len(f._index_elem.get_bytes()), 0)\n self.assertEqual(len(f._index_param_elem.get_bytes()), 0)\n self.assertEqual(len(f._descr_cache_elem.get_bytes()), 0)\n\n # Make unit vectors, one for each feature\n dim = 8\n test_descriptors = []\n for i in range(dim):\n v = numpy.zeros(dim, float)\n v[i] = 1.\n d = DescriptorMemoryElement('unit', i)\n d.set_vector(v)\n test_descriptors.append(d)\n\n f.build_index(test_descriptors)\n\n # Internal elements should not have non-zero byte values.\n self.assertGreater(len(f._index_elem.get_bytes()), 0)\n self.assertGreater(len(f._index_param_elem.get_bytes()), 0)\n self.assertGreater(len(f._descr_cache_elem.get_bytes()), 0)\n"
] |
[
[
"numpy.array",
"numpy.zeros",
"numpy.ones"
]
] |
kingmbc/iris-python
|
[
"824a3dd9cf9fd9685ece05298423a4b8e78dccb7"
] |
[
"Lasagne/iris_lasagne.py"
] |
[
"from __future__ import print_function\nfrom builtins import range\n\n\"\"\"\nSECTION 1 : Load and setup data for training\n\nthe datasets has separated to two file from originai datasets:\niris_train.csv = datasets for training purpose, 80% from the original data\niris_test.csv = datasets for testing purpose, 20% from the original data\n\"\"\"\nimport pandas as pd\n\n#load\ndatatrain = pd.read_csv('../Datasets/iris/iris_train.csv')\n\n#change string value to numeric\ndatatrain.loc[datatrain['species']=='Iris-setosa', 'species']=0\ndatatrain.loc[datatrain['species']=='Iris-versicolor', 'species']=1\ndatatrain.loc[datatrain['species']=='Iris-virginica', 'species']=2\ndatatrain = datatrain.apply(pd.to_numeric)\n\n#change dataframe to array\ndatatrain_array = datatrain.values\n\n#split x and y (feature and target)\nxtrain = datatrain_array[:,:4]\nytrain = datatrain_array[:,4]\n\n\"\"\"\nSECTION 2 : Build and Train Model\n\nMultilayer perceptron model, with one hidden layer.\ninput layer : 4 neuron, represents the feature of Iris\nhidden layer : 10 neuron, activation using ReLU\noutput layer : 3 neuron, represents the class of Iris, Softmax Layer\n\noptimizer = stochastic gradient descent with no batch-size\nloss function = categorical cross entropy\nlearning rate = 0.01\nepoch = 500\n\"\"\"\nimport theano\nimport theano.tensor as T\nimport numpy as np\nimport lasagne\n\n#initiate theano variable\ninput_val = T.fmatrix(\"inputs\")\ntarget_val = T.ivector(\"targets\")\n\n#build model\ninput_layer = lasagne.layers.InputLayer(shape=xtrain.shape, input_var=input_val)\nhidden_layer = lasagne.layers.DenseLayer(input_layer, num_units=10,nonlinearity=lasagne.nonlinearities.rectify) \noutput_layer = lasagne.layers.DenseLayer(hidden_layer, num_units=3,nonlinearity=lasagne.nonlinearities.softmax) \noutput_val = output_layer.get_output()\n\n#choose objective/loss function \nobjective = lasagne.objectives.Objective(\n output_layer,\n loss_function=lasagne.objectives.categorical_crossentropy) \nloss = objective.get_loss(target=target_val)\n\n#choose optimizer\nall_params = lasagne.layers.get_all_params(output_layer)\nupdates = lasagne.updates.sgd(loss, all_params, learning_rate=0.01)\n\n#compile theano function\ntrain_model = theano.function([input_val,target_val],loss,allow_input_downcast=True,updates=updates)\ntest_model = theano.function([input_val],output_val,allow_input_downcast=True)\n\n#train\nfor _ in range(500): \n loss_val = train_model(xtrain,ytrain)\n prediction = np.argmax(test_model(xtrain),axis=1)\n accuration = 100*np.mean(ytrain == prediction)\n print(\"Epoch \" + str(_+1) + \"/\" + str(500) + \" - loss: \" + str(loss_val) + \" - accuration: \" + str(accuration))\n \n\"\"\"\nSECTION 3 : Testing model\n\"\"\"\n#load\ndatatest = pd.read_csv('../Datasets/iris/iris_test.csv')\n\n#change string value to numeric\ndatatest.loc[datatest['species']=='Iris-setosa', 'species']=0\ndatatest.loc[datatest['species']=='Iris-versicolor', 'species']=1\ndatatest.loc[datatest['species']=='Iris-virginica', 'species']=2\ndatatest = datatest.apply(pd.to_numeric)\n\n#change dataframe to array\ndatatest_array = datatest.values\n\n#split x and y (feature and target)\nxtest= datatest_array[:,:4]\nytest = datatest_array[:,4]\n\n#get prediction\nprediction = np.argmax(test_model(xtest),axis=1)\n\n#get accuration\naccuration = 100*np.mean(ytest == prediction)\nprint(\"Test Accuration : \"+str(accuration))\nprint(\"Prediction :\")\nprint(prediction)\nprint(\"Target :\")\nprint(np.asarray(ytest,dtype=\"int32\"))"
] |
[
[
"numpy.asarray",
"pandas.read_csv",
"numpy.mean"
]
] |
edfong/conformal_bayes
|
[
"0c6d1c1e8e2d41480b57125c52665fc8be182908"
] |
[
"run_scripts/load_data.py"
] |
[
"from sklearn.datasets import load_boston,load_diabetes,load_breast_cancer\nfrom sklearn.model_selection import train_test_split\nimport time\nimport numpy as np\nfrom tqdm import tqdm\nimport pandas as pd\nimport scipy as sp\n\n## Sparse Regression ##\n#Well specified?\ndef load_traintest_sparsereg(train_frac, dataset,seed):\n #Load dataset\n if dataset ==\"diabetes\":\n x,y = load_diabetes(return_X_y = True)\n elif dataset ==\"boston\":\n x,y = load_boston(return_X_y = True)\n else:\n print('Invalid dataset')\n return\n\n n = np.shape(x)[0]\n d = np.shape(x)[1]\n\n #Standardize beforehand (for validity)\n x = (x - np.mean(x,axis = 0))/np.std(x,axis = 0)\n y = (y - np.mean(y))/np.std(y)\n\n #Train test split\n ind_train, ind_test = train_test_split(np.arange(n), train_size = int(train_frac*n),random_state = seed)\n x_train = x[ind_train]\n y_train = y[ind_train]\n x_test = x[ind_test]\n y_test = y[ind_test]\n\n y_plot = np.linspace(np.min(y_train) - 2, np.max(y_train) + 2,100)\n \n return x_train,y_train,x_test,y_test,y_plot,n,d\n\n## Sparse Classification ##\n# Load data\ndef load_traintest_sparseclass(train_frac,dataset, seed):\n #Load dataset\n if dataset ==\"breast\":\n x,y = load_breast_cancer(return_X_y = True)\n elif dataset == \"parkinsons\":\n data = pd.read_csv('data/parkinsons.data')\n data[data == '?']= np.nan\n data.dropna(axis = 0,inplace = True)\n y = data['status'].values #convert strings to integer\n x = data.drop(columns = ['name','status']).values\n else:\n print('Invalid dataset')\n return\n\n n = np.shape(x)[0]\n d = np.shape(x)[1]\n\n #Standardize beforehand (for validity)\n x = (x - np.mean(x,axis = 0))/np.std(x,axis = 0)\n\n #Train test split\n ind_train, ind_test = train_test_split(np.arange(n), train_size = int(train_frac*n),random_state = seed)\n x_train = x[ind_train]\n y_train = y[ind_train]\n x_test = x[ind_test]\n y_test = y[ind_test]\n\n y_plot = np.array([0,1])\n \n return x_train,y_train,x_test,y_test,y_plot,n,d\n\n\n## Hierarchical Datasets ##\n#Simulate data \ndef gen_data_hier(n,p,n_test,seed,K,misspec = False): #n and n_test is number per group\n #Generate groups first\n theta = np.zeros(p)\n\n #Generate K beta_values (fixed random values)\n np.random.seed(24)\n beta_true = np.random.randn(K,p) + theta.reshape(1,-1)\n sigma_true = np.random.exponential(size = K, scale = 1)\n \n #Training data\n np.random.seed(seed) #try new seed\n x = np.zeros((n*K,p+1))\n y = np.zeros(n*K)\n\n for k in range(K):\n if misspec == True:\n #eps = sp.stats.skewnorm.rvs(a=5,size = n)\n eps = np.random.randn(n)*sigma_true[k]\n else:\n eps = np.random.randn(n) \n x[k*n:(k+1)*n] = np.concatenate((np.random.randn(n,p),k*np.ones((n,1))),axis = 1) #Append group index to last dimension\n y[k*n:(k+1)*n] = np.dot(x[k*n:(k+1)*n,0:p],beta_true[k]) + eps\n \n #Test data\n x_test = np.zeros((n_test*(K),p+1))\n y_test = np.zeros(n_test*(K))\n\n for k in range(K): \n if misspec == True:\n #eps_test = sp.stats.skewnorm.rvs(a=5,size = n_test)\n eps_test = np.random.randn(n_test)*sigma_true[k]\n else:\n eps_test = np.random.randn(n_test) \n x_test[k*n_test:(k+1)*n_test] = np.concatenate((np.random.randn(n_test,p),k*np.ones((n_test,1))),axis = 1) #Append group index to last dimension\n y_test[k*n_test:(k+1)*n_test] = np.dot(x_test[k*n_test:(k+1)*n_test,0:p],beta_true[k]) + eps_test\n \n y_plot = np.linspace(-10,10,100)\n return y,x,y_test,x_test,beta_true,sigma_true,y_plot\n\n# Load Radon (Minnesota) dataset, based on https://docs.pymc.io/notebooks/multilevel_modeling.html\ndef load_traintest_hier(train_frac,dataset, seed):\n #Load dataset\n if dataset ==\"radon\":\n # Import radon data\n srrs2 = pd.read_csv(\"./data/srrs2.dat\")\n srrs2.columns = srrs2.columns.map(str.strip)\n srrs_mn = srrs2[srrs2.state == \"MN\"].copy()\n\n srrs_mn[\"fips\"] = srrs_mn.stfips * 1000 + srrs_mn.cntyfips\n cty = pd.read_csv(\"./data/cty.dat\")\n cty_mn = cty[cty.st == \"MN\"].copy()\n cty_mn[\"fips\"] = 1000 * cty_mn.stfips + cty_mn.ctfips\n\n srrs_mn = srrs_mn.merge(cty_mn[[\"fips\", \"Uppm\"]], on=\"fips\")\n srrs_mn = srrs_mn.drop_duplicates(subset=\"idnum\")\n u = np.log(srrs_mn.Uppm).unique()\n\n n = len(srrs_mn)\n\n srrs_mn.county = srrs_mn.county.map(str.strip)\n mn_counties = srrs_mn.county.unique()\n counties = len(mn_counties)\n county_lookup = dict(zip(mn_counties, range(counties)))\n\n county = srrs_mn[\"county_code\"] = srrs_mn.county.replace(county_lookup).values\n radon = srrs_mn.activity\n srrs_mn[\"log_radon\"] = log_radon = np.log(radon + 0.1).values\n floor = srrs_mn.floor.values\n\n #Preprocess\n x = np.zeros((n,2))\n x[:,0] = floor\n x[:,1]= county\n x = np.array(x, dtype = 'int')\n y = np.array(log_radon)\n \n else:\n print('Invalid dataset')\n return\n\n n = np.shape(x)[0]\n d = np.shape(x)[1]\n\n #Train test split\n if train_frac ==1.:\n ind_train = np.arange(n)\n ind_test = np.array([],dtype = 'int')\n else:\n ind_train, ind_test = train_test_split(np.arange(n), train_size = int(train_frac*n),random_state = seed,stratify = x[:,1])\n x_train = x[ind_train]\n y_train = y[ind_train]\n x_test = x[ind_test]\n y_test = y[ind_test]\n\n y_plot = np.linspace(-6,6,100)\n \n return x_train,y_train,x_test,y_test,y_plot,n,d\n## ##"
] |
[
[
"numpy.dot",
"numpy.linspace",
"sklearn.datasets.load_diabetes",
"numpy.max",
"numpy.random.randn",
"numpy.mean",
"sklearn.datasets.load_boston",
"pandas.read_csv",
"numpy.arange",
"numpy.std",
"numpy.zeros",
"numpy.log",
"numpy.min",
"numpy.array",
"sklearn.datasets.load_breast_cancer",
"numpy.random.seed",
"numpy.random.exponential",
"numpy.ones",
"numpy.shape"
]
] |
dsa110/dsa110-meridian-fs
|
[
"2c68ae5091f5a4984208c18666c744ec2febde2d"
] |
[
"tests/travis/test_fringestopping.py"
] |
[
"import os\nimport pytest\nfrom antpos import utils\nfrom dsamfs import fringestopping\nfrom dsamfs.utils import parse_params\nimport dsacalib.utils as du\nimport dsacalib.constants as ct\nfrom dsacalib.fringestopping import calc_uvw\nimport numpy as np\nimport astropy.units as u\n\ndef test_gentable(tmpdir):\n fstable = '{0}/fs_table.npz'.format(tmpdir)\n pt_dec = 0.71094487066\n tsamp = 0.134217728\n nint = 10\n antenna_order = [24, 10, 3, 66]\n outrigger_delays = {24 : 1200, }\n bname = []\n for i, ant1 in enumerate(antenna_order):\n for ant2 in antenna_order[i:]:\n bname += ['{0}-{1}'.format(ant1, ant2)]\n df_bls = utils.get_baselines(antenna_order, autocorrs=True, casa_order=False)\n blen = np.array([df_bls['x_m'], df_bls['y_m'], df_bls['z_m']]).T\n fringestopping.generate_fringestopping_table(\n blen, pt_dec, nint, tsamp, antenna_order, outrigger_delays, bname,\n outname=fstable)\n assert os.path.exists(fstable)\n\ndef test_outrigger_lookup():\n bn = '100-101'\n ants = bn.split('-')\n _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, outrigger_delays = parse_params()\n delay = outrigger_delays.get(int(ants[0]), 0) - outrigger_delays.get(int(ants[1]), 0)\n assert np.abs(delay) > 0\n delay2 = outrigger_delays[int(ants[0])] - outrigger_delays[int(ants[1])]\n assert delay2 == delay\n \ndef test_write_fs_delay_table():\n msname = 'test_write'\n source = du.src('TEST', 16*u.hourangle, 37*u.deg, 1.)\n antenna_order = [24, 10, 3, 66]\n df_bls = utils.get_baselines(antenna_order, autocorrs=True, casa_order=False)\n blen = np.array([df_bls['x_m'], df_bls['y_m'], df_bls['z_m']]).T\n \ndef test_calc_uvw():\n nant = 5\n nt = 10\n nbl = (nant*(nant+1))//2\n antenna_order = np.arange(nant)+1\n tobs = 59100.956635023+np.arange(nt)/ct.SECONDS_PER_DAY\n df_bls = utils.get_baselines(antenna_order, autocorrs=True, casa_order=False)\n blen = np.array([df_bls['x_m'], df_bls['y_m'], df_bls['z_m']]).T\n ra = 14.31225787*u.hourangle\n dec = 0.71094487*u.rad\n uvw_blt = fringestopping.calc_uvw_blt(np.tile(blen[np.newaxis, :, :],\n (nt, 1, 1)).reshape(-1, 3),\n np.tile(tobs[:, np.newaxis],\n (1, nbl)).flatten(),\n 'J2000', ra, dec)\n uu, vv, ww = calc_uvw(blen, tobs, 'J2000', ra, dec)\n print(uvw_blt.shape, uu.T.shape)\n assert np.all(np.abs(uvw_blt[:, 0]-uu.T.flatten()) < 1e-6)\n assert np.all(np.abs(uvw_blt[:, 1]-vv.T.flatten()) < 1e-6)\n assert np.all(np.abs(uvw_blt[:, 2]-ww.T.flatten()) < 1e-6)\n \n uvw_blt = fringestopping.calc_uvw_blt(np.tile(blen[np.newaxis, :, :],\n (nt, 1, 1)).reshape(-1, 3),\n np.tile(tobs[:, np.newaxis],\n (1, nbl)).flatten(),\n 'HADEC',\n np.zeros(nt*nbl)*u.rad,\n np.ones(nt*nbl)*dec)\n uu, vv, ww = calc_uvw(blen, tobs, 'HADEC', np.zeros(nt)*u.rad, np.ones(nt)*dec)\n assert np.all(np.abs(uvw_blt[:, 0]-uu.T.flatten()) < 1e-6)\n assert np.all(np.abs(uvw_blt[:, 1]-vv.T.flatten()) < 1e-6)\n assert np.all(np.abs(uvw_blt[:, 2]-ww.T.flatten()) < 1e-6)\n"
] |
[
[
"numpy.abs",
"numpy.arange",
"numpy.tile",
"numpy.ones",
"numpy.array",
"numpy.zeros"
]
] |
JonathanAMichaels/NeuropixelsRegistration
|
[
"b2623f0777b12c72ab304f7f2c1477e9954ef54a"
] |
[
"python/estimate_displacement.py"
] |
[
"#################################\n# register raw data\n# input: raw data\n# output: registered raw data: float 32\n#################################\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm, notebook\nimport torch\nimport pickle\nimport os\n\nfrom scipy.signal import butter, filtfilt\nfrom numpy.fft import fft2, ifft2, fftshift, ifftshift # Python DFT\nimport pywt\n\nfrom skimage.restoration import denoise_nl_means, estimate_sigma\n\nfrom scipy.stats import norm\nfrom scipy.ndimage import shift, gaussian_filter\nfrom scipy.stats import zscore\nfrom scipy.spatial.distance import cdist\n\nfrom scipy.interpolate import griddata\n\nfrom utils import merge_filtered_files\n\n# function that wraps around all functions\n# reader: yass reader\ndef estimate_displacement(reader, geomarray, \n detection_threshold=6, \n num_chans_per_spike=4,\n do_destripe=True,\n do_denoise=True,\n do_subsampling=True,\n reg_win_num=5,\n reg_block_num=10,\n iteration_num=4,\n vert_smooth=3,\n horz_smooth=7,\n reader_type='yass', # also has an option 'spikeglx'\n save_raster_info=True,\n working_directory='./',\n resume_with_raster=False):\n \n if resume_with_raster:\n depths = np.load(os.path.join(working_directory, 'depths.npy'))\n times = np.load(os.path.join(working_directory, 'times.npy'))\n amps = np.load(os.path.join(working_directory, 'amps.npy'))\n widths = np.load(os.path.join(working_directory, 'widths.npy'))\n else:\n # spike detection: detection + deduplication\n spike_output_directory = os.path.join(working_directory, \"spikes\") # unified working directory\n if not os.path.exists(spike_output_directory):\n os.makedirs(spike_output_directory)\n \n raster_info_directory = working_directory\n if not os.path.exists(raster_info_directory):\n os.makedirs(raster_info_directory)\n\n # ts: a raw data batch of size (sampling frequency, n_channels)\n if reader_type == 'yass':\n n_batches = reader.n_batches\n for i in tqdm(range(n_batches)):\n ts = reader.read_data_batch(i)\n run_spike_detect(ts, geomarray, spike_output_directory, i, threshold=detection_threshold)\n elif reader_type == 'spikeglx':\n sf = int(reader.fs)\n n_batches = int(reader.ns / reader.fs) # recording length in seconds\n for i in tqdm(range(n_batches)):\n ts_memmap = reader._raw[sf*i:sf*(i+1),:-1]\n ts = np.empty(ts_memmap.shape, dtype=np.int16)\n ts[:] = ts_memmap\n run_spike_detect(ts, geomarray, spike_output_directory, i, threshold=detection_threshold)\n elif reader_type == 'None': # reader is directory to bin file\n second_bytesize = 2 * 385 * 30000\n n_batches = int(os.path.getsize(reader) / second_bytesize)\n for i in tqdm(range(n_batches)):\n ts = np.fromfile(reader, dtype=np.int16, count=385*30000, offset=385*30000*i)\n ts = ts.reshape((30000,-1))[:,:-1]\n run_spike_detect(ts, geomarray, spike_output_directory, i, threshold=detection_threshold)\n\n # generate raster\n depths, times, amps, widths = gen_raster_info(spike_output_directory, num_chans=num_chans_per_spike)\n if save_raster_info:\n # save depths, times, amps, widths\n np.save(os.path.join(raster_info_directory, 'depths.npy'), depths)\n np.save(os.path.join(raster_info_directory, 'times.npy'), times)\n np.save(os.path.join(raster_info_directory, 'amps.npy'), amps)\n np.save(os.path.join(raster_info_directory, 'widths.npy'), widths)\n\n # rarely we can get some NaNs\n if np.sum(np.isnan(times)) > 0:\n print('We have some NANs. Probably want to look into this')\n nan_log = np.isnan(times)\n depths = depths[~nan_log]\n times = times[~nan_log]\n amps = amps[~nan_log]\n widths = widths[~nan_log]\n\n raster = gen_raster(depths, times, amps, geomarray)\n if do_destripe:\n destriped = destripe(raster)\n else:\n destriped = raster\n \n if do_denoise:\n denoised = cheap_anscombe_denoising(destriped)\n else:\n denoised = destriped\n # decentralized registration\n total_shift = decentralized_registration(denoised, \n win_num=reg_win_num, # change for non-rigid registration\n reg_block_num=reg_block_num, # change for non-rigid registration\n iter_num=iteration_num,\n vert_smooth=vert_smooth,\n horz_smooth=horz_smooth,\n working_directory=working_directory)\n \n np.save(working_directory + 'total_shift.npy', total_shift)\n \n return total_shift\n\n\n# function that checks raster plot\n# reader: yass reader\ndef check_raster(reader, geomarray,\n dtype = \"int16\",\n detection_threshold=6, \n num_chans_per_spike=4,\n do_destripe=True,\n do_denoise=True,\n reader_type='yass', # also has an option 'spikeglx'\n working_directory='./',\n save_raster_info=True):\n \n # spike detection: detection + deduplication\n spike_output_directory = os.path.join(working_directory, \"spikes\")\n if not os.path.exists(spike_output_directory):\n os.makedirs(spike_output_directory)\n \n raster_info_directory = working_directory\n if not os.path.exists(raster_info_directory):\n os.makedirs(raster_info_directory)\n\n # ts: a raw data batch of size (sampling frequency, n_channels)\n if reader_type == 'yass':\n n_batches = reader.n_batches\n for i in tqdm(range(n_batches)):\n ts = reader.read_data_batch(i)\n run_spike_detect(ts, geomarray, spike_output_directory, i, threshold=detection_threshold)\n elif reader_type == 'spikeglx':\n sf = int(reader.fs)\n n_batches = int(reader.ns / reader.fs) # recording length in seconds\n for i in tqdm(range(n_batches)):\n ts_memmap = reader._raw[sf*i:sf*(i+1),:-1]\n ts = np.empty(ts_memmap.shape, dtype=np.int16)\n ts[:] = ts_memmap\n run_spike_detect(ts, geomarray, spike_output_directory, i, threshold=detection_threshold)\n elif reader_type == 'None': # reader is directory to bin file\n if dtype == 'int16':\n second_bytesize = 2 * 385 * 30000\n elif dtype == 'float32':\n second_bytesize = 4 * 384 * 30000\n n_batches = int(os.path.getsize(reader) / second_bytesize)\n for i in tqdm(range(n_batches)):\n if dtype == 'int16':\n ts = np.fromfile(reader, dtype=np.int16, count=385*30000, offset=385*30000*i)\n elif dtype == 'float32':\n ts = np.fromfile(reader, dtype=np.float32, count=384*30000, offset=384*30000*i)\n ts = ts.reshape((30000,-1))[:,:-1]\n run_spike_detect(ts, geomarray, spike_output_directory, i, threshold=detection_threshold)\n \n # generate raster\n depths, times, amps, widths = gen_raster_info(spike_output_directory, num_chans=num_chans_per_spike)\n if save_raster_info:\n # save depths, times, amps, widths\n np.save(os.path.join(raster_info_directory, 'depths.npy'), depths)\n np.save(os.path.join(raster_info_directory, 'times.npy'), times)\n np.save(os.path.join(raster_info_directory, 'amps.npy'), amps)\n np.save(os.path.join(raster_info_directory, 'widths.npy'), widths)\n\n raster = gen_raster(depths, times, amps, geomarray)\n \n if do_destripe:\n destriped = destripe(raster)\n else:\n destriped = raster\n \n if do_denoise:\n denoised = cheap_anscombe_denoising(destriped)\n else:\n denoised = destriped\n\n return denoised\n\n\ndef register(reader, geomarray, total_shift,\n registration_interp='linear', # also has an option 'gpr'\n reader_type='yass',\n registration_type='non_rigid',\n working_directory='./'):\n \n # ts: a raw data batch of size (sampling frequency, n_channels)\n if reader_type == 'yass':\n n_batches = reader.n_batches\n elif reader_type == 'spikeglx':\n n_batches = int(reader.ns / reader.fs) # recording length in seconds\n elif reader_type == 'None': # reader is directory to bin file\n second_bytesize = 2 * 385 * 30000\n n_batches = int(os.path.getsize(reader) / second_bytesize)\n \n # register raw data\n registered_output_directory = os.path.join(working_directory, \"registered\")\n if not os.path.exists(registered_output_directory):\n os.makedirs(registered_output_directory)\n \n register_data(reader, \n total_shift, \n geomarray, \n registered_output_directory, \n registration_interp,\n n_batches,\n reader_type,\n registration_type)\n \n merge_filtered_files(registered_output_directory, registered_output_directory, delete = True)\n\n# detects + deduplicates spikes\ndef spike_detect(X, geom, radius, timeradius):\n spike = {}\n spike_chans = {}\n spike_times = {}\n spike_amps = {}\n spike_central_coor = {}\n spike_central_time = {}\n spike_central_amplitude = {}\n spike_central_chan = {}\n \n # connected spike event grabbing\n nonzero = np.nonzero(X)\n I, T = nonzero[0], nonzero[1]\n V = X[nonzero]\n\n t = 0\n while I.shape[0] > 0:\n t += 1\n idx = np.where(np.abs(T - T[0]) < timeradius)\n #idx2 = np.where(np.linalg.norm(geom[I[idx]] - geom[I[0]], axis=1) < radius)\n idx2 = np.where(cdist(geom[I[idx]], geom[I[0]][np.newaxis,:], 'euclidean')[:,0] < radius)\n \n spike_chans[t] = I[idx[0][idx2]]\n spike_times[t] = T[idx[0][idx2]]\n spike_amps[t] = V[idx[0][idx2]]\n\n I = np.delete(I, idx[0][idx2])\n T = np.delete(T, idx[0][idx2])\n V = np.delete(V, idx[0][idx2])\n # print('spike event grabbing done!')\n\n # de-duplication\n for t in spike_chans.keys():\n spike_central_coor[t] = 0\n spike_central_time[t] = 0\n\n r = (spike_amps[t]/spike_amps[t].sum())[:,np.newaxis]\n spike_central_coor[t] += (geom[spike_chans[t]]*r).sum(0)\n spike_central_time[t] += (spike_times[t]*r[:,0]).sum()\n\n spike_central_amplitude[t] = spike_amps[t].max()\n #idx = np.linalg.norm(geom - spike_central_coor[t], axis=1).argmin()\n idx = cdist(geom, spike_central_coor[t][np.newaxis,:], 'euclidean')[:,0].argmin()\n spike_central_chan[t] = idx\n\n spike['chans'] = spike_chans\n spike['times'] = spike_times\n spike['amps'] = spike_amps\n spike['central_coor'] = spike_central_coor\n spike['central_time'] = spike_central_time\n spike['central_amplitude'] = spike_central_amplitude\n spike['central_chan'] = spike_central_chan\n \n return spike\n\n# butterworth filtering\ndef butterworth_filtering(ts, low_frequency=300, high_frequency=2000, order=3, sampling_frequency=30000):\n low = float(low_frequency) / sampling_frequency * 2\n high = float(high_frequency) / sampling_frequency * 2\n b,a = butter(order, [low, high], btype='bandpass', analog=False)\n \n T,C = ts.shape\n output = np.zeros((T,C), 'float32')\n for c in range(C):\n output[:, c] = filtfilt(b, a, ts[:,c])\n \n return output\n\ndef run_spike_detect(ts, geom, output_directory, batch_id, threshold=6, sf=30000,\n low_frequency=300, high_frequency=2000, order=3,\n spatial_radius=100, time_radius=100, decorr_iter=2):\n \n if os.path.exists(os.path.join(\n output_directory, \"spike_{}.pkl\".format(str(batch_id).zfill(6)))):\n return\n mp2d= torch.nn.MaxPool2d(kernel_size = [25, 1], stride = [2,1]).cuda()\n ts = butterworth_filtering(ts, low_frequency, high_frequency, order, sf)\n for i in range(decorr_iter):\n ts = zscore(ts, axis=1)\n ts = zscore(ts, axis=0)\n \n ts = torch.from_numpy(ts).cuda().float()\n ptp_sliding = mp2d(ts[None])[0] + mp2d(-ts[None])[0]\n ptp_sliding = np.asarray(ptp_sliding.cpu().T)\n ptp_sliding[np.where(ptp_sliding <= threshold)] = 0\n \n # args: ptp_sliding, geomarray, spatial_radius, time_radius\n spike = spike_detect(ptp_sliding, geom, spatial_radius, time_radius)\n \n fname = os.path.join(output_directory, \"spike_{}.pkl\".format(str(batch_id).zfill(6)))\n\n with open(fname, 'wb') as f:\n pickle.dump(spike, f, protocol=pickle.HIGHEST_PROTOCOL)\n\n\ndef gen_raster_info(saved_directory, sf=30000, num_chans=4, delete=True):\n depths = []\n times = []\n amps = []\n widths = []\n \n filenames = os.listdir(saved_directory)\n filenames_sorted = sorted(filenames)\n \n for fname in tqdm(filenames_sorted):\n t = int(fname.split('_')[-1].rstrip('.pkl'))\n with open(os.path.join(saved_directory, fname), 'rb') as f:\n spike = pickle.load(f)\n for j in spike['chans'].keys():\n if np.unique(spike['chans'][j]).shape[0] > num_chans:\n depths.append(spike['central_coor'][j][1])\n widths.append(spike['central_coor'][j][0])\n times.append(t + spike['central_time'][j]/(sf/2))\n amps.append(spike['central_amplitude'][j])\n if delete==True:\n os.remove(os.path.join(saved_directory, fname))\n\n depths = np.asarray(depths)\n times = np.asarray(times)\n amps = np.asarray(amps)\n widths = np.asarray(widths)\n \n return depths, times, amps, widths\n\ndef gen_raster(depths, times, amps, geom):\n max_t = np.ceil(times.max()).astype(int)\n D = geom[:,1].max().astype(int)\n raster = np.zeros((D,max_t))\n raster_count = np.zeros((D,max_t))\n for i in tqdm(range(max_t)):\n idx = np.intersect1d(np.where(times > i)[0], np.where(times < i+1)[0])\n\n for j in idx:\n depth = int(np.floor(depths[j]))\n amp = amps[j]\n raster[depth,i] += amp\n raster_count[depth,i] += 1\n\n raster_count[np.where(raster_count == 0)] = 1\n \n return raster/raster_count\n\ndef cheap_anscombe_denoising(z, sigma=1, h=0.1, estimate_sig=True, fast_mode=True, multichannel=False):\n minmax = (z - z.min()) / (z.max() - z.min()) # scales data to 0-1\n \n # Gaussianizing Poissonian data\n z_anscombe = 2. * np.sqrt(minmax + (3. / 8.))\n \n if estimate_sig:\n sigma = np.mean(estimate_sigma(z_anscombe, multichannel=multichannel))\n print(\"estimated sigma: {}\".format(sigma))\n # Gaussian denoising\n z_anscombe_denoised = denoise_nl_means(z_anscombe, h=h*sigma, sigma=sigma, fast_mode=fast_mode) # NL means denoising\n\n z_inverse_anscombe = (z_anscombe_denoised / 2.)**2 + 0.25 * np.sqrt(1.5) * z_anscombe_denoised**-1 - (11. / 8.) * z_anscombe_denoised**-2 +(5. / 8.) * np.sqrt(1.5) * z_anscombe_denoised**-3 - (1. / 8.)\n \n z_inverse_anscombe_scaled = ((z.max() - z.min()) * z_inverse_anscombe) + z.min()\n \n return z_inverse_anscombe_scaled\n\ndef destripe(raster):\n D, W = raster.shape\n LL0 = raster\n wlet = 'db5'\n coeffs = pywt.wavedec2(LL0, wlet)\n L = len(coeffs)\n for i in range(1,L):\n HL = coeffs[i][1] \n Fb = fft2(HL) \n Fb = fftshift(Fb)\n mid = Fb.shape[0]//2\n Fb[mid,:] = 0\n Fb[mid-1,:] /= 3\n Fb[mid+1,:] /= 3\n Fb = ifftshift(Fb) \n coeffs[i]= (coeffs[i][0], np.real(ifft2(Fb)), coeffs[i][2] )\n LL = pywt.waverec2(coeffs, wlet)\n LL = LL[:D,:W]\n \n destriped = np.zeros_like(raster)\n destriped[:D,:W] = LL\n return destriped\n\ndef get_gaussian_window(height, width, loc, scale=1):\n window = np.zeros((height,width))\n for i in range(height):\n window[i] = norm.pdf(i, loc=loc, scale=scale)\n return window / window.max()\n\ndef calc_displacement_matrix_raster(raster, nbins=1, disp = 400, step_size = 1, batch_size = 1):\n T = raster.shape[0]\n possible_displacement = np.arange(-disp, disp + step_size, step_size)\n raster = torch.from_numpy(raster).cuda().float()\n c2d = torch.nn.Conv2d(in_channels = 1, out_channels = T, kernel_size = [nbins, raster.shape[-1]], stride = 1,\n padding = [0, possible_displacement.size//2], bias = False).cuda().requires_grad_(False)\n c2d.weight[:,0] = raster\n displacement = np.zeros([T, T])\n for i in notebook.tqdm(range(T//batch_size)):\n res = c2d(raster[i*batch_size:(i+1)*batch_size,None])[:,:,0,:].argmax(2)\n displacement[i*batch_size:(i+1)*batch_size] = possible_displacement[res.cpu()]\n del res\n del c2d\n del raster\n torch.cuda.empty_cache()\n return displacement\n\ndef calc_displacement(displacement, n_iter = 1000):\n p = torch.zeros(displacement.shape[0]).cuda()\n displacement = torch.from_numpy(displacement).cuda().float()\n n_batch = displacement.shape[0]\n pprev = p.clone()\n for i in notebook.tqdm(range(n_iter)):\n repeat1 = p.repeat_interleave(n_batch).reshape((n_batch, n_batch))\n repeat2 = p.repeat_interleave(n_batch).reshape((n_batch, n_batch)).T\n mat_norm = displacement + repeat1 - repeat2\n p += 2*(torch.sum(displacement-torch.diag(displacement), dim=1) - (n_batch-1)*p)/torch.norm(mat_norm)\n del mat_norm\n del repeat1\n del repeat2\n if torch.allclose(pprev, p):\n break\n else:\n del pprev\n pprev = p.clone()\n disp = np.asarray(p.cpu())\n del p\n del pprev\n del displacement\n torch.cuda.empty_cache()\n return disp\n\ndef shift_x(x, shift_amt):\n shifted = np.zeros_like(x)\n for t in range(x.shape[1]):\n col = x[:,t]\n sh = shift_amt[t]\n shifted[:,t] = shift(col, sh)\n\n return shifted\n\ndef register_raster(raster, total_shift, blocks):\n raster_sh = np.zeros_like(raster)\n for k in notebook.tqdm(range(1, blocks.shape[0])):\n cur = blocks[k]\n prev = blocks[k-1]\n sh = np.mean(-total_shift[prev:cur], axis=0)\n roi = np.zeros_like(raster)\n roi[prev:cur] = raster[prev:cur]\n raster_sh += shift_x(roi, sh)\n return raster_sh\n\ndef save_registered_raster(raster_sh, i, output_directory):\n fname = os.path.join(output_directory, \"raster_{}.png\".format(str(i+1).zfill(6)))\n print('plotting...')\n plt.figure(figsize=(16, 10))\n plt.imshow(raster_sh, vmin=0, vmax=10, aspect=\"auto\", cmap=plt.get_cmap('inferno'))\n plt.ylabel(\"depth\", fontsize=16)\n plt.xlabel(\"time\", fontsize=16)\n plt.savefig(fname,bbox_inches='tight')\n plt.close()\n \ndef decentralized_registration(raster, win_num=1, reg_block_num=1, iter_num=4, vert_smooth=3, horz_smooth=7,\n working_directory='./'):\n D, T = raster.shape\n \n # get windows\n window_list = []\n if win_num == 1:\n window_list.append(np.ones_like(raster))\n else:\n space = int(D//(win_num+1))\n locs = np.linspace(space, D-space, win_num, dtype=np.int32)\n for i in range(win_num):\n window = get_gaussian_window(D, T, locs[i], scale=D/(0.5*win_num))\n window_list.append(window)\n window_sum = np.sum(np.asarray(window_list), axis=0)\n\n shifts = np.zeros((win_num, T))\n total_shift = np.zeros_like(raster)\n \n raster_i = gaussian_filter(raster, sigma=(vert_smooth, horz_smooth), order=0)\n \n reg_block_num += 1\n blocks = np.linspace(0, D, reg_block_num, dtype=np.int64)\n \n output_directory = os.path.join(working_directory, \"decentralized_raster\")\n if not os.path.exists(output_directory):\n os.makedirs(output_directory)\n \n save_registered_raster(raster, -1, output_directory)\n \n for i in notebook.tqdm(range(iter_num)):\n \n shift_amt = np.zeros_like(raster)\n \n for j, w in enumerate(window_list):\n w_raster = w*raster_i\n displacement_matrix = calc_displacement_matrix_raster((w_raster).T[:,np.newaxis,:])\n disp = calc_displacement(displacement_matrix)\n shift_amt += w * disp[np.newaxis,:]\n shifts[j] += disp\n \n total_shift += (shift_amt / window_sum)\n\n raster_sh = register_raster(raster, total_shift, blocks)\n \n raster_i = gaussian_filter(raster_sh, sigma=(vert_smooth, horz_smooth), order=0)\n \n save_registered_raster(raster_sh, i, output_directory)\n \n return total_shift\n\ndef register_data(reader, total_shift, geomarray, \n registered_output_directory, interp, \n n_batches, reader_type, \n registration_type='non_rigid'):\n D, T = total_shift.shape\n ys = geomarray[:,1]\n n_chans = ys.shape[0]\n \n if registration_type == 'non_rigid':\n win_num = np.unique(ys).shape[0]\n\n # get windows\n window_list = []\n for i in tqdm(range(n_chans)):\n window = get_gaussian_window(D, T, ys[i], scale=D/(0.5*win_num))\n window_list.append(window)\n\n estimated_displacement = np.zeros((n_chans, total_shift.shape[1]))\n for i in tqdm(range(n_chans)):\n window = window_list[i]\n w_disp = total_shift * window\n w_disp = w_disp.sum(0) / window.sum(0)\n estimated_displacement[i] = w_disp\n \n elif registration_type == 'rigid':\n estimated_displacement = np.zeros((n_chans, total_shift.shape[1]))\n for i in tqdm(range(n_chans)):\n estimated_displacement[i] = total_shift[0]\n \n for batch_id in tqdm(range(int(n_batches))):\n if interp == 'linear':\n register_data_linear(\n batch_id, \n reader, \n registered_output_directory, \n estimated_displacement,\n geomarray,\n n_chans,\n reader_type\n )\n elif interp == 'gpr':\n pass\n\n\ndef register_data_linear(i, reader, registered_output_directory, estimated_displacement, geomarray, n_chans, reader_type):\n if reader_type == 'yass':\n ts = reader.read_data_batch(i)\n elif reader_type == 'spikeglx':\n sf = int(reader.fs)\n ts_memmap = reader._raw[sf*i:sf*(i+1),:-1]\n ts = np.empty(ts_memmap.shape, dtype=np.int16)\n ts[:] = ts_memmap\n elif reader_type == 'None': # reader is directory to bin file\n ts = np.fromfile(reader, dtype=np.int16, count=385*30000, offset=385*30000*i)\n ts = ts.reshape((30000,-1))[:,:-1]\n ts = ts.T\n disp = np.concatenate((np.zeros(n_chans)[:,None],estimated_displacement[:,i][:,None]), axis=1)\n ts = griddata(geomarray, ts, geomarray + disp, method = 'linear', fill_value = 0)\n ts = np.vstack([ts, np.zeros(shape=(1, ts.shape[1]))]) # spikeglx reader doesn't return the sync channel (385),\n # so I'm adding it back to preserve consistency with kilosort\n ts = np.round(ts).astype(np.int16) # To save disk space we convert back to int16 -\n # at the price of losing some precision\n np.save(os.path.join(\n registered_output_directory,\n \"registered_{}.npy\".format(\n str(i).zfill(6))), ts.T.astype(np.int16)) # was float32\n"
] |
[
[
"numpy.sqrt",
"numpy.linspace",
"torch.zeros",
"numpy.asarray",
"scipy.stats.zscore",
"matplotlib.pyplot.get_cmap",
"numpy.fft.fftshift",
"numpy.round",
"numpy.zeros_like",
"numpy.mean",
"scipy.interpolate.griddata",
"torch.allclose",
"numpy.where",
"torch.norm",
"numpy.ones_like",
"numpy.unique",
"numpy.arange",
"torch.from_numpy",
"numpy.save",
"scipy.signal.butter",
"numpy.fft.ifftshift",
"matplotlib.pyplot.close",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.fft.fft2",
"numpy.nonzero",
"numpy.isnan",
"torch.nn.Conv2d",
"torch.cuda.empty_cache",
"matplotlib.pyplot.savefig",
"scipy.spatial.distance.cdist",
"numpy.delete",
"numpy.floor",
"torch.diag",
"matplotlib.pyplot.ylabel",
"numpy.fromfile",
"scipy.ndimage.gaussian_filter",
"scipy.signal.filtfilt",
"scipy.stats.norm.pdf",
"numpy.abs",
"numpy.fft.ifft2",
"torch.nn.MaxPool2d",
"matplotlib.pyplot.xlabel",
"scipy.ndimage.shift",
"numpy.empty"
]
] |
pressler-vsc/sarpy
|
[
"fa6c951c42b9a7d9df2edfa53c771494cb0246fb"
] |
[
"docs/examples/polygon_example.py"
] |
[
"import numpy\nfrom matplotlib import pyplot\nimport time\n\nfrom sarpy.geometry.geometry_elements import Polygon\n\n\ndef generate_random_polygon(segment_count=12):\n \"\"\"\n Generate the coordinates for a random polygon going from (-1, 0) to (1, 0) and back.\n It will be contained in square [-1, 1] x [-1, 1].\n\n Parameters\n ----------\n segment_count : int\n\n Returns\n -------\n numpy.ndarray\n \"\"\"\n\n # starts at (-1, 0) and goes up to (1, 0) with negative y coordinates by <segment_count> random steps,\n # then back to (-1, 0) with positive y coordinates by <segment_count> random steps.\n coords = numpy.zeros((2 * segment_count + 1, 2), dtype=numpy.float64)\n # fill in the randomly generated x coordinates\n x1 = numpy.random.rand(segment_count + 1)\n x1[0] = 0\n l1 = numpy.cumsum(x1)\n coords[:segment_count+1, 0] = -1 + 2*l1/l1[-1]\n x2 = numpy.cumsum(numpy.random.rand(segment_count))\n coords[segment_count + 1:, 0] = 1 - 2*x2/x2[-1]\n # fill in the randomly generated y coordinates\n coords[1:segment_count, 1] = -numpy.random.rand(segment_count - 1)\n coords[segment_count+1:2*segment_count, 1] = numpy.random.rand(segment_count - 1)\n return coords\n\n\ndef basic_check():\n \"\"\"\n Example for checks on a basic polygon.\n\n Returns\n -------\n None\n \"\"\"\n\n # create our polygon object with coordinates bounded by square [0, 1]x[-1, 1]\n coords = generate_random_polygon()\n poly = Polygon(coordinates=[coords, ])\n\n #############################\n # perform random samples check\n samples = 10000\n\n pts = 2.2*numpy.random.rand(samples, 2) - 1.1\n\n start = time.time()\n in_poly_condition = poly.contain_coordinates(pts[:, 0], pts[:, 1])\n lapsed = time.time() - start\n print('basic poly: lapsed = {}, lapsed/point = {}'.format(lapsed, lapsed/samples))\n\n ###########################\n # perform grid check\n grid_samples = 1001\n x_grid = numpy.linspace(-1.1, 1.1, grid_samples)\n y_grid = numpy.linspace(-1.1, 1.1, grid_samples)\n\n start = time.time()\n in_poly_condition2 = poly.grid_contained(x_grid[:-1], y_grid[:-1])\n lapsed = time.time() - start\n print('basic poly: lapsed = {}, lapsed/point = {}'.format(lapsed, lapsed/((grid_samples - 1)**2)))\n\n #############################\n # visualize results\n fig, axs = pyplot.subplots(nrows=2, ncols=1, sharex='col', sharey='col')\n fig.suptitle('Basic polygon example')\n axs[0].scatter(pts[in_poly_condition, 0], pts[in_poly_condition, 1], color='r', marker='.', s=16)\n axs[0].scatter(pts[~in_poly_condition, 0], pts[~in_poly_condition, 1], color='b', marker='.', s=16)\n axs[0].plot(coords[:, 0], coords[:, 1], 'k-')\n y2d, x2d = numpy.meshgrid(y_grid, x_grid, indexing='xy')\n axs[1].pcolormesh(x2d, y2d, in_poly_condition2, cmap='jet')\n axs[1].plot(coords[:, 0], coords[:, 1], 'k-', lw=2, zorder=99)\n pyplot.show()\n\n\ndef compound_poly_check():\n \"\"\"\n Example for compound polygon with a hole in it.\n\n Returns\n -------\n None\n \"\"\"\n\n # create our polygon object with coordinates bounded by square [0, 1]x[-1, 1]\n outer_coords = numpy.array([\n [-1, 0], [-0.5, -1], [0.5, -1], [1, 0], [0.5, 1], [-0.5, 1], [-1, 0],], dtype='float64')\n inner_coords = 0.5*generate_random_polygon()\n poly = Polygon(coordinates=[outer_coords, inner_coords])\n\n #############################\n # perform random samples check\n samples = 10000\n pts = 2.2*numpy.random.rand(samples, 2) - 1.1\n\n start = time.time()\n in_poly_condition = poly.contain_coordinates(pts[:, 0], pts[:, 1])\n lapsed = time.time() - start\n print('compound poly: lapsed = {}, lapsed/point = {}'.format(lapsed, lapsed/samples))\n\n ###########################\n # perform grid check\n grid_samples = 1001\n x_grid = numpy.linspace(-1.1, 1.1, grid_samples)\n y_grid = numpy.linspace(-1.1, 1.1, grid_samples)\n\n start = time.time()\n in_poly_condition2 = poly.grid_contained(x_grid[:-1], y_grid[:-1])\n lapsed = time.time() - start\n print('compound poly: lapsed = {}, lapsed/point = {}'.format(lapsed, lapsed/((grid_samples - 1)**2)))\n\n #############################\n # visualize results\n fig, axs = pyplot.subplots(nrows=2, ncols=1, sharex='col', sharey='col')\n fig.suptitle('Compound polygon example')\n axs[0].scatter(pts[in_poly_condition, 0], pts[in_poly_condition, 1], color='r', marker='.', s=16)\n axs[0].scatter(pts[~in_poly_condition, 0], pts[~in_poly_condition, 1], color='b', marker='.', s=16)\n axs[0].plot(outer_coords[:, 0], outer_coords[:, 1], 'k-')\n axs[0].plot(inner_coords[:, 0], inner_coords[:, 1], 'k-')\n y2d, x2d = numpy.meshgrid(y_grid, x_grid, indexing='xy')\n axs[1].pcolormesh(x2d, y2d, in_poly_condition2, cmap='jet')\n axs[1].plot(outer_coords[:, 0], outer_coords[:, 1], 'k-')\n axs[1].plot(inner_coords[:, 0], inner_coords[:, 1], 'k-')\n pyplot.show()\n\n\nif __name__ == '__main__':\n basic_check()\n compound_poly_check()\n"
] |
[
[
"numpy.linspace",
"matplotlib.pyplot.subplots",
"numpy.cumsum",
"numpy.random.rand",
"numpy.array",
"numpy.meshgrid",
"numpy.zeros",
"matplotlib.pyplot.show"
]
] |
lyj911111/OpenCV_Project
|
[
"9acbfbf666188b6ebb7f2ec4500bb3ab3d2994b9"
] |
[
"AceVision/new/Air3239/Air3239_v2.py"
] |
[
"# -*- coding: utf-8 -*-\nimport numpy as np # pip install numpy==1.15.4\nimport cv2 # pip install opencv-python==3.4.4.19\nfrom PIL import Image as Img # pip install image==1.5.27\nimport pyzbar.pyzbar as pyzbar # pip install pyzbar==0.1.7\nfrom more_itertools import unique_everseen # pip install more_itertools==4.3.0\nimport serial # pip install pyserial==3.4\nfrom PIL import ImageTk\nfrom math import *\nimport datetime\nimport time\nimport os\nfrom tkinter import filedialog\nfrom tkinter import *\nimport socket\nimport copy\nimport sys\n\nimport math\n\nimport pickle\n\n\n# 데이터를 저장할 위치(서버저장)\nstore_local_location = \"D:/Air3239/\"\nstore_server_location = \"//192.168.105.4/Multimedia/Air3239/\"\nSerial_No = ''\npre_Serial_No = '1'\nPLC_rx = 'ready'\nPLC_tx_OK = '1'\nPLC_tx_NG = '2'\nprotocol = 0\nport_num = ''\nPLC_ready = ''\n\ncheck_protocol = False\nbarcode_set = False\nBig_ROI_setting = False\nSmall_ROI_setting = False\nexcept_big_setting = False\nexcept_small_setting = False\ndetect_once_big = False\ndetect_once_small = False\nrivet_detect = False\ncheck_set = True\nPLC_sensor = False\ncheck_result_label = False\ncheck_local_path = False\ncheck_server_path = False\nload_setting_flag = False\n\ncheck_rivet_result = 0\nPLC_flag = 0\ncount_make_log = 2\ncount_make_folder = 2\ncount_mouse = 0\nsave_rivet_center_flag_big = 0\nsave_rivet_center_flag_small = 0\nStart_except_box_big = 0\nStart_except_box_small = 0\ntact_time_flag = 0\nstart_time = 0\ntact_time = 0\nplc_time = 0\ncnt = 0\nrotate = 0\nplc_check_time = 0\n\ncheck_barcode_area = 0\ncheck_year = 0\ncheck_month = 0\ncheck_day = 0\ncheck_make_folder = 0\ncheck_result = 0\npre_day = 0\n\naccum = 0\npre_accum = 1000\ncount_pass_rivet = 0\ncount_fail_rivet = 0\n\nbar_x1 = 0\nbar_y1 = 0\nbar_x2 = 0\nbar_y2 = 0\n\ncircle_center_list = []\nrivet_empty_list = []\ncircle_center_area_list = []\n\nBig_ROI_list = []\nSmall_ROI_list = []\nexcept_box_big = []\nexcept_box_small = []\nex_w_big = 0\nex_w_small = 0\nex_h_big = 0\nex_h_small = 0\nwhole_circle_list_big = []\nwhole_circle_list_small = []\nexcept_center_list_big = []\nexcept_center_list_small = []\ncircle_area_list_big = []\ncircle_area_list_small = []\nexcept_box_list_big = []\nexcept_box_list_small = []\nrect_list_big = []\nrect_list_small = []\nexcept_list_big = []\nexcept_list_small = []\nsave_delete_item_list_big = []\nsave_delete_item_list_small = []\ntemp_whole_circle_big = []\ntemp_whole_circle_small = []\nexcept_box_wh_big = []\nexcept_box_wh_small = []\n\n\n# 2대의 카메라 해상도 설정 및 출력.\ncap0 = cv2.VideoCapture(0)\ncap0.set(cv2.CAP_PROP_FRAME_WIDTH, 4024) # Width 4024\ncap0.set(cv2.CAP_PROP_FRAME_HEIGHT, 3036) # Height 3036\nprint(\"첫번째 카메라 현재 해상도 %d x %d\" %(cap0.get(3), cap0.get(4)))\n\n\ncap1 = cv2.VideoCapture(1)\ncap1.set(cv2.CAP_PROP_FRAME_WIDTH, 4024) # Width 4024\ncap1.set(cv2.CAP_PROP_FRAME_HEIGHT, 3036) # Height 3036\nprint(\"두번째 카메라 현재 해상도 %d x %d\" %(cap1.get(3), cap1.get(4)))\n\n\n\nser1 = serial.Serial(\n port='COM5',\n baudrate=9600,\n parity=serial.PARITY_NONE,\\\n stopbits=serial.STOPBITS_ONE,\\\n bytesize=serial.EIGHTBITS,\\\n)\n\n\ndef light_on():\n DATA = chr(0x02) + chr(0x43) + chr(0x48) + chr(0x41) + chr(0x53) + chr(0x32) + chr(0x35) + chr(0x35) + chr(\n 0x32) + chr(0x35) + chr(0x35) + chr(0x32) + chr(0x35) + chr(0x35) + chr(0x32) + chr(0x35) + chr(0x35) + chr(\n 0x03)\n if ser1.readable():\n DATA = DATA.encode()\n ser1.write(DATA) # 시리얼 데이터 전송\n\n\ndef light_off():\n DATA = chr(0x02) + chr(0x43) + chr(0x48) + chr(0x41) + chr(0x53) + chr(0x30) + chr(0x30) + chr(0x30) + chr(\n 0x30) + chr(0x30) + chr(0x30) + chr(0x30) + chr(0x30) + chr(0x30) + chr(0x30) + chr(0x30) + chr(0x30) + chr(\n 0x03)\n\n if ser1.readable():\n DATA = DATA.encode()\n ser1.write(DATA) # 시리얼 데이터 전송\n\n\n\n\ndef get_today():\n now = time.localtime()\n local_time = \"%04d-%02d-%02d\" % (now.tm_year, now.tm_mon, now.tm_mday)\n return local_time\n\n\ndef make_folder(folder_name):\n if not os.path.isdir(folder_name):\n os.mkdir(folder_name)\n\n\ndef check_time_value():\n time = datetime.datetime.now()\n year = time.year\n month = time.month\n day = time.day\n hour = time.hour\n minute = time.minute\n sec = time.second\n\n return year, month, day, hour, minute, sec\n\n\ndef leave_log(check):\n global check_year, check_month, check_day, f\n global today, pre_day, localtime\n global check_make_folder, folder_name\n global foldername_pass, foldername_fail, foldername_log\n global open_foldername_pass, open_foldername_fail, open_foldername_log\n global count_make_folder, count_make_log\n\n if check == 1:\n store_location = store_local_location + '/'\n elif check == 2:\n store_location = store_server_location + '/'\n\n year, month, day, hour, minute, sec = check_time_value()\n\n fn = datetime.datetime.now()\n folder_name = str(fn.year) + \"-\" + str(\"%02d\" % fn.month) + \"-\" + str(\"%02d\" % fn.day)\n\n if pre_day != day:\n check_make_folder = 0\n count_make_folder = 2\n count_make_log = 2\n\n if check_make_folder == 0:\n today = get_today()\n foldername_today = store_location + today\n make_folder(foldername_today)\n foldername_barcode = store_location + today + \"/rivet\"\n make_folder(foldername_barcode)\n foldername_pass = store_location + today + \"/rivet\" + \"/pass\"\n make_folder(foldername_pass)\n foldername_fail = store_location + today + \"/rivet\" + \"/fail\"\n make_folder(foldername_fail)\n count_make_folder -= 1\n\n if count_make_folder == 0:\n check_make_folder = 1\n\n filename = str(year) + str(\"%02d\" % month) + str(\"%02d\" % day)\n if day != check_day or count_make_log != 0:\n # print(\"새로운 로그 파일 생성\")\n today = get_today()\n foldername_log = store_location + today + \"/rivet\" + \"/log\"\n make_folder(foldername_log)\n f = open(store_location + today + \"/rivet/log/log_%s.txt\" % filename, 'w', encoding='utf - 8')\n data = \"시리얼 넘버 // 판독 시간 // 누적 판독량 // 정상 // 불량 \\n\"\n f.write(data)\n\n check_year = datetime.datetime.now().year\n check_month = datetime.datetime.now().month\n check_day = datetime.datetime.now().day\n pre_day = check_day\n\n count_make_log -= 1\n\n\n if check == 1:\n open_foldername_pass = store_local_location + '/' + today + \"/rivet\" + \"/pass\"\n open_foldername_fail = store_local_location + '/' + today + \"/rivet\" + \"/fail\"\n open_foldername_log = store_local_location + '/' + today + \"/rivet\" + \"/log\"\n\n\n\n # print(store_location)\n f = open(store_location + today + \"/rivet/log/log_%s.txt\" % filename, 'a')\n localtime = str(year) + \"-\" + str(\"%02d\" % month) + \"-\" + str(\"%02d\" % day) + \" \" + str(\"%02d\" % hour) + \":\" + str(\n \"%02d\" % minute) + \":\" + str(\"%02d\" % sec)\n data = str(Serial_No) + \" // \" + str(localtime) + \" // \" + str(\"%04d\" % accum) + \" // \" + str(\n \"%04d\" % count_pass_rivet) + \" // \" + str(\"%04d\" % count_fail_rivet) + \"\\n\"\n f.write(data)\n\n '''\n RV_SN.insert(20, Serial_No)\n RV_TIME.insert(20, localtime)\n RV_ACC.insert(20, accum)\n RV_PASS.insert(20, count_pass_rivet)\n RV_NG.insert(20, count_fail_rivet)\n RV_TACT.insert(20, tact_time)\n '''\n\n f.close()\n\n\ndef Reformat_Image(image, ratio_w, ratio_h):\n height, width = image.shape[:2]\n width = int(width * ratio_w)\n height = int(height * ratio_h)\n # res = cv2.resize(image, (width, height), interpolation=cv2.INTER_AREA)\n\n res = cv2.resize(image, (width, height), interpolation=cv2.INTER_LINEAR)\n\n return res\n\n\ndef TCP_IP():\n global PORT, sock\n global PLC_sensor\n\n PORT = int(PORT)\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect((HOST, PORT))\n receive_data = sock.recv(1024) # 서버로 부터 오는 데이터\n receive_data = receive_data.decode('utf-8')\n # print(\"서버에서 받은 메세지 : \", receive_data) # 서버에서 받은 데이터를 출력.\n\n receive_data = receive_data.lower()\n\n # print(\"최종 receive_data : \", receive_data)\n if receive_data == PLC_rx:\n PLC_sensor = True\n\n\ndef RS_232():\n global PLC_sensor, PLC_ready, PLC_flag\n global plc_check_time, port_num, Serial_No\n # global ser, check_detect, port_num\n # global PLC_rx, PLC_tx_OK, PLC_tx_NG\n\n res = ser.readline()\n # PLC_ready = res.lower()\n PLC_ready = res.decode() # 공백이 있을시 추가.\n PLC_ready = PLC_ready.lower()\n\n if PLC_ready == 'ready':\n plc_check_time += 1\n\n if plc_check_time == 1:\n light_on()\n\n print(\"PLC_ready : \", PLC_ready, plc_check_time)\n\n if PLC_ready == 'ready' and PLC_flag == 0 and plc_check_time >= 4:\n # print(\"아두이노로 부터 받은 프로토콜:\", PLC_ready) # 받은 프로토콜\n PLC_sensor = True\n #print(\"PLC_sensor = True\")\n PLC_flag = 1\n plc_check_time = 0\n\n image_label.destroy()\n result_label.destroy()\n text_label.destroy()\n RV_SN.delete(0, END)\n RV_TIME.delete(0, END)\n RV_ACC.delete(0, END)\n RV_PASS.delete(0, END)\n RV_NG.delete(0, END)\n RV_TACT.delete(0, END)\n\n # print(\"PLC_flag\", PLC_flag)\n else:\n pass\n\n if PLC_ready != 'ready':\n PLC_ready = ''\n\n\ndef imageShow(N, Display):\n frame = N\n cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n cv2image = Img.fromarray(cv2image)\n imgtk = ImageTk.PhotoImage(image=cv2image)\n Display.imgtk = imgtk\n Display.configure(image=imgtk)\n\n\ndef webCamShow(N, Display, cam_no):\n _, frame = N\n\n if cam_no == 1:\n frame = RivetDetect_Big(frame)\n frame = Reformat_Image(frame, 0.5, 0.5)\n\n cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)\n cv2image = Img.fromarray(cv2image)\n imgtk = ImageTk.PhotoImage(image=cv2image)\n Display.imgtk = imgtk\n Display.configure(image=imgtk)\n\n\ndef decode(im):\n global Serial_No, pre_Serial_No\n # global RV_SN, RV_TIME, RV_ACC, RV_PASS, RV_NG, RV_TACT\n\n im = Reformat_Image(im, 2.5, 2.5)\n im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n # cv2.imshow(\"barcode_area\", im)\n decodedObjects = str(pyzbar.decode(im)) # 바코드와 QR코드를 찾아냄\n Serial_No = decodedObjects[16:29]\n # print(decodedObjects)\n # print(Serial_No)\n # Serial_No += str(accum)\n\n '''\n if Serial_No != '':\n # RV_SN.insert(20, Serial_No)\n RV_SN.delete(0, END)\n RV_TIME.delete(0, END)\n RV_ACC.delete(0, END)\n RV_PASS.delete(0, END)\n RV_NG.delete(0, END)\n RV_TACT.delete(0, END)\n\n # print(\"=======\\n\", decodedObjects)\n # print(\"Serial_No :\", Serial_No)\n '''\n\n\ndef Rotate(src, num):\n if num == 0:\n dst = src\n elif num == 1:\n dst = cv2.transpose(src)\n dst = cv2.flip(dst, 1)\n elif num == 2:\n dst = cv2.transpose(src)\n dst = cv2.flip(src, -1)\n elif num == 3:\n dst = cv2.transpose(src)\n dst = cv2.flip(dst, 0)\n elif num == -1:\n dst = cv2.transpose(src)\n dst = cv2.flip(src, -1)\n dst = Rotate(dst, 1)\n elif num == -2:\n dst = cv2.transpose(src)\n dst = cv2.flip(src, 1)\n dst = Rotate(dst, 2)\n dst = cv2.flip(src, -1)\n elif num == -3:\n dst = cv2.transpose(src)\n dst = cv2.flip(src, -1)\n dst = Rotate(dst, 3)\n\n return dst\n\n\ndef roate_left():\n global rotate\n\n rotate -= 1\n if rotate == -4:\n rotate = 0\n\n\ndef roate_right():\n global rotate\n\n rotate += 1\n if rotate == 4:\n rotate = 0\n\n\ndef read_frame():\n ## 바코드 인식 카메라 추가 시 바코드 리드 함수 추가 위치 ##\n # global Serial_No, pre_Serial_No\n # global RV_SN, RV_P1, RV_P2, RV_P3, RV_P4, RV_P5\n global PLC_sensor, folder_name, Serial_No, PLC_ready, PLC_flag, image_reformat\n # global check_PLC_sensor, image_reformat, result_rivet\n # global store_location\n # global position\n # global HOST, PORT, PLC_rx, PLC_tx_OK, PLC_tx_NG\n # global ser, sock, protocol, port_num, set\n global check_result_label, result_label, image_label, SN_label, text_label\n global check_result, barcode_area, tact_time_flag, start_time, tact_time\n global Pre_Serial_No, plc_time, pre_accum\n\n # global barcode_set, result_frame, pass_frame, ng_frame, frame_cp, rivet_empty_list, small_frame\n\n # print(\"rivet count :\", len(circle_center_list), len(whole_circle_list_big), len(whole_circle_list_small))\n\n screen_width = root.winfo_screenwidth()\n screen_height = root.winfo_screenheight()\n tk_width, tk_height = 1920, 1080\n\n webCamShow(cap1.read(), cam1_label, 1)\n\n if check_set == False:\n #print(\"=====while=====\")\n #print_data()\n\n if barcode_set == True:\n # Serial_No += str(accum)\n '''\n barcode_area = frame_cp[(bar_y1 - 5):(bar_y2 + 5), (bar_x1 - 5):(bar_x2 + 5)]\n image_reformat = Reformat_Image(barcode_area, 1, 1)\n image_reformat = Rotate(image_reformat, rotate)\n # print(image_reformat.shape)\n\n # label = 1100, 800\n # if (int(bar_x2) - int(bar_x1)) < (int(bar_y2) - int(bar_y1)):\n # image_reformat = Rotate(image_reformat, 270)\n # imageShow(image_reformat, SN_label)\n '''\n\n # 4608, 3288\n # (4608/1280) (3288/960)\n # barcode_area = frame_raw[(int(bar_y1 * math.floor(3288/960) - 5)):(int(bar_y2 * math.ceil(3288/960) + 5)),\n # (int(bar_x1 * math.floor(4608/1280)) - 5):(int(bar_x2 * math.ceil(4608/1280) + 5))]\n\n barcode_area = frame_raw[(int(bar_y1 * (3288 / 960) - 5)):(int(bar_y2 * (3288 / 960) + 5)),\n (int(bar_x1 * (4608 / 1280) - 5)):(int(bar_x2 * (4608 / 1280) + 5))]\n # print(bar_y1, bar_y2, bar_x1, bar_x2)\n # print((int(bar_y1) * int(math.floor(4608/1280)* 2) - 5), (int(bar_y2) * int(math.ceil(4608/1280) * 2) + 5), (int(bar_x1) * int(math.floor(3288/960)* 2 ) - 5), (int(bar_x2) * int(math.ceil(3288/960)* 2) + 5))\n # print(\"y1:\", (int(bar_y1) * int(math.floor(3288/480) - 5)))\n # print(\"y2:\", (int(bar_y2) * int(math.ceil(3288/480) + 5)))\n # cv2.imshow(\"barcode_area\", barcode_area)\n\n # cv2.imwrite(store_local_location + \"test.png\" , barcode_area)\n # image_reformat = Reformat_Image(barcode_area, 1, 1)\n barcode_area = Rotate(barcode_area, rotate)\n height, width, _ = barcode_area.shape\n\n decode(barcode_area)\n\n # print(\"local, server : \", check_local_path, check_server_path)\n\n '''\n if check_local_path == True:\n leave_log(1)\n if check_server_path == True:\n leave_log(2)\n '''\n\n\n if plc_check_time == 0:\n if (ser.isOpen() == False):\n ser.open()\n RS_232()\n\n\n if Serial_No != '':\n #print(\"Serial No Pass\")\n if PLC_flag == 0:\n if protocol == 1:\n RS_232()\n elif protocol == 2:\n TCP_IP()\n\n if check_result == 1:\n #print(\"check_result == 1\")\n check_result = 0\n\n if check_local_path == True:\n leave_log(1)\n if check_server_path == True:\n leave_log(2)\n PLC_sensor = False\n # tact_time_flag = 0\n\n '''\n if check_result_label == True and Serial_No != '':\n result_label.destroy()\n image_label.destroy()\n #SN_label.destroy()\n check_result_label = False\n '''\n\n '''\n if barcode_set == True:\n SN_label = Label(root)\n SN_label.place(x=screen_width * (1252 / tk_width) - (width / 2),\n y=screen_height * (861 / tk_height) - (height / 2))\n image_reformat = Reformat_Image(barcode_area, 0.5, 0.5)\n imageShow(image_reformat, SN_label)\n '''\n\n # print(\"==PLC_flag====\", PLC_flag)\n\n if PLC_flag == 1:\n plc_time = time.time()\n if check_set == False and tact_time_flag == 0:\n start_time = time.time()\n tact_time_flag = 1\n\n if PassOrNG == 1:\n # if check_local_path == True:\n cv2.imwrite(store_local_location + \"/%s/rivet/pass/%s.png\" % (folder_name, Serial_No),\n pass_frame)\n # if check_server_path == True:\n cv2.imwrite(store_server_location + \"/%s/rivet/pass/%s.png\" % (folder_name, Serial_No),\n pass_frame)\n result_label = Label(root, text=\"OK\", font=\"Helvetica 140 bold\", fg=\"RoyalBlue\")\n result_label.place(x=screen_width * (1550 / tk_width), y=screen_height * (760 / tk_height))\n\n image_label = Label(root)\n image_label.place(x=screen_width * (985 / tk_width), y=screen_height * (10 / tk_height))\n text_label = Label(root, text=\"image file saved\\n log file saved\",\n width=int(screen_width * (14 / tk_width)),\n height=int(screen_height * (2 / tk_height)), font=\"Helvetica 20 bold\",\n fg=\"RoyalBlue\")\n text_label.place(x=screen_width * (1630 / tk_width), y=screen_height * (660 / tk_height))\n\n result_image = Reformat_Image(pass_frame, 0.5, 0.5)\n imageShow(result_image, image_label)\n\n if protocol == 1:\n #ser.open()\n ser.write(bytes(PLC_tx_OK, encoding='ascii'))\n # time.sleep(5)\n PLC_flag = 0\n elif protocol == 2:\n sock.send(PLC_tx_OK.encode())\n\n light_off()\n ser.close()\n\n # PLC_flag = 0\n\n else:\n rivet_empty_list.clear()\n # if check_local_path == True:\n cv2.imwrite(store_local_location + \"/%s/rivet/fail/%s.png\" % (folder_name, Serial_No), ng_frame)\n # if check_server_path == True:\n cv2.imwrite(store_server_location + \"/%s/rivet/fail/%s.png\" % (folder_name, Serial_No), ng_frame)\n result_label = Label(root, text=\"NG\", font=\"Helvetica 140 bold\", fg=\"red\")\n result_label.place(x=screen_width * (1550 / tk_width), y=screen_height * (760 / tk_height))\n\n image_label = Label(root)\n image_label.place(x=screen_width * (985 / tk_width), y=screen_height * (10 / tk_height))\n\n text_label = Label(root, text=\"image file saved\\n log file saved\",\n width=int(screen_width * (14 / tk_width)),\n height=int(screen_height * (2 / tk_height)), font=\"Helvetica 20 bold\",\n fg=\"RoyalBlue\")\n text_label.place(x=screen_width * (1630 / tk_width), y=screen_height * (660 / tk_height))\n result_image = Reformat_Image(ng_frame, 0.5, 0.5)\n imageShow(result_image, image_label)\n\n if protocol == 1:\n #ser.open()\n ser.write(bytes(PLC_tx_NG, encoding='ascii'))\n # time.sleep(3)\n PLC_flag = 0\n elif protocol == 2:\n sock.send(PLC_tx_NG.encode())\n # PLC_flag = 0\n\n light_off()\n ser.close()\n\n\n RV_SN.insert(20, Serial_No)\n RV_TIME.insert(20, localtime)\n RV_ACC.insert(20, accum)\n RV_PASS.insert(20, count_pass_rivet)\n RV_NG.insert(20, count_fail_rivet)\n RV_TACT.insert(20, tact_time)\n\n check_result_label = True\n\n tact_time = str(round(time.time() - start_time, 2)) + ' [sec]'\n tact_time_flag = 0\n time.sleep(2)\n #ser.flush()\n # sys.stdout.flush()\n\n\n\n root.after(20, read_frame)\n\n\ndef judgefunc():\n global rivet_empty_list, check_result, ng_frame, pass_frame\n global rivet_label, check_rivet_result\n\n sum = 0\n\n screen_width = root.winfo_screenwidth()\n screen_height = root.winfo_screenheight()\n tk_width, tk_height = 1920, 1080\n\n if check_rivet_result == 1:\n check_rivet_result = 0\n rivet_label.destroy()\n\n for i in range(len(circle_center_list)):\n pixel_avg = 0\n count = 0\n\n for j in range(-2, 3):\n temp_pixel = int(frame_cp[circle_center_list[i][1] + j, circle_center_list[i][0], 0])\n pixel_avg += temp_pixel\n\n temp_pixel = int(frame_cp[circle_center_list[i][1], circle_center_list[i][0] + j, 0])\n pixel_avg += temp_pixel\n count += 2\n\n pixel_avg = pixel_avg / count\n\n if pixel_avg >= 100:\n sum += 1\n else:\n rivet_empty_list.append([circle_center_list[i][0], circle_center_list[i][1]])\n\n '''\n if len(rivet_empty_list) > 0:\n print(\"rivet_empty_list:\", rivet_empty_list)\n print(Serial_No)\n '''\n check_result = 1\n\n if sum == len(circle_center_list):\n pass_frame = frame_cp.copy()\n for i in range(len(circle_center_list)):\n cv2.circle(pass_frame, (circle_center_list[i][0], circle_center_list[i][1]), circle_center_area_list[i],\n (0, 255, 0), 2)\n\n rivet_label = Label(root, text=\"0\", fg=\"blue\", bg=\"#ebebeb\", font=\"Helvetica 60 bold\")\n rivet_label.place(x=screen_width * (1050 / tk_width),\n y=(screen_height / 3) + screen_height * (430 / tk_height) + (\n 0 * screen_height * (80 / tk_height)), relx=0.01, rely=0.01)\n check_rivet_result = 1\n return 1\n else:\n ng_frame = frame_cp.copy()\n if len(rivet_empty_list) != 0:\n for i in range(len(rivet_empty_list)):\n cv2.circle(ng_frame, (rivet_empty_list[i][0], rivet_empty_list[i][1]), 10, (0, 0, 255), 2)\n cv2.putText(ng_frame, '%d' % (i + 1), (rivet_empty_list[i][0] - 30, rivet_empty_list[i][1] + 10),\n cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)\n\n rivet_label = Label(root, text=\"{}\".format(len(rivet_empty_list)), fg=\"red\", bg=\"#ebebeb\",\n font=\"Helvetica 60 bold\")\n rivet_label.place(x=screen_width * (1040 / tk_width),\n y=(screen_height / 3) + screen_height * (430 / tk_height) + (\n 0 * screen_height * (80 / tk_height)), relx=0.01, rely=0.01)\n check_rivet_result = 1\n return -1\n\n\ndef RivetDetect_Big(frame):\n global detect_once_big, whole_circle_list_big, except_center_list_big, circle_area_list_big\n global Start_except_box_big, rect_list_big, except_list_big\n global detect_once_small, whole_circle_list_small, except_center_list_small, circle_area_list_small\n global Start_except_box_small, rect_list_small, except_list_small\n global frame_cp, result_frame, result\n global accum, count_pass_rivet, count_fail_rivet, PassOrNG, pass_frame, frame_raw\n global bar_x1, bar_y1, bar_x2, bar_y2\n # while True:\n\n # 프레임 읽기\n # 화면 크기 조절 (본인에게 맞는 해상도 조절)\n\n #frame = cv2.flip(frame, 1)\n #frame = cv2.flip(frame, 0)\n frame_raw = frame.copy()\n result = cv2.resize(frame, (1280, 960), interpolation=cv2.INTER_LINEAR)\n frame_cp = result.copy()\n img_gray = cv2.cvtColor(result, cv2.COLOR_BGR2GRAY) # gray로 변환.\n\n if Start_except_box_big == 1:\n rect_list_big.append(except_idx_big)\n except_list_big.append([ex_w_big, ex_h_big])\n Start_except_box_big = 0\n\n if Start_except_box_small == 1:\n rect_list_small.append(except_idx_small)\n except_list_small.append([ex_w_small, ex_h_small])\n Start_except_box_small = 0\n\n # 관심영역(ROI, Range of Interest) 지정.\n for i in range(len(Big_ROI_list)):\n result = cv2.rectangle(result, Big_ROI_list[i][0], Big_ROI_list[i][1], (150, 50, 150), 5)\n # cv2.putText(result, 'ROI%d' %(i + 1), (ROI_list[i][0][0], ROI_list[i][0][1] - 3), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)\n\n # 관심영역(ROI, Range of Interest) 지정.\n for i in range(len(Small_ROI_list)):\n result = cv2.rectangle(result, Small_ROI_list[i][0], Small_ROI_list[i][1], (50, 150, 50), 5)\n # cv2.putText(result, 'ROI%d' %(i + 1), (ROI_list[i][0][0], ROI_list[i][0][1] - 3), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)\n\n result = cv2.rectangle(result, (bar_x1, bar_y1), (bar_x2, bar_y2), (255, 216, 0), 5)\n # bar_x1, bar_y1, bar_x2, bar_y2\n\n # 예외처리(Exception Box) 지정.\n for i in range(len(rect_list_big)):\n result = cv2.rectangle(result, (except_box_list_big[i][0] - int((except_list_big[i][0]) / 2),\n except_box_list_big[i][1] - int((except_list_big[i][1]) / 2)), \\\n (except_box_list_big[i][0] + int((except_list_big[i][0]) / 2),\n except_box_list_big[i][1] + int((except_list_big[i][1]) / 2)), (0, 255, 255), 1)\n\n result = cv2.circle(result, (except_box_list_big[i][0], except_box_list_big[i][1]), 2, (50, 205, 50), -1)\n\n result = cv2.line(result, (except_box_list_big[i][0] - int((except_list_big[i][0]) / 2),\n except_box_list_big[i][1] - int((except_list_big[i][1]) / 2)), \\\n (except_box_list_big[i][0] + int((except_list_big[i][0]) / 2),\n except_box_list_big[i][1] + int((except_list_big[i][1]) / 2)), (0, 255, 255), 1)\n\n result = cv2.line(result, (except_box_list_big[i][0] + int((except_list_big[i][0]) / 2),\n except_box_list_big[i][1] - int((except_list_big[i][1]) / 2)), \\\n (except_box_list_big[i][0] - int((except_list_big[i][0]) / 2),\n except_box_list_big[i][1] + int((except_list_big[i][1]) / 2)), (0, 255, 255), 1)\n\n # 예외처리(Exception Box) 지정.\n for i in range(len(rect_list_small)):\n result = cv2.rectangle(result, (except_box_list_small[i][0] - int((except_list_small[i][0]) / 2),\n except_box_list_small[i][1] - int((except_list_small[i][1]) / 2)), \\\n (except_box_list_small[i][0] + int((except_list_small[i][0]) / 2),\n except_box_list_small[i][1] + int((except_list_small[i][1]) / 2)), (0, 255, 255), 1)\n\n result = cv2.circle(result, (except_box_list_small[i][0], except_box_list_small[i][1]), 2, (50, 205, 50), -1)\n\n result = cv2.line(result, (except_box_list_small[i][0] - int((except_list_small[i][0]) / 2),\n except_box_list_small[i][1] - int((except_list_small[i][1]) / 2)), \\\n (except_box_list_small[i][0] + int((except_list_small[i][0]) / 2),\n except_box_list_small[i][1] + int((except_list_small[i][1]) / 2)), (0, 255, 255), 1)\n\n result = cv2.line(result, (except_box_list_small[i][0] + int((except_list_small[i][0]) / 2),\n except_box_list_small[i][1] - int((except_list_small[i][1]) / 2)), \\\n (except_box_list_small[i][0] - int((except_list_small[i][0]) / 2),\n except_box_list_small[i][1] + int((except_list_small[i][1]) / 2)), (0, 255, 255), 1)\n\n if rivet_detect == True or load_setting_flag == True:\n\n # param1 = 250, param2 = 20\n # 원본과 비율 / 찾은 원들간의 최소 중심거리 / param1, param2를 조절해 원을 찾음 250 20 5 30\n # big_circles = cv2.HoughCircles(img_gray, cv2.HOUGH_GRADIENT, 1.208, 10, param1=34, param2=24, minRadius=10, maxRadius=13)\n big_circles = cv2.HoughCircles(img_gray, cv2.HOUGH_GRADIENT, 1, 13, param1=110, param2=9, minRadius=4, maxRadius=7)\n\n # 관심영역내 원만을 탐지함.\n if big_circles is not None:\n big_circles = np.uint16(np.around(big_circles))\n\n if detect_once_big == False:\n detect_once_big = True\n pass_frame = frame_cp.copy()\n\n for i in big_circles[0, :]:\n for j in range(len(Big_ROI_list)):\n if (i[0] > Big_ROI_list[j][0][0] and i[0] < Big_ROI_list[j][1][0]) and (\n i[1] > Big_ROI_list[j][0][1] and i[1] < Big_ROI_list[j][1][1]): # ROI 관심영역 내에서 찾아냄.\n whole_circle_list_big.append([i[0], i[1]]) # ROI 내 모든 중심점.\n circle_area_list_big.append(i[2])\n\n for k in range(len(except_box_big)):\n if (whole_circle_list_big[k][0] > except_box_big[k][0] and whole_circle_list_big[k][0] < (\n except_box_big[k][0] + ex_w_big)) and (\n whole_circle_list_big[k][1] > except_box_big[k][1] and whole_circle_list_big[k][1] < (\n except_box_big[k][1] + ex_h_big)):\n except_center_list_big.append(\n [whole_circle_list_big[k][0], whole_circle_list_big[k][1]]) # 예외처리 중심점을 리스트에 추가\n whole_circle_list_big.remove(except_center_list_big[0]) # 예외처리 리스트에 있는 중심점들을 전체 중심점리스트에서 제거\n except_center_list_big.pop() # 제외 처리를 하고나서 값을 빼서 다음 값을 프로세스 진행하도록 함.\n\n if check_set == True:\n for idx in range(len(whole_circle_list_big)):\n cv2.circle(result, (whole_circle_list_big[idx][0], whole_circle_list_big[idx][1]),\n circle_area_list_big[idx], (0, 255, 0), 2) # 원 외곽 컨투어 표시.\n cv2.circle(result, (whole_circle_list_big[idx][0], whole_circle_list_big[idx][1]), 3, (255, 0, 40),\n -1) # 원의 중심점을 표시\n\n\n elif check_set == False:\n circle_area_list_big.clear()\n except_center_list_big.clear()\n whole_circle_list_big.clear()\n for i in big_circles[0, :]:\n for j in range(len(Big_ROI_list)):\n if (i[0] > Big_ROI_list[j][0][0] and i[0] < Big_ROI_list[j][1][0]) and (\n i[1] > Big_ROI_list[j][0][1] and i[1] < Big_ROI_list[j][1][1]): # ROI 관심영역 내에서 찾아냄.\n whole_circle_list_big.append([i[0], i[1]]) # ROI 내 모든 중심점.\n circle_area_list_big.append(i[2])\n\n try:\n for i in range(len(save_delete_item_list_big)):\n for j in range(len(whole_circle_list_big)):\n if ((0 <= abs(\n int(whole_circle_list_big[j][0]) - int(save_delete_item_list_big[i][0]))) and (abs(\n int(whole_circle_list_big[j][0]) - int(save_delete_item_list_big[i][0])) <= 5)) and \\\n ((0 <= abs(\n int(whole_circle_list_big[j][1]) - int(save_delete_item_list_big[i][1]))) and (\n abs(int(whole_circle_list_big[j][1]) - int(\n save_delete_item_list_big[i][1])) <= 5)):\n whole_circle_list_big[j][0] = save_delete_item_list_big[i][0]\n whole_circle_list_big[j][1] = save_delete_item_list_big[i][1]\n\n whole_circle_list_big.remove([save_delete_item_list_big[i][0], save_delete_item_list_big[i][1]])\n except ValueError:\n pass\n\n for i in range(len(whole_circle_list_big)):\n for j in range(len(circle_center_list)):\n if ((0 <= abs(int(whole_circle_list_big[i][0]) - int(circle_center_list[j][0]))) and (\n abs(int(whole_circle_list_big[i][0]) - int(circle_center_list[j][0])) <= 5)) and \\\n ((0 <= abs(int(whole_circle_list_big[i][1]) - int(circle_center_list[j][1]))) and (\n abs(int(whole_circle_list_big[i][1]) - int(circle_center_list[j][1])) <= 5)):\n whole_circle_list_big[i][0] = circle_center_list[j][0]\n whole_circle_list_big[i][1] = circle_center_list[j][1]\n try:\n for k in range(len(except_box_big)):\n if ((whole_circle_list_big[k][0] > except_box_big[k][0]) and (\n whole_circle_list_big[k][0] < (except_box_big[k][0] + ex_w_big))) and (\n (whole_circle_list_big[k][1] > except_box_big[k][1]) and (\n whole_circle_list_big[k][1] < (except_box_big[k][1] + ex_h_big))):\n except_center_list_big.append(\n [whole_circle_list_big[k][0], whole_circle_list_big[k][1]]) # 예외처리 중심점을 리스트에 추가\n whole_circle_list_big.remove(except_center_list_big[0]) # 예외처리 리스트에 있는 중심점들을 전체 중심점리스트에서 제거\n # print(\"예외처리 중심점:\", except_center_list)\n except_center_list_big.pop() # 제외 처리를 하고나서 값을 빼서 다음 값을 프로세스 진행하도록 함.\n except IndexError:\n pass\n\n for idx in range(len(whole_circle_list_big)):\n cv2.circle(result, (whole_circle_list_big[idx][0], whole_circle_list_big[idx][1]),\n circle_area_list_big[idx], (0, 0, 255), 2) # 원 외곽 컨투어 표시.\n cv2.circle(result, (whole_circle_list_big[idx][0], whole_circle_list_big[idx][1]), 3, (255, 0, 40),\n -1) # 원의 중심점을 표시\n\n if rivet_detect == True or load_setting_flag == True:\n\n # param1 = 250, param2 = 20\n # 원본과 비율 / 찾은 원들간의 최소 중심거리 / param1, param2를 조절해 원을 찾음 250 20 5 30\n # small_circles = cv2.HoughCircles(img_gray, cv2.HOUGH_GRADIENT, 0.5, 10, param1=70, param2=10, minRadius=8, maxRadius=10)\n\n small_circles = cv2.HoughCircles(img_gray, cv2.HOUGH_GRADIENT, 1, 13, param1=110, param2=8, minRadius=2,\n maxRadius=4)\n\n # 관심영역내 원만을 탐지함.\n if small_circles is not None:\n small_circles = np.uint16(np.around(small_circles))\n\n if detect_once_small == False:\n detect_once_small = True\n pass_frame = frame_cp.copy()\n\n for i in small_circles[0, :]:\n for j in range(len(Small_ROI_list)):\n if (i[0] > Small_ROI_list[j][0][0] and i[0] < Small_ROI_list[j][1][0]) and (\n i[1] > Small_ROI_list[j][0][1] and i[1] < Small_ROI_list[j][1][1]): # ROI 관심영역 내에서 찾아냄.\n whole_circle_list_small.append([i[0], i[1]]) # ROI 내 모든 중심점.\n circle_area_list_small.append(i[2])\n\n for k in range(len(except_box_small)):\n if (whole_circle_list_small[k][0] > except_box_small[k][0] and whole_circle_list_small[k][0] < (\n except_box_small[k][0] + ex_w_small)) and (\n whole_circle_list_small[k][1] > except_box_small[k][1] and whole_circle_list_small[k][1] < (\n except_box_small[k][1] + ex_h_small)):\n except_center_list_small.append(\n [whole_circle_list_small[k][0], whole_circle_list_small[k][1]]) # 예외처리 중심점을 리스트에 추가\n whole_circle_list_small.remove(except_center_list_small[0]) # 예외처리 리스트에 있는 중심점들을 전체 중심점리스트에서 제거\n except_center_list_small.pop() # 제외 처리를 하고나서 값을 빼서 다음 값을 프로세스 진행하도록 함.\n\n if check_set == True:\n for idx in range(len(whole_circle_list_small)):\n cv2.circle(result, (whole_circle_list_small[idx][0], whole_circle_list_small[idx][1]),\n circle_area_list_small[idx], (0, 255, 0), 2) # 원 외곽 컨투어 표시.\n cv2.circle(result, (whole_circle_list_small[idx][0], whole_circle_list_small[idx][1]), 3,\n (255, 0, 40), -1) # 원의 중심점을 표시\n\n\n elif check_set == False:\n circle_area_list_small.clear()\n except_center_list_small.clear()\n whole_circle_list_small.clear()\n for i in small_circles[0, :]:\n for j in range(len(Small_ROI_list)):\n if (i[0] > Small_ROI_list[j][0][0] and i[0] < Small_ROI_list[j][1][0]) and (\n i[1] > Small_ROI_list[j][0][1] and i[1] < Small_ROI_list[j][1][1]): # ROI 관심영역 내에서 찾아냄.\n whole_circle_list_small.append([i[0], i[1]]) # ROI 내 모든 중심점.\n circle_area_list_small.append(i[2])\n\n try:\n for i in range(len(save_delete_item_list_small)):\n for j in range(len(whole_circle_list_small)):\n if ((0 <= abs(\n int(whole_circle_list_small[j][0]) - int(save_delete_item_list_small[i][0]))) and (\n abs(int(whole_circle_list_small[j][0]) - int(\n save_delete_item_list_small[i][0])) <= 5)) and \\\n ((0 <= abs(int(whole_circle_list_small[j][1]) - int(\n save_delete_item_list_small[i][1]))) and (abs(\n int(whole_circle_list_small[j][1]) - int(\n save_delete_item_list_small[i][1])) <= 5)):\n whole_circle_list_small[j][0] = save_delete_item_list_small[i][0]\n whole_circle_list_small[j][1] = save_delete_item_list_small[i][1]\n whole_circle_list_small.remove(\n [save_delete_item_list_small[i][0], save_delete_item_list_small[i][1]])\n except ValueError:\n pass\n\n for i in range(len(whole_circle_list_small)):\n for j in range(len(circle_center_list)):\n if ((0 <= abs(int(whole_circle_list_small[i][0]) - int(circle_center_list[j][0]))) and (\n abs(int(whole_circle_list_small[i][0]) - int(circle_center_list[j][0])) <= 5)) and \\\n ((0 <= abs(int(whole_circle_list_small[i][1]) - int(circle_center_list[j][1]))) and (\n abs(int(whole_circle_list_small[i][1]) - int(circle_center_list[j][1])) <= 5)):\n whole_circle_list_small[i][0] = circle_center_list[j][0]\n whole_circle_list_small[i][1] = circle_center_list[j][1]\n try:\n for k in range(len(except_box_small)):\n if ((whole_circle_list_small[k][0] > except_box_small[k][0]) and (\n whole_circle_list_small[k][0] < (except_box_small[k][0] + ex_w_small))) and (\n (whole_circle_list_small[k][1] > except_box_small[k][1]) and (\n whole_circle_list_small[k][1] < (except_box_small[k][1] + ex_h_small))):\n except_center_list_small.append(\n [whole_circle_list_small[k][0], whole_circle_list_small[k][1]]) # 예외처리 중심점을 리스트에 추가\n whole_circle_list_small.remove(\n except_center_list_small[0]) # 예외처리 리스트에 있는 중심점들을 전체 중심점리스트에서 제거\n # print(\"예외처리 중심점:\", except_center_list)\n except_center_list_small.pop() # 제외 처리를 하고나서 값을 빼서 다음 값을 프로세스 진행하도록 함.\n except IndexError:\n pass\n\n for idx in range(len(whole_circle_list_small)):\n cv2.circle(result, (whole_circle_list_small[idx][0], whole_circle_list_small[idx][1]),\n circle_area_list_small[idx], (0, 0, 255), 2) # 원 외곽 컨투어 표시.\n cv2.circle(result, (whole_circle_list_small[idx][0], whole_circle_list_small[idx][1]), 3,\n (255, 0, 40), -1) # 원의 중심점을 표시\n # 원의 갯수\n\n if PLC_flag == 1:\n if PLC_sensor == True and Serial_No != '':\n # time.sleep(1)\n PassOrNG = judgefunc()\n\n if (PassOrNG == 1):\n count_pass_rivet += 1\n result_frame = result.copy()\n elif (PassOrNG == -1):\n count_fail_rivet += 1\n else:\n pass\n\n accum = count_pass_rivet + count_fail_rivet\n\n if check_set == False:\n return frame_cp\n else:\n return result\n\n\ndef affiche(com_port):\n global choices, port_num\n\n port_num = com_port\n\n # print(port_num)\n\n\ndef mouse_position(event):\n global count_mouse\n # print(\"===== 마우스 포지션 출력 =====\")\n # print(\"click - \", event.x *2 , event.y * 2)\n\n try:\n if Big_ROI_setting == False:\n if count_mouse == 0:\n BIg_LU_X.insert(20, event.x)\n Big_LU_Y.insert(20, event.y)\n count_mouse += 1\n elif count_mouse == 1:\n Big_RD_X.insert(20, event.x)\n Big_RD_Y.insert(20, event.y)\n count_mouse = 0\n elif Big_ROI_setting == True and Small_ROI_setting == False:\n if count_mouse == 0:\n Small_LU_X.insert(20, event.x)\n Small_LU_Y.insert(20, event.y)\n count_mouse += 1\n elif count_mouse == 1:\n Small_RD_X.insert(20, event.x)\n Small_RD_Y.insert(20, event.y)\n count_mouse = 0\n elif Small_ROI_setting == True and except_big_setting == False:\n Big_Except_X.insert(20, event.x)\n Big_Except_Y.insert(20, event.y)\n elif except_big_setting == True and except_small_setting == False:\n Small_Except_X.insert(20, event.x)\n Small_Except_Y.insert(20, event.y)\n # Except_W.insert(20, 5)\n # Except_H.insert(20, 5)\n\n if except_big_setting == True and except_small_setting == True:\n if count_mouse == 0:\n B_LU_X.insert(20, event.x)\n B_LU_Y.insert(20, event.y)\n count_mouse += 1\n elif count_mouse == 1:\n B_RD_X.insert(20, event.x)\n B_RD_Y.insert(20, event.y)\n count_mouse = 0\n except ValueError:\n pass\n\n\ndef open_folder_pass():\n ### 폴더 경로 변경\n if check_make_folder == 1:\n #path = foldername_pass\n path = open_foldername_pass\n path = os.path.realpath(path)\n os.startfile(path)\n\n\ndef open_folder_ng():\n ### 폴더 경로 변경\n if check_make_folder == 1:\n #path = foldername_fail\n path = open_foldername_fail\n path = os.path.realpath(path)\n os.startfile(path)\n\n\ndef open_folder_log():\n ### 폴더 경로 변경\n if check_make_folder == 1:\n #path = foldername_log\n path = open_foldername_log\n path = os.path.realpath(path)\n os.startfile(path)\n\n\ndef select_RS_232():\n global protocol, check_protocol\n # global set, RSC_B, PLC_IP_label, PLC_IP, PLC_PORT\n global list_box, SP_label, RS_B, TI_B, PLC_PORT_label\n\n RS_B.destroy()\n TI_B.destroy()\n\n if protocol == 2:\n PLC_IP_label.destroy()\n PLC_PORT_label.destroy()\n PLC_IP.destroy()\n PLC_PORT.destroy()\n\n protocol = 1\n check_protocol = True\n\n screen_width = set.winfo_screenwidth()\n screen_height = set.winfo_screenheight()\n tk_width, tk_height = 1920, 1080\n\n RS_B = Button(set, text=\"RS-232\", font=\"Helvetica 10\", relief=\"raised\", overrelief=\"solid\", bg=\"#dfffbf\", \\\n width=int(screen_width * (14 / tk_width)), height=int(screen_height * (2 / tk_height)), bd=3, padx=2,\n pady=2, command=select_RS_232)\n RS_B.place(x=screen_width * (135 / tk_width), y=screen_height * (710 / tk_height))\n\n TI_B = Button(set, text=\"TCP/IP\", font=\"Helvetica 10\", relief=\"raised\", overrelief=\"solid\", bg=\"#ebebeb\", \\\n width=int(screen_width * (14 / tk_width)), height=int(screen_height * (2 / tk_height)), bd=3, padx=2,\n pady=2, command=select_TCP_IP)\n TI_B.place(x=screen_width * (135 / tk_width), y=screen_height * (760 / tk_height))\n\n SP_label = Label(set, text=\"Serial Port\", height=int(screen_height * (2 / tk_height)),\n width=int(screen_width * (12 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 13 bold\")\n SP_label.place(x=screen_width * (265 / tk_width), y=screen_height * (705 / tk_height), relx=0.01, rely=0.01)\n\n choices = ['COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', \\\n 'COM9', 'COM10', 'COM11', 'COM12', 'COM13', 'COM14', 'COM15', 'COM16']\n\n variable = StringVar(root)\n variable.set(' COM_Port ')\n list_box = OptionMenu(set, variable, *choices, command=affiche)\n list_box.place(x=screen_width * (265 / tk_width), y=screen_height * (765 / tk_height), relx=0.01, rely=0.01)\n\n # print(\"통신방식 : RS-232 \")\n\n\ndef select_TCP_IP():\n global protocol, check_protocol\n # global set, list_box, SP_label, RSC_B\n global RS_B, TI_B, PLC_IP_label, PLC_IP, PLC_PORT_label, PLC_PORT\n\n TI_B.destroy()\n\n if protocol == 1:\n list_box.destroy()\n SP_label.destroy()\n\n protocol = 2\n check_protocol = True\n\n screen_width = set.winfo_screenwidth()\n screen_height = set.winfo_screenheight()\n tk_width, tk_height = 1920, 1080\n\n PLC_IP_label = Label(set, text=\"PLC IP Address\", height=int(screen_height * (2 / tk_height)),\n width=int(screen_width * (15 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 13 bold\")\n PLC_IP_label.place(x=screen_width * (265 / tk_width), y=screen_height * (705 / tk_height), relx=0.01, rely=0.01)\n\n PLC_PORT_label = Label(set, text=\"PLC PORT Number\", height=int(screen_height * (2 / tk_height)),\n width=int(screen_width * (16 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 13 bold\")\n PLC_PORT_label.place(x=screen_width * (610 / tk_width), y=screen_height * (705 / tk_height), relx=0.01, rely=0.01)\n\n PLC_IP = Entry(set, width=int(screen_width * (15 / tk_width)), relief=\"groove\", font=\"Helvetica 30 bold\")\n PLC_IP.place(x=screen_width * (265 / tk_width), y=screen_height * (750 / tk_height) + 0, relx=0.01, rely=0.01)\n\n PLC_PORT = Entry(set, width=int(screen_width * (8 / tk_width)), relief=\"groove\", font=\"Helvetica 30 bold\")\n PLC_PORT.place(x=screen_width * (610 / tk_width), y=screen_height * (750 / tk_height) + 0, relx=0.01, rely=0.01)\n\n RS_B = Button(set, text=\"RS-232\", font=\"Helvetica 10\", relief=\"raised\", overrelief=\"solid\", bg=\"#ebebeb\", \\\n width=int(screen_width * (14 / tk_width)), height=int(screen_height * (2 / tk_height)), bd=3, padx=2,\n pady=2, command=select_RS_232)\n RS_B.place(x=screen_width * (135 / tk_width), y=screen_height * (710 / tk_height))\n\n TI_B = Button(set, text=\"TCP/IP\", font=\"Helvetica 10\", relief=\"raised\", overrelief=\"solid\", bg=\"#dfffbf\", \\\n width=int(screen_width * (14 / tk_width)), height=int(screen_height * (2 / tk_height)), bd=3, padx=2,\n pady=2, command=select_TCP_IP)\n TI_B.place(x=screen_width * (135 / tk_width), y=screen_height * (760 / tk_height))\n\n # print(\"통신방식 : TCP/IP\")\n\n\ndef check_setting():\n global check_set, store_local_location, pathname, store_server_location, store_local_location\n global ser, HOST, PORT\n global circle_center_list, circle_center_area_list\n global check_local_path, check_server_path, load_setting_flag\n # global port_num, protocol, check_protocol, set, whole_circle_list_big, circle_area_list_big, whole_circle_list_small, circle_area_list_small\n\n # print(\"pro, port : \", protocol, port_num)\n\n screen_width = root.winfo_screenwidth()\n screen_height = root.winfo_screenheight()\n tk_width, tk_height = 1920, 1080\n\n #### circle_center_list 에 big + small 적용\n #if load_setting_flag == False:\n circle_center_list = copy.deepcopy(whole_circle_list_big) + copy.deepcopy(whole_circle_list_small)\n circle_center_area_list = copy.deepcopy(circle_area_list_big) + copy.deepcopy(circle_area_list_small)\n # print(len(circle_center_list), len(circle_center_area_list))\n # print(circle_center_list)\n\n\n #print(\"=====check_set=====\")\n #print_data()\n #print(\"*********************\")\n\n\n whole_circle_list_big.clear()\n whole_circle_list_small.clear()\n circle_area_list_big.clear()\n circle_area_list_small.clear()\n\n Label(root, text=\"{}\".format(len(circle_center_list)), fg=\"black\", bg=\"#ebebeb\",\n font=\"Helvetica 60 bold\").place(x=screen_width * (1200 / tk_width),\n y=(screen_height / 3) + screen_height * (430 / tk_height) + (\n 0 * screen_height * (80 / tk_height)), relx=0.01, rely=0.01)\n Label(root, text=\"/\", fg=\"black\", bg=\"#ebebeb\",\n font=\"Helvetica 60 bold\").place(x=screen_width * (1150 / tk_width),\n y=(screen_height / 3) + screen_height * (430 / tk_height) + (\n 0 * screen_height * (80 / tk_height)), relx=0.01, rely=0.01)\n\n if protocol == 1 and port_num != '':\n ser = serial.Serial(\n port=port_num,\n baudrate=9600,\n parity=serial.PARITY_NONE, \\\n stopbits=serial.STOPBITS_ONE, \\\n bytesize=serial.EIGHTBITS, \\\n timeout=0\n )\n check_communication = True\n elif protocol == 2:\n HOST = PLC_IP.get()\n PORT = PLC_PORT.get()\n check_communication = True\n\n if check_protocol == True and check_communication == True and barcode_set == True:\n #check_set = False\n store_local_location_input = datapath_local.get()\n store_server_location_input = datapath_server.get()\n\n # print(HOST, PORT)\n set.destroy()\n\n pathname_local = ''\n pathname_server = ''\n # print(store_local_location_input)\n # print(store_server_location_input)\n if store_local_location_input != '':\n check_local_path = True\n parsing_local = store_local_location_input.split('/')\n\n # print(\"parsing_local\", parsing_local)\n\n for i in range(len(parsing_local)):\n if parsing_local[i] != '':\n pathname_local += parsing_local[i] + '/'\n # print(pathname)\n elif parsing_local[i] == '':\n pathname_local += '\\\\'\n elif parsing_local[i] == '/':\n break\n # print(pathname_local)\n\n '''\n if i != 0:\n make_folder(pathname)\n '''\n store_local_location = pathname_local\n # print(\"locaal location : \", store_local_location)\n\n if store_server_location_input != '':\n check_server_path = True\n parsing_server = store_server_location_input.split('/')\n\n # print(\"parsing_server\", parsing_server)\n\n for i in range(len(parsing_server)):\n if parsing_server[i] != '':\n pathname_server += parsing_server[i] + '/'\n # print(pathname)\n elif parsing_server[i] == '':\n pathname_server += '\\\\'\n elif parsing_server[i] == '/':\n break\n\n '''\n if i != 0 and parsing_server[i] != '':\n #print(pathname_server)\n make_folder(pathname)\n '''\n store_server_location = pathname_server\n # print(\"server location : \", store_server_location)\n\n if check_server_path == True and check_local_path == True:\n check_set = False\n\ndef save_setting():\n #print_data()\n\n with open('save_setting.p', 'wb') as file: # hello.txt 파일을 바이너리 쓰기 모드(wb)로 열기\n pickle.dump(Big_ROI_list, file)\n pickle.dump(Small_ROI_list, file)\n pickle.dump(except_center_list_big, file)\n pickle.dump(except_center_list_small, file)\n pickle.dump(whole_circle_list_big, file)\n pickle.dump(whole_circle_list_small, file)\n pickle.dump(except_box_big, file)\n pickle.dump(except_box_small, file)\n pickle.dump(circle_area_list_big, file)\n pickle.dump(circle_area_list_small, file)\n pickle.dump(save_delete_item_list_big, file)\n pickle.dump(save_delete_item_list_small, file)\n pickle.dump(circle_center_list, file)\n pickle.dump(ex_w_big, file)\n pickle.dump(ex_w_small, file)\n pickle.dump(ex_h_big, file)\n pickle.dump(ex_h_small, file)\n pickle.dump(bar_x1, file)\n pickle.dump(bar_y1, file)\n pickle.dump(bar_x2, file)\n pickle.dump(bar_y2, file)\n pickle.dump(protocol, file)\n pickle.dump(port_num, file)\n pickle.dump(store_local_location, file)\n pickle.dump(store_server_location, file)\n\n\ndef load_setting():\n global Big_ROI_list, Small_ROI_list, except_center_list_big, except_center_list_small, whole_circle_list_big, whole_circle_list_small\n global except_box_big, except_box_small, circle_area_list_big, circle_area_list_small, save_delete_item_list_big, save_delete_item_list_small\n global circle_center_list, ex_w_big, ex_w_small, ex_h_big, ex_h_small, bar_x1, bar_y1, bar_x2, bar_y2, protocol, port_num, store_local_location, store_server_location\n global check_protocol, barcode_set, rivet_detect, check_local_path, check_server_path, load_setting_flag, detect_once_big, detect_once_small\n\n with open('save_setting.p', 'rb') as file: # hello.txt 파일을 바이너리 쓰기 모드(wb)로 열기\n Big_ROI_list = pickle.load(file)\n Small_ROI_list = pickle.load(file)\n except_center_list_big = pickle.load(file)\n except_center_list_small = pickle.load(file)\n whole_circle_list_big = pickle.load(file)\n whole_circle_list_small = pickle.load(file)\n except_box_big = pickle.load(file)\n except_box_small = pickle.load(file)\n circle_area_list_big = pickle.load(file)\n circle_area_list_small = pickle.load(file)\n save_delete_item_list_big = pickle.load(file)\n save_delete_item_list_small = pickle.load(file)\n circle_center_list = pickle.load(file)\n ex_w_big = pickle.load(file)\n ex_w_small = pickle.load(file)\n ex_h_big = pickle.load(file)\n ex_h_small = pickle.load(file)\n bar_x1 = pickle.load(file)\n bar_y1 = pickle.load(file)\n bar_x2 = pickle.load(file)\n bar_y2 = pickle.load(file)\n protocol = pickle.load(file)\n port_num = pickle.load(file)\n store_local_location = pickle.load(file)\n store_server_location = pickle.load(file)\n\n #print_data()\n check_protocol = True\n barcode_set = True\n #rivet_detect = True\n check_local_path = True\n check_server_path = True\n load_setting_flag = True\n detect_once_big = True\n detect_once_small = True\n\n\n '''\n print(\"load\")\n for i in range(len(save_setting_list)):\n print(save_setting_list[i])\n '''\n\ndef print_data():\n\n print(\"Big_ROI_list\", Big_ROI_list)\n print(\"Small_ROI_list\", Small_ROI_list)\n print(\"except_center_list_big\", except_center_list_big)\n print(\"except_center_list_small\", except_center_list_small)\n print(\"whole_circle_list_big\", whole_circle_list_big)\n print(\"whole_circle_list_small\", whole_circle_list_small)\n print(\"except_box_big\", except_box_big)\n print(\"except_box_small\", except_box_small)\n print(\"circle_area_list_big\", circle_area_list_big)\n print(\"circle_area_list_small\", circle_area_list_small)\n print(\"save_delete_item_list_big\", save_delete_item_list_big)\n print(\"save_delete_item_list_small\", save_delete_item_list_small)\n\n print(\"circle_center_list\", circle_center_list)\n\n print(\"ex_w_big\", ex_w_big)\n print(\"ex_w_small\", ex_w_small)\n print(\"ex_h_big\", ex_h_big)\n print(\"ex_h_small\", ex_h_small)\n\n print(\"bar_x1\", bar_x1)\n print(\"bar_y1\", bar_y1)\n print(\"bar_x2\", bar_x2)\n print(\"bar_y2\", bar_y2)\n\n print(\"protocol\", protocol)\n print(\"port_num\", port_num)\n\n print(\"store_local_location\", store_local_location)\n print(\"store_server_location\", store_server_location)\n\n\ndef start_rivet_detect():\n global rivet_detect\n\n rivet_detect = True\n\n\ndef restart_rivet_detect():\n global detect_once_big, detect_once_small, whole_circle_list_big, whole_circle_list_small\n\n whole_circle_list_big = []\n whole_circle_list_small = []\n detect_once_big = False\n detect_once_small = False\n # print(\"리벳 위치 재감지\")\n\n\ndef add_Big_ROI():\n global Big_ROI_list, count_mouse\n\n try:\n ROI_X1 = int(BIg_LU_X.get()) * 2\n ROI_Y1 = int(Big_LU_Y.get()) * 2\n ROI_X2 = int(Big_RD_X.get()) * 2\n ROI_Y2 = int(Big_RD_Y.get()) * 2\n\n Big_ROI_list.append([(ROI_X1, ROI_Y1), (ROI_X2, ROI_Y2)])\n\n count_mouse = 0\n\n BIg_LU_X.delete(0, END)\n Big_LU_Y.delete(0, END)\n Big_RD_X.delete(0, END)\n Big_RD_Y.delete(0, END)\n except ValueError:\n pass\n\n\ndef add_small_ROI():\n global Small_ROI_list, count_mouse\n\n try:\n ROI_X1 = int(Small_LU_X.get()) * 2\n ROI_Y1 = int(Small_LU_Y.get()) * 2\n ROI_X2 = int(Small_RD_X.get()) * 2\n ROI_Y2 = int(Small_RD_Y.get()) * 2\n\n Small_ROI_list.append([(ROI_X1, ROI_Y1), (ROI_X2, ROI_Y2)])\n\n count_mouse = 0\n\n Small_LU_X.delete(0, END)\n Small_LU_Y.delete(0, END)\n Small_RD_X.delete(0, END)\n Small_RD_Y.delete(0, END)\n except ValueError:\n pass\n\n\ndef set_comp_Big_ROI():\n global Big_ROI_setting\n\n Big_ROI_setting = True\n\n BIg_LU_X.delete(0, END)\n Big_LU_Y.delete(0, END)\n Big_RD_X.delete(0, END)\n Big_RD_Y.delete(0, END)\n\n\ndef set_comp_Small_ROI():\n global Small_ROI_setting\n\n Small_ROI_setting = True\n\n Small_LU_X.delete(0, END)\n Small_LU_Y.delete(0, END)\n Small_RD_X.delete(0, END)\n Small_RD_Y.delete(0, END)\n\n\ndef set_comp_big_except():\n global except_big_setting\n\n except_big_setting = True\n\n Big_Except_X.delete(0, END)\n Big_Except_Y.delete(0, END)\n # Except_W.delete(0, END)\n # Except_H.delete(0, END)\n\n\ndef set_comp_small_except():\n global except_small_setting\n\n except_small_setting = True\n\n Small_Except_X.delete(0, END)\n Small_Except_Y.delete(0, END)\n # Except_W.delete(0, END)\n # Except_H.delete(0, END)\n\n\ndef set_Bar_area():\n global barcode_set\n global bar_x1, bar_y1, bar_x2, bar_y2\n\n try:\n barcode_set = True\n\n bar_x1 = int(B_LU_X.get()) * 2\n bar_y1 = int(B_LU_Y.get()) * 2\n bar_x2 = int(B_RD_X.get()) * 2\n bar_y2 = int(B_RD_Y.get()) * 2\n\n B_LU_X.delete(0, END)\n B_RD_X.delete(0, END)\n B_LU_Y.delete(0, END)\n B_RD_Y.delete(0, END)\n except ValueError:\n pass\n\n\ndef reset_Bar_area():\n global barcode_set\n\n barcode_set = False\n\n\ndef add_except_big_area():\n global except_box_big, ex_w_big, ex_h_big\n global whole_circle_list_big, except_box_wh_big\n global save_rivet_center_flag_big, except_box_list_big, temp_whole_circle_big\n global except_idx_big, Start_except_box_big, save_delete_item_list_big, circle_area_list_big\n\n try:\n if Big_ROI_setting == True:\n EA_X_big = int(Big_Except_X.get()) * 2\n EA_Y_big = int(Big_Except_Y.get()) * 2\n ex_w_big = 7\n ex_h_big = 7\n # ex_w = int(Except_W.get()) * 2\n # ex_h = int(Except_H.get()) * 2\n\n Big_Except_X.delete(0, END)\n Big_Except_Y.delete(0, END)\n # Except_W.delete(0, END)\n # Except_H.delete(0, END)\n\n except_box_big.append([EA_X_big, EA_Y_big])\n except_box_wh_big.append([ex_w_big, ex_h_big])\n\n Start_except_box_big = 1\n\n if save_rivet_center_flag_big == 0:\n save_rivet_center_flag_big = 1\n temp_whole_circle_big = whole_circle_list_big\n\n idx = 0\n delete_item_list_big = []\n for i in range(len(except_box_big)):\n for j in range(len(whole_circle_list_big)):\n if ((except_box_big[i][0] - ex_w_big) <= whole_circle_list_big[j][0]) and (\n whole_circle_list_big[j][0] <= (except_box_big[i][0] + ex_w_big)) \\\n and ((except_box_big[i][1] - ex_h_big) <= whole_circle_list_big[j][1]) and (\n whole_circle_list_big[j][1] <= (except_box_big[i][1] + ex_h_big)):\n delete_item_list_big.append([whole_circle_list_big[j][0], whole_circle_list_big[j][1]])\n\n delete_item_list_big = list(unique_everseen(delete_item_list_big))\n\n # print(\"1. whole_circle_list\", whole_circle_list)\n\n for i in range(len(delete_item_list_big)):\n if (0 <= abs(delete_item_list_big[i][0] - EA_X_big) and abs(\n delete_item_list_big[i][0] - EA_X_big) <= 3) and (\n 0 <= abs(delete_item_list_big[i][1] - EA_Y_big) and abs(\n delete_item_list_big[i][1] - EA_Y_big) <= 3):\n idx = i\n\n except_idx_big = temp_whole_circle_big.index([delete_item_list_big[idx][0], delete_item_list_big[idx][1]])\n except_box_list_big.append(temp_whole_circle_big[except_idx_big])\n del circle_area_list_big[except_idx_big]\n\n for i in range(len(delete_item_list_big)):\n whole_circle_list_big.remove([delete_item_list_big[i][0], delete_item_list_big[i][1]])\n save_delete_item_list_big.append([delete_item_list_big[i][0], delete_item_list_big[i][1]])\n\n # print(\"2. whole_circle_list\", whole_circle_list)\n # print(\"3. delete_item_list\", delete_item_list)\n\n except IndexError:\n Start_except_box_big = 0\n\n except ValueError:\n pass\n\n\ndef add_except_small_area():\n global except_box_small, ex_w_small, ex_h_small\n global whole_circle_list_small, except_box_wh_small\n global save_rivet_center_flag_small, except_box_list_small, temp_whole_circle_small\n global except_idx_small, Start_except_box_small, save_delete_item_list_small, circle_area_list_small\n\n try:\n if Big_ROI_setting == True:\n EA_X_small = int(Small_Except_X.get()) * 2\n EA_Y_small = int(Small_Except_Y.get()) * 2\n ex_w_small = 7\n ex_h_small = 7\n # ex_w = int(Except_W.get()) * 2\n # ex_h = int(Except_H.get()) * 2\n\n Small_Except_X.delete(0, END)\n Small_Except_Y.delete(0, END)\n # Except_W.delete(0, END)\n # Except_H.delete(0, END)\n\n except_box_small.append([EA_X_small, EA_Y_small])\n except_box_wh_small.append([ex_w_small, ex_h_small])\n\n Start_except_box_small = 1\n\n if save_rivet_center_flag_small == 0:\n save_rivet_center_flag_small = 1\n temp_whole_circle_small = whole_circle_list_small\n\n idx = 0\n delete_item_list_small = []\n for i in range(len(except_box_small)):\n for j in range(len(whole_circle_list_small)):\n if ((except_box_small[i][0] - ex_w_small) <= whole_circle_list_small[j][0]) and (\n whole_circle_list_small[j][0] <= (except_box_small[i][0] + ex_w_small)) \\\n and ((except_box_small[i][1] - ex_h_small) <= whole_circle_list_small[j][1]) and (\n whole_circle_list_small[j][1] <= (except_box_small[i][1] + ex_h_small)):\n delete_item_list_small.append([whole_circle_list_small[j][0], whole_circle_list_small[j][1]])\n\n delete_item_list_small = list(unique_everseen(delete_item_list_small))\n\n # print(\"1. whole_circle_list\", whole_circle_list)\n\n for i in range(len(delete_item_list_small)):\n if (0 <= abs(delete_item_list_small[i][0] - EA_X_small) and abs(\n delete_item_list_small[i][0] - EA_X_small) <= 3) and (\n 0 <= abs(delete_item_list_small[i][1] - EA_Y_small) and abs(\n delete_item_list_small[i][1] - EA_Y_small) <= 3):\n idx = i\n\n except_idx_small = temp_whole_circle_small.index(\n [delete_item_list_small[idx][0], delete_item_list_small[idx][1]])\n except_box_list_small.append(temp_whole_circle_small[except_idx_small])\n del circle_area_list_small[except_idx_small]\n\n for i in range(len(delete_item_list_small)):\n whole_circle_list_small.remove([delete_item_list_small[i][0], delete_item_list_small[i][1]])\n save_delete_item_list_small.append([delete_item_list_small[i][0], delete_item_list_small[i][1]])\n\n # print(\"2. whole_circle_list\", whole_circle_list)\n # print(\"3. delete_item_list\", delete_item_list)\n\n except IndexError:\n Start_except_box_small = 0\n\n except ValueError:\n pass\n\n\ndef browse_folder_local():\n global store_local_location, check_local_path\n\n # check_local_path = True\n datapath_local.delete(0, END)\n browse = Tk()\n browse.dirName = filedialog.askdirectory()\n store_local_location = browse.dirName\n datapath_local.insert(20, store_local_location)\n browse.destroy()\n # print(store_location)\n\n\ndef browse_folder_server():\n global store_server_location, check_server_path\n\n # check_server_path = True\n datapath_server.delete(0, END)\n browse = Tk()\n browse.dirName = filedialog.askdirectory()\n store_server_location = browse.dirName\n datapath_server.insert(20, store_server_location)\n browse.destroy()\n # print(store_location)\n\n\ndef setting_window():\n global datapath_local, datapath_server, set\n # global choices\n global RS_B, TI_B\n global BIg_LU_X, Big_RD_X, Big_LU_Y, Big_RD_Y\n global Small_LU_X, Small_RD_X, Small_LU_Y, Small_RD_Y\n global Big_Except_X, Big_Except_Y, Small_Except_X, Small_Except_Y\n global B_LU_X, B_RD_X, B_LU_Y, B_RD_Y\n\n ### 설정창\n\n set = Toplevel(root)\n screen_width = set.winfo_screenwidth()\n screen_height = set.winfo_screenheight()\n tk_width, tk_height = 1920, 1080\n\n set.iconbitmap(\"aceantenna.ico\")\n set.geometry(\"{}x{}+{}+{}\".format(int(screen_width * (830 / tk_width)), int(screen_height * (1000 / tk_height)), \\\n int((screen_width / 2) - int(screen_width * (830 / tk_width) / 2)),\n int((screen_height / 2) - int(screen_height * (950 / tk_height) / 2)) - 65))\n # set.geometry(\"800x600\")\n set.title(\"Setting Window\")\n set.configure(bg=\"#ebebeb\")\n\n Label(set, text=\"Initial Setting\", font=\"Helvetica 15 bold\", bg=\"#ebebeb\", bd=2,\n width=int(screen_width * (20 / tk_width)), \\\n height=int(screen_height * (2 / tk_height)), relief=\"groove\", anchor=CENTER).place(x=0, y=0)\n\n ### ROI\n Label(set, font=\"Helvetica 15 bold\", bg=\"#ebebeb\", bd=2, width=int(screen_width * (33 / tk_width)), \\\n height=int(screen_height * (12 / tk_height)), relief=\"groove\", anchor=CENTER).place(\n x=screen_width * (0 / tk_width), y=screen_height * (70 / tk_height), relx=0.01, rely=0.01)\n\n Label(set, font=\"Helvetica 15 bold\", bg=\"#ebebeb\", bd=2, width=int(screen_width * (33 / tk_width)), \\\n height=int(screen_height * (12 / tk_height)), relief=\"groove\", anchor=CENTER).place(\n x=screen_width * (410 / tk_width), y=screen_height * (70 / tk_height), relx=0.01, rely=0.01)\n\n ###예외 지역\n Label(set, font=\"Helvetica 15 bold\", bg=\"#ebebeb\", bd=2, width=int(screen_width * (33 / tk_width)), \\\n height=int(screen_height * (12 / tk_height)), relief=\"groove\", anchor=CENTER).place(\n x=screen_width * (0 / tk_width), y=screen_height * (400 / tk_height), relx=0.01, rely=0.01)\n ### 바코드 위치\n Label(set, font=\"Helvetica 15 bold\", bg=\"#ebebeb\", bd=2, width=int(screen_width * (33 / tk_width)), \\\n height=int(screen_height * (12 / tk_height)), relief=\"groove\", anchor=CENTER).place(\n x=screen_width * (410 / tk_width), y=screen_height * (400 / tk_height), relx=0.01, rely=0.01)\n\n Label(set, text=\"Set ROI(Large_Rivet)\", height=int(screen_height * (2 / tk_height)),\n width=int(screen_width * (20 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 13 bold\").place(x=screen_width * (95 / tk_width), y=screen_height * (55 / tk_height),\n relx=0.01, rely=0.01)\n\n Label(set, text=\"Set ROI(Small_Rivet)\", height=int(screen_height * (2 / tk_height)),\n width=int(screen_width * (20 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 13 bold\").place(x=screen_width * (505 / tk_width), y=screen_height * (55 / tk_height),\n relx=0.01, rely=0.01)\n\n Label(set, text=\"Set Exception Area\", height=int(screen_height * (2 / tk_height)),\n width=int(screen_width * (20 / tk_width)),\n fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 13 bold\").place(x=screen_width * (95 / tk_width), y=screen_height * (380 / tk_height),\n relx=0.01, rely=0.01)\n\n Label(set, text=\"Set Barcode position\", height=int(screen_height * (2 / tk_height)),\n width=int(screen_width * (20 / tk_width)),\n fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 13 bold\").place(x=screen_width * (505 / tk_width), y=screen_height * (385 / tk_height),\n relx=0.01, rely=0.01)\n\n Label(set, text=\"Set Data Save Path\", font=\"Helvetica 12 bold\", fg=\"red\", bg=\"#ebebeb\", bd=2,\n width=int(screen_width * (25 / tk_width)), \\\n height=int(screen_height * (2 / tk_height)), relief=\"groove\", anchor=CENTER).place(x=0, y=screen_height * (\n 817 / tk_height))\n\n Label(set, text=\"Local\", font=\"Helvetica 12 bold\", fg=\"red\", bg=\"#ebebeb\", bd=2,\n width=int(screen_width * (10 / tk_width)), \\\n height=int(screen_height * (2 / tk_height)), relief=\"groove\", anchor=CENTER).place(x=0, y=screen_height * (\n 870 / tk_height))\n\n datapath_local = Entry(set, width=int(screen_width * (55 / tk_width)), relief=\"groove\", font=\"Helvetica 25 bold\")\n datapath_local.place(x=103, y=screen_height * (870 / tk_height), relx=0.001, rely=0)\n\n Label(set, text=\"Server\", font=\"Helvetica 12 bold\", fg=\"red\", bg=\"#ebebeb\", bd=2,\n width=int(screen_width * (10 / tk_width)), \\\n height=int(screen_height * (2 / tk_height)), relief=\"groove\", anchor=CENTER).place(x=0, y=screen_height * (\n 913 / tk_height))\n\n datapath_server = Entry(set, width=int(screen_width * (55 / tk_width)), relief=\"groove\", font=\"Helvetica 25 bold\")\n datapath_server.place(x=103, y=screen_height * (913 / tk_height), relx=0.001, rely=0)\n\n Button(set, text=\"Set Complete\", font=\"Helvetica 13 bold\", relief=\"groove\", overrelief=\"solid\", bg=\"#ebebeb\", \\\n bd=3, padx=2, pady=2, command=check_setting).pack(side=BOTTOM, fill=X)\n\n Button(set, text=\"Detect Rivet \", font=\"Helvetica 10 bold\", relief=\"raised\", overrelief=\"solid\", bg=\"#ebebeb\", \\\n width=int(screen_width * (20 / tk_width)), height=int(screen_height * (2 / tk_height)), bd=3, padx=2, pady=2,\n command=start_rivet_detect).place(x=screen_width * (460 / tk_width), y=screen_height * (815 / tk_height))\n\n Button(set, text=\"Redetect Rivet\", font=\"Helvetica 10 bold\", relief=\"raised\", overrelief=\"solid\", bg=\"#ebebeb\", \\\n width=int(screen_width * (20 / tk_width)), height=int(screen_height * (2 / tk_height)), bd=3, padx=2, pady=2,\n command=restart_rivet_detect).place(x=screen_width * (640 / tk_width), y=screen_height * (815 / tk_height))\n\n Button(set, text=\"Browse\\n(Local)\", font=\"Helvetica 10 bold\", relief=\"raised\", overrelief=\"solid\", bg=\"#ebebeb\", \\\n width=int(screen_width * (10 / tk_width)), height=int(screen_height * (2 / tk_height)), bd=3, padx=2, pady=2,\n command=browse_folder_local).place(x=screen_width * (260 / tk_width), y=screen_height * (815 / tk_height))\n\n Button(set, text=\"Browse\\n(Server)\", font=\"Helvetica 10 bold\", relief=\"raised\", overrelief=\"solid\", bg=\"#ebebeb\", \\\n width=int(screen_width * (10 / tk_width)), height=int(screen_height * (2 / tk_height)), bd=3, padx=2, pady=2,\n command=browse_folder_server).place(x=screen_width * (360 / tk_width), y=screen_height * (815 / tk_height))\n\n ### 통신 방식\n ### Label\n Label(set, text=\"Set\\nCommunication\", height=int(screen_height * (4 / tk_height)),\n width=int(screen_width * (12 / tk_width)),\n fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 13 bold\").place(x=screen_width * (0 / tk_width), y=screen_height * (713 / tk_height),\n relx=0.01, rely=0.01)\n\n ### Button\n RS_B = Button(set, text=\"RS-232\", font=\"Helvetica 10 bold\", relief=\"raised\", overrelief=\"solid\", bg=\"#ebebeb\", \\\n width=int(screen_width * (14 / tk_width)), height=int(screen_height * (2 / tk_height)), bd=3, padx=2,\n pady=2, command=select_RS_232)\n RS_B.place(x=screen_width * (135 / tk_width), y=screen_height * (710 / tk_height))\n\n TI_B = Button(set, text=\"TCP/IP\", font=\"Helvetica 10 bold\", relief=\"raised\", overrelief=\"solid\", bg=\"#ebebeb\", \\\n width=int(screen_width * (14 / tk_width)), height=int(screen_height * (2 / tk_height)), bd=3, padx=2,\n pady=2, command=select_TCP_IP)\n TI_B.place(x=screen_width * (135 / tk_width), y=screen_height * (760 / tk_height))\n\n ##### ROI #####\n ### ROI Label\n box_list = [\"Left Up\", \"Right Down\"]\n position_list = [\"X\", \"Y\"]\n for i in range(2):\n Label(set, text=box_list[i], height=int(screen_height * (2 / tk_height)),\n width=int(screen_width * (15 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 13 bold\").place(x=screen_width * (10 / tk_width) + (i * screen_width * (220 / tk_width)),\n y=screen_height * (105 / tk_height), relx=0.01, rely=0.01)\n\n Label(set, text=box_list[i], height=int(screen_height * (2 / tk_height)),\n width=int(screen_width * (15 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 13 bold\").place(x=screen_width * (420 / tk_width) + (i * screen_width * (220 / tk_width)),\n y=screen_height * (105 / tk_height), relx=0.01, rely=0.01)\n\n Label(set, text=box_list[i], height=int(screen_height * (2 / tk_height)),\n width=int(screen_width * (15 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 13 bold\").place(x=screen_width * (420 / tk_width) + (i * screen_width * (220 / tk_width)),\n y=screen_height * (435 / tk_height), relx=0.01, rely=0.01)\n\n ## ROI(BIG)\n Label(set, text=position_list[i], height=int(screen_height * (4 / tk_height)),\n width=int(screen_width * (5 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 8 bold\").place(x=screen_width * (5 / tk_width), y=(screen_height / 7) + (\n i * screen_height * (61 / tk_height)) + screen_height * (10 / tk_height), relx=0.01, rely=0.01)\n\n Label(set, text=position_list[i], height=int(screen_height * (4 / tk_height)),\n width=int(screen_width * (5 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 8 bold\").place(x=screen_width * (215 / tk_width), y=(screen_height / 7) + (\n i * screen_height * (61 / tk_height)) + screen_height * (10 / tk_height), relx=0.01, rely=0.01)\n\n ### ROI(Small)\n Label(set, text=position_list[i], height=int(screen_height * (4 / tk_height)),\n width=int(screen_width * (5 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 8 bold\").place(x=screen_width * (415 / tk_width), y=(screen_height / 7) + (\n i * screen_height * (61 / tk_height)) + screen_height * (10 / tk_height), relx=0.01, rely=0.01)\n\n Label(set, text=position_list[i], height=int(screen_height * (4 / tk_height)),\n width=int(screen_width * (5 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 8 bold\").place(x=screen_width * (625 / tk_width), y=(screen_height / 7) + (\n i * screen_height * (61 / tk_height)) + screen_height * (10 / tk_height), relx=0.01, rely=0.01)\n\n ### barcode\n Label(set, text=position_list[i], height=int(screen_height * (4 / tk_height)),\n width=int(screen_width * (5 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 8 bold\").place(x=screen_width * (415 / tk_width), y=(screen_height / 7) + (\n i * screen_height * (61 / tk_height)) + screen_height * (340 / tk_height), relx=0.01, rely=0.01)\n\n Label(set, text=position_list[i], height=int(screen_height * (4 / tk_height)),\n width=int(screen_width * (5 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 8 bold\").place(x=screen_width * (625 / tk_width), y=(screen_height / 7) + (\n i * screen_height * (61 / tk_height)) + screen_height * (340 / tk_height), relx=0.01, rely=0.01)\n\n ### ROI(BIG) X, Y Entry\n BIg_LU_X = Entry(set, width=int(screen_width * (5 / tk_width)), relief=\"groove\", font=\"Helvetica 35 bold\")\n BIg_LU_X.place(x=screen_width * (45 / tk_width), y=(screen_height / 10) + (screen_height * (57 / tk_height)),\n relx=0.01, rely=0.01)\n\n Big_RD_X = Entry(set, width=int(screen_width * (5 / tk_width)), relief=\"groove\", font=\"Helvetica 35 bold\")\n Big_RD_X.place(x=screen_width * (255 / tk_width), y=(screen_height / 10) + (screen_height * (57 / tk_height)),\n relx=0.01, rely=0.01)\n\n Big_LU_Y = Entry(set, width=int(screen_width * (5 / tk_width)), relief=\"groove\", font=\"Helvetica 35 bold\")\n Big_LU_Y.place(x=screen_width * (45 / tk_width), y=(screen_height / 10) + (screen_height * (118 / tk_height)),\n relx=0.01, rely=0.01)\n\n Big_RD_Y = Entry(set, width=int(screen_width * (5 / tk_width)), relief=\"groove\", font=\"Helvetica 35 bold\")\n Big_RD_Y.place(x=screen_width * (255 / tk_width), y=(screen_height / 10) + (screen_height * (118 / tk_height)),\n relx=0.01, rely=0.01)\n\n ### ROI(small) X, Y Entry\n Small_LU_X = Entry(set, width=int(screen_width * (5 / tk_width)), relief=\"groove\", font=\"Helvetica 35 bold\")\n Small_LU_X.place(x=screen_width * (455 / tk_width), y=(screen_height / 10) + (screen_height * (57 / tk_height)),\n relx=0.01, rely=0.01)\n\n Small_RD_X = Entry(set, width=int(screen_width * (5 / tk_width)), relief=\"groove\", font=\"Helvetica 35 bold\")\n Small_RD_X.place(x=screen_width * (665 / tk_width), y=(screen_height / 10) + (screen_height * (57 / tk_height)),\n relx=0.01, rely=0.01)\n\n Small_LU_Y = Entry(set, width=int(screen_width * (5 / tk_width)), relief=\"groove\", font=\"Helvetica 35 bold\")\n Small_LU_Y.place(x=screen_width * (455 / tk_width), y=(screen_height / 10) + (screen_height * (118 / tk_height)),\n relx=0.01, rely=0.01)\n\n Small_RD_Y = Entry(set, width=int(screen_width * (5 / tk_width)), relief=\"groove\", font=\"Helvetica 35 bold\")\n Small_RD_Y.place(x=screen_width * (665 / tk_width), y=(screen_height / 10) + (screen_height * (118 / tk_height)),\n relx=0.01, rely=0.01)\n\n ### ROI(Big) Button\n Big_ROI_B = Button(set, text=\"ROI Add\", font=\"Helvetica 10 bold\", relief=\"raised\", overrelief=\"solid\", bg=\"#ebebeb\", \\\n width=int(screen_width * (15 / tk_width)), height=int(screen_height * (2 / tk_height)), bd=3,\n padx=2, pady=2, command=add_Big_ROI)\n Big_ROI_B.place(x=screen_width * (30 / tk_width), y=screen_height * (310 / tk_height))\n\n Big_ROI_SC_B = Button(set, text=\"ROI Set Complete\", font=\"Helvetica 10 bold\", relief=\"raised\", overrelief=\"solid\",\n bg=\"#ebebeb\", \\\n width=int(screen_width * (15 / tk_width)), height=int(screen_height * (2 / tk_height)), bd=3,\n padx=2, pady=2, command=set_comp_Big_ROI)\n Big_ROI_SC_B.place(x=screen_width * (245 / tk_width), y=screen_height * (310 / tk_height))\n\n ### ROI(Small) Button\n Small_ROI_B = Button(set, text=\"ROI Add\", font=\"Helvetica 10 bold\", relief=\"raised\", overrelief=\"solid\",\n bg=\"#ebebeb\", \\\n width=int(screen_width * (15 / tk_width)), height=int(screen_height * (2 / tk_height)), bd=3,\n padx=2, pady=2, command=add_small_ROI)\n Small_ROI_B.place(x=screen_width * (440 / tk_width), y=screen_height * (310 / tk_height))\n\n Small_ROI_SC_B = Button(set, text=\"ROI Set Complete\", font=\"Helvetica 10 bold\", relief=\"raised\", overrelief=\"solid\",\n bg=\"#ebebeb\", \\\n width=int(screen_width * (15 / tk_width)), height=int(screen_height * (2 / tk_height)),\n bd=3, padx=2, pady=2, command=set_comp_Small_ROI)\n Small_ROI_SC_B.place(x=screen_width * (655 / tk_width), y=screen_height * (310 / tk_height))\n\n ### Barcode X, Y Entry\n\n B_LU_X = Entry(set, width=int(screen_width * (5 / tk_width)), relief=\"groove\", font=\"Helvetica 35 bold\")\n B_LU_X.place(x=screen_width * (455 / tk_width), y=(screen_height / 10) + (screen_height * (387 / tk_height)),\n relx=0.01, rely=0.01)\n\n B_RD_X = Entry(set, width=int(screen_width * (5 / tk_width)), relief=\"groove\", font=\"Helvetica 35 bold\")\n B_RD_X.place(x=screen_width * (665 / tk_width), y=(screen_height / 10) + (screen_height * (387 / tk_height)),\n relx=0.01, rely=0.01)\n\n B_LU_Y = Entry(set, width=int(screen_width * (5 / tk_width)), relief=\"groove\", font=\"Helvetica 35 bold\")\n B_LU_Y.place(x=screen_width * (455 / tk_width), y=(screen_height / 10) + (screen_height * (448 / tk_height)),\n relx=0.01, rely=0.01)\n\n B_RD_Y = Entry(set, width=int(screen_width * (5 / tk_width)), relief=\"groove\", font=\"Helvetica 35 bold\")\n B_RD_Y.place(x=screen_width * (665 / tk_width), y=(screen_height / 10) + (screen_height * (448 / tk_height)),\n relx=0.01, rely=0.01)\n\n ### Barcode Button\n\n B_ROI_B = Button(set, text=\"Set Barcode Area\", font=\"Helvetica 10 bold\", relief=\"raised\", overrelief=\"solid\",\n bg=\"#ebebeb\", \\\n width=int(screen_width * (15 / tk_width)), height=int(screen_height * (2 / tk_height)), bd=3,\n padx=2, pady=2, command=set_Bar_area)\n B_ROI_B.place(x=screen_width * (440 / tk_width), y=screen_height * (640 / tk_height))\n\n B_SC_B = Button(set, text=\"Reset Barcode Area\", font=\"Helvetica 10 bold\", relief=\"raised\", overrelief=\"solid\",\n bg=\"#ebebeb\", \\\n width=int(screen_width * (15 / tk_width)), height=int(screen_height * (2 / tk_height)), bd=3,\n padx=2, pady=2, command=reset_Bar_area)\n B_SC_B.place(x=screen_width * (655 / tk_width), y=screen_height * (640 / tk_height))\n\n Label(set, text=\"Big\", height=int(screen_height * (6 / tk_height)), width=int(screen_width * (5 / tk_width)),\n fg=\"red\", relief=\"groove\", bg=\"#ebebeb\", font=\"Helvetica 11 bold\") \\\n .place(x=screen_width * (5 / tk_width), y=screen_height * (442 / tk_height), relx=0.01, rely=0.01)\n Label(set, text=\"Small\", height=int(screen_height * (6 / tk_height)), width=int(screen_width * (5 / tk_width)),\n fg=\"red\", relief=\"groove\", bg=\"#ebebeb\", font=\"Helvetica 11 bold\") \\\n .place(x=screen_width * (5 / tk_width), y=screen_height * (564 / tk_height), relx=0.01, rely=0.01)\n\n excpet_item_list = [\"X\", \"Y\", \"X\", \"Y\"]\n for i in range(len(excpet_item_list)):\n Label(set, text=excpet_item_list[i], height=int(screen_height * (4 / tk_height)),\n width=int(screen_width * (5 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 8 bold\").place(x=screen_width * (60 / tk_width), y=screen_height * (437 / tk_height) + (\n i * screen_height * (61 / tk_height)), relx=0.01, rely=0.01)\n ### Except Entry\n Big_Except_X = Entry(set, width=int(screen_width * (6 / tk_width)), relief=\"groove\", font=\"Helvetica 35 bold\")\n Big_Except_X.place(x=screen_width * (100 / tk_width),\n y=screen_height * (437 / tk_height) + (screen_height * (0 / tk_height)), relx=0.01, rely=0.01)\n\n Big_Except_Y = Entry(set, width=int(screen_width * (6 / tk_width)), relief=\"groove\", font=\"Helvetica 35 bold\")\n Big_Except_Y.place(x=screen_width * (100 / tk_width),\n y=screen_height * (437 / tk_height) + (screen_height * (61 / tk_height)), relx=0.01, rely=0.01)\n\n Small_Except_X = Entry(set, width=int(screen_width * (6 / tk_width)), relief=\"groove\", font=\"Helvetica 35 bold\")\n Small_Except_X.place(x=screen_width * (100 / tk_width),\n y=screen_height * (437 / tk_height) + (screen_height * (122 / tk_height)), relx=0.01,\n rely=0.01)\n\n Small_Except_Y = Entry(set, width=int(screen_width * (6 / tk_width)), relief=\"groove\", font=\"Helvetica 35 bold\")\n Small_Except_Y.place(x=screen_width * (100 / tk_width),\n y=screen_height * (437 / tk_height) + (screen_height * (183 / tk_height)), relx=0.01,\n rely=0.01)\n\n ### Except Button\n Big_Except_B = Button(set, text=\"Add\", font=\"Helvetica 10 bold\", relief=\"raised\", overrelief=\"solid\",\n bg=\"#ebebeb\", \\\n width=int(screen_width * (6 / tk_width)), height=int(screen_height * (5 / tk_height)), bd=3,\n padx=2, pady=2, command=add_except_big_area)\n Big_Except_B.place(x=screen_width * (270 / tk_width), y=screen_height * (460 / tk_height))\n\n Small_Except_B = Button(set, text=\"Add\", font=\"Helvetica 10 bold\", relief=\"raised\", overrelief=\"solid\",\n bg=\"#ebebeb\", \\\n width=int(screen_width * (6 / tk_width)), height=int(screen_height * (5 / tk_height)), bd=3,\n padx=2, pady=2, command=add_except_small_area)\n Small_Except_B.place(x=screen_width * (270 / tk_width), y=screen_height * (580 / tk_height))\n\n Big_Except_SC_B = Button(set, text=\"Setting\\nComplete\", font=\"Helvetica 10 bold\", relief=\"raised\",\n overrelief=\"solid\",\n bg=\"#ebebeb\", \\\n width=int(screen_width * (7 / tk_width)), height=int(screen_height * (5 / tk_height)),\n bd=3, padx=2, pady=2, command=set_comp_big_except)\n Big_Except_SC_B.place(x=screen_width * (335 / tk_width), y=screen_height * (460 / tk_height))\n\n Small_Except_SC_B = Button(set, text=\"Setting\\nComplete\", font=\"Helvetica 10 bold\", relief=\"raised\",\n overrelief=\"solid\",\n bg=\"#ebebeb\", \\\n width=int(screen_width * (7 / tk_width)), height=int(screen_height * (5 / tk_height)),\n bd=3, padx=2, pady=2, command=set_comp_small_except)\n Small_Except_SC_B.place(x=screen_width * (335 / tk_width), y=screen_height * (580 / tk_height))\n\n save_data_B = Button(set, text=\"Save Setting Data\", font=\"Helvetica 10 bold\", relief=\"raised\", overrelief=\"solid\", bg=\"#ebebeb\",\n width=int(screen_width * (15 / tk_width)), height=int(screen_height * (2 / tk_height)), bd=3, padx=2, pady=2, command=save_setting)\n save_data_B.place(x=screen_width * (530 / tk_width), y=screen_height * (10 / tk_height))\n\n load_data_B = Button(set, text=\"load Setting Data\", font=\"Helvetica 10 bold\", relief=\"raised\", overrelief=\"solid\", bg=\"#ebebeb\",\n width=int(screen_width * (15 / tk_width)), height=int(screen_height * (2 / tk_height)), bd=3, padx=2, pady=2, command=load_setting)\n load_data_B.place(x=screen_width * (680 / tk_width), y=screen_height * (10 / tk_height))\n\ndef main():\n global root, cam1_label\n global RV_SN, RV_TIME, RV_ACC, RV_PASS, RV_NG, RV_TACT, result_label, image_label, text_label\n global save_setting_list\n # global SN_label\n # global image_label, set, datapath_local\n\n root = Tk()\n root.iconbitmap(\"aceantenna.ico\")\n\n root.bind('<Escape>', lambda e: root.quit())\n root.bind(\"<Double-Button-1>\", mouse_position)\n # root.bind(\"<Motion>\", mouse_position)\n\n screen_width = root.winfo_screenwidth()\n screen_height = root.winfo_screenheight()\n tk_width, tk_height = 1920, 1080\n\n cam1_label = Label(root)\n cam1_label.place(x=screen_width * (10 / tk_width), y=screen_height * (10 / tk_height))\n\n result_label = Label(root)\n image_label = Label(root)\n text_label = Label(root)\n\n root.title(\"Air3239 Check Rivet\")\n root.geometry(\"{}x{}+{}+{}\".format(screen_width, screen_height, -10, 0))\n\n name = [\"Serial\\nNumber\", \"Time\", \"No. of\\nAccumulation\",\n \"No. of\\nOK\", \"No. of\\nNG\", \"Tact Time\", ]\n\n ##정보 Label 생성\n for i in range(len(name)):\n Label(root, text=name[i], height=int(screen_height * (5 / tk_height)),\n width=int(screen_width * (17 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 9 bold\") \\\n .place(x=screen_width * (95 / tk_width),\n y=(screen_height / 3) + screen_height * (140 / tk_height) + (i * screen_height * (80 / tk_height)),\n relx=0.01, rely=0.01)\n\n Label(root, text=\"Rivet \\nDetect Info\", height=int(screen_height * (25 / tk_height)),\n width=int(screen_width * (11 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 13 bold\").place(x=-14, y=(screen_height / 3) + screen_height * (140 / tk_height) + (\n 0 * screen_height * (80 / tk_height)), relx=0.01, rely=0.01)\n\n Label(root, height=int(screen_height * (25 / tk_height)), width=int(screen_width * (90 / tk_width)), fg=\"red\",\n relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 13 bold\").place(x=screen_width * (970 / tk_width),\n y=(screen_height / 3) + screen_height * (140 / tk_height) + (\n 0 * screen_height * (80 / tk_height)), relx=0.01, rely=0.01)\n\n Label(root, text=\"Open folder\", height=int(screen_height * (5 / tk_height)),\n width=int(screen_width * (13 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 13 bold\").place(x=screen_width * (970 / tk_width),\n y=(screen_height / 3) + screen_height * (140 / tk_height) + (\n 0 * screen_height * (80 / tk_height)), relx=0.01, rely=0.01)\n\n Label(root, text=\"Rivet Count\\n(NG Count)\", height=int(screen_height * (5 / tk_height)),\n width=int(screen_width * (13 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 13 bold\").place(x=screen_width * (970 / tk_width),\n y=(screen_height / 3) + screen_height * (270 / tk_height) + (\n 0 * screen_height * (80 / tk_height)), relx=0.01, rely=0.01)\n\n Label(root, text=\"Result\", height=int(screen_height * (5 / tk_height)),\n width=int(screen_width * (13 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 13 bold\").place(x=screen_width * (1450 / tk_width),\n y=(screen_height / 3) + screen_height * (270 / tk_height) + (\n 0 * screen_height * (80 / tk_height)), relx=0.01, rely=0.01)\n '''\n Label(root, text=\"Rivet Count\", height=int(screen_height * (3 / tk_height)),\n width=int(screen_width * (13 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 13 bold\").place(x=screen_width * (1650 / tk_width),\n y = screen_height * (30 / tk_height), relx=0.01, rely=0.01)\n '''\n\n MF_name_list = [\"PASS\", \"FAIL\", \"LOG\"]\n for i in range(len(MF_name_list)):\n Label(root, text=MF_name_list[i], height=int(screen_height * (4 / tk_height)),\n width=int(screen_width * (10 / tk_width)), fg=\"red\", relief=\"groove\", bg=\"#ebebeb\",\n font=\"Helvetica 12 bold\") \\\n .place(x=screen_width * (1160 / tk_width) + (i * 230),\n y=(screen_height / 3) + screen_height * (150 / tk_height), relx=0.01, rely=0.01)\n\n Button(root, text=\"Open\\nPass Folder\", font=\"Helvetica 10 bold\", relief=\"raised\", overrelief=\"solid\", bg=\"#ebebeb\", \\\n width=int(screen_width * (10 / tk_width)), height=int(screen_height * (4 / tk_height)), bd=3, padx=2, pady=2,\n command=open_folder_pass) \\\n .place(x=screen_width * (1290 / tk_width) + (0 * 230),\n y=(screen_height / 3) + screen_height * (161 / tk_height) + (0 * screen_height * (80 / tk_height)))\n\n Button(root, text=\"Open\\nFail Folder\", font=\"Helvetica 10 bold\", relief=\"raised\", overrelief=\"solid\", bg=\"#ebebeb\", \\\n width=int(screen_width * (10 / tk_width)), height=int(screen_height * (4 / tk_height)), bd=3, padx=2, pady=2,\n command=open_folder_ng) \\\n .place(x=screen_width * (1290 / tk_width) + (1 * 230),\n y=(screen_height / 3) + screen_height * (161 / tk_height) + (0 * screen_height * (80 / tk_height)))\n\n Button(root, text=\"Open\\nLog Folder\", font=\"Helvetica 10 bold\", relief=\"raised\", overrelief=\"solid\", bg=\"#ebebeb\", \\\n width=int(screen_width * (10 / tk_width)), height=int(screen_height * (4 / tk_height)), bd=3, padx=2, pady=2,\n command=open_folder_log) \\\n .place(x=screen_width * (1290 / tk_width) + (2 * 230),\n y=(screen_height / 3) + screen_height * (161 / tk_height) + (0 * screen_height * (80 / tk_height)))\n\n '''\n Button(root, text=\"Rotate\\n-90 degree\", font=\"Helvetica 10 bold\", relief=\"raised\", overrelief=\"solid\", bg=\"#ebebeb\", \\\n width=int(screen_width * (10 / tk_width)), height=int(screen_height * (4 / tk_height)), bd=3, padx=2, pady=2,\n command=roate_left) \\\n .place(x=screen_width * (1150 / tk_width), y=(screen_height / 3) + screen_height * (290 / tk_height))\n\n Button(root, text=\"Rotate\\n90 degree\", font=\"Helvetica 10 bold\", relief=\"raised\", overrelief=\"solid\", bg=\"#ebebeb\", \\\n width=int(screen_width * (10 / tk_width)), height=int(screen_height * (4 / tk_height)), bd=3, padx=2, pady=2,\n command=roate_right) \\\n .place(x=screen_width * (1250 / tk_width), y=(screen_height / 3) + screen_height * (290 / tk_height))\n '''\n\n RV_SN = Entry(root, width=int(screen_width * (19 / tk_width)), relief=\"groove\", font=\"Helvetica 50 bold\")\n RV_SN.place(x=screen_width * (218 / tk_width),\n y=(screen_height / 3) + screen_height * (140 / tk_height) + (0 * screen_height * (80 / tk_height)),\n relx=0.01, rely=0.01)\n\n RV_TIME = Entry(root, width=int(screen_width * (19 / tk_width)), relief=\"groove\", font=\"Helvetica 50 bold\")\n RV_TIME.place(x=screen_width * (218 / tk_width),\n y=(screen_height / 3) + screen_height * (140 / tk_height) + (1 * screen_height * (80 / tk_height)),\n relx=0.01, rely=0.01)\n\n RV_ACC = Entry(root, width=int(screen_width * (19 / tk_width)), relief=\"groove\", font=\"Helvetica 50 bold\")\n RV_ACC.place(x=screen_width * (218 / tk_width),\n y=(screen_height / 3) + screen_height * (140 / tk_height) + (2 * screen_height * (80 / tk_height)),\n relx=0.01, rely=0.01)\n\n RV_PASS = Entry(root, width=int(screen_width * (19 / tk_width)), relief=\"groove\", font=\"Helvetica 50 bold\")\n RV_PASS.place(x=screen_width * (218 / tk_width),\n y=(screen_height / 3) + screen_height * (140 / tk_height) + (3 * screen_height * (80 / tk_height)),\n relx=0.01, rely=0.01)\n\n RV_NG = Entry(root, width=int(screen_width * (19 / tk_width)), relief=\"groove\", font=\"Helvetica 50 bold\")\n RV_NG.place(x=screen_width * (218 / tk_width),\n y=(screen_height / 3) + screen_height * (140 / tk_height) + (4 * screen_height * (80 / tk_height)),\n relx=0.01, rely=0.01)\n\n RV_TACT = Entry(root, width=int(screen_width * (19 / tk_width)), relief=\"groove\", font=\"Helvetica 50 bold\")\n RV_TACT.place(x=screen_width * (218 / tk_width),\n y=(screen_height / 3) + screen_height * (140 / tk_height) + (5 * screen_height * (80 / tk_height)),\n relx=0.01, rely=0.01)\n\n imageData = PhotoImage(file=\"C:/AceVision/attached file/image/ace_logo.png\")\n label_main = Label(root, image=imageData)\n # label_main.place(x = screen_width * (1690 / tk_width), y = screen_height * (937 / tk_height))\n label_main.place(x=screen_width * (1720 / tk_width), y=screen_height * (-2 / tk_height))\n\n setting_window()\n read_frame()\n\n root.mainloop()\n\n\nif __name__ == \"__main__\":\n main()\n\n"
] |
[
[
"numpy.around"
]
] |
nd1511/pytorch2keras
|
[
"db9c50ebea98dc59c85f9b1066fa06bcc78ff316"
] |
[
"tests/models/resnet18_channels_last.py"
] |
[
"import numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom pytorch2keras.converter import pytorch_to_keras\nimport torchvision\n\n\ndef check_error(output, k_model, input_np, epsilon=1e-5):\n pytorch_output = output.data.numpy()\n keras_output = k_model.predict(input_np)\n\n error = np.max(pytorch_output - keras_output)\n print('Error:', error)\n\n assert error < epsilon\n return error\n\n\nif __name__ == '__main__':\n max_error = 0\n for i in range(100):\n model = torchvision.models.resnet18()\n model.eval()\n\n input_np = np.random.uniform(0, 1, (1, 3, 224, 224))\n input_var = Variable(torch.FloatTensor(input_np))\n output = model(input_var)\n\n k_model = pytorch_to_keras(model, input_var, (3, 224, 224,), verbose=True, change_ordering=True)\n\n error = check_error(output, k_model, input_np.transpose(0, 2, 3, 1)) \n if max_error < error:\n max_error = error\n\n print('Max error: {0}'.format(max_error))\n"
] |
[
[
"numpy.max",
"torch.FloatTensor",
"numpy.random.uniform"
]
] |
akesandgren/numpy
|
[
"cc51ba88af13175d4bdf9e7bf9675a88e3cb10ea"
] |
[
"numpy/core/tests/test_api.py"
] |
[
"from __future__ import division, absolute_import, print_function\n\nimport sys\n\nimport numpy as np\nfrom numpy.compat import sixu\nfrom numpy.testing import (\n run_module_suite, assert_, assert_equal, assert_array_equal,\n assert_raises\n)\n\n# Switch between new behaviour when NPY_RELAXED_STRIDES_CHECKING is set.\nNPY_RELAXED_STRIDES_CHECKING = np.ones((10, 1), order='C').flags.f_contiguous\n\n\ndef test_array_array():\n tobj = type(object)\n ones11 = np.ones((1, 1), np.float64)\n tndarray = type(ones11)\n # Test is_ndarray\n assert_equal(np.array(ones11, dtype=np.float64), ones11)\n old_refcount = sys.getrefcount(tndarray)\n np.array(ones11)\n assert_equal(old_refcount, sys.getrefcount(tndarray))\n\n # test None\n assert_equal(np.array(None, dtype=np.float64),\n np.array(np.nan, dtype=np.float64))\n old_refcount = sys.getrefcount(tobj)\n np.array(None, dtype=np.float64)\n assert_equal(old_refcount, sys.getrefcount(tobj))\n\n # test scalar\n assert_equal(np.array(1.0, dtype=np.float64),\n np.ones((), dtype=np.float64))\n old_refcount = sys.getrefcount(np.float64)\n np.array(np.array(1.0, dtype=np.float64), dtype=np.float64)\n assert_equal(old_refcount, sys.getrefcount(np.float64))\n\n # test string\n S2 = np.dtype((str, 2))\n S3 = np.dtype((str, 3))\n S5 = np.dtype((str, 5))\n assert_equal(np.array(\"1.0\", dtype=np.float64),\n np.ones((), dtype=np.float64))\n assert_equal(np.array(\"1.0\").dtype, S3)\n assert_equal(np.array(\"1.0\", dtype=str).dtype, S3)\n assert_equal(np.array(\"1.0\", dtype=S2), np.array(\"1.\"))\n assert_equal(np.array(\"1\", dtype=S5), np.ones((), dtype=S5))\n\n # test unicode\n _unicode = globals().get(\"unicode\")\n if _unicode:\n U2 = np.dtype((_unicode, 2))\n U3 = np.dtype((_unicode, 3))\n U5 = np.dtype((_unicode, 5))\n assert_equal(np.array(_unicode(\"1.0\"), dtype=np.float64),\n np.ones((), dtype=np.float64))\n assert_equal(np.array(_unicode(\"1.0\")).dtype, U3)\n assert_equal(np.array(_unicode(\"1.0\"), dtype=_unicode).dtype, U3)\n assert_equal(np.array(_unicode(\"1.0\"), dtype=U2),\n np.array(_unicode(\"1.\")))\n assert_equal(np.array(_unicode(\"1\"), dtype=U5),\n np.ones((), dtype=U5))\n\n builtins = getattr(__builtins__, '__dict__', __builtins__)\n assert_(hasattr(builtins, 'get'))\n\n # test buffer\n _buffer = builtins.get(\"buffer\")\n if _buffer and sys.version_info[:3] >= (2, 7, 5):\n # This test fails for earlier versions of Python.\n # Evidently a bug got fixed in 2.7.5.\n dat = np.array(_buffer('1.0'), dtype=np.float64)\n assert_equal(dat, [49.0, 46.0, 48.0])\n assert_(dat.dtype.type is np.float64)\n\n dat = np.array(_buffer(b'1.0'))\n assert_equal(dat, [49, 46, 48])\n assert_(dat.dtype.type is np.uint8)\n\n # test memoryview, new version of buffer\n _memoryview = builtins.get(\"memoryview\")\n if _memoryview:\n dat = np.array(_memoryview(b'1.0'), dtype=np.float64)\n assert_equal(dat, [49.0, 46.0, 48.0])\n assert_(dat.dtype.type is np.float64)\n\n dat = np.array(_memoryview(b'1.0'))\n assert_equal(dat, [49, 46, 48])\n assert_(dat.dtype.type is np.uint8)\n\n # test array interface\n a = np.array(100.0, dtype=np.float64)\n o = type(\"o\", (object,),\n dict(__array_interface__=a.__array_interface__))\n assert_equal(np.array(o, dtype=np.float64), a)\n\n # test array_struct interface\n a = np.array([(1, 4.0, 'Hello'), (2, 6.0, 'World')],\n dtype=[('f0', int), ('f1', float), ('f2', str)])\n o = type(\"o\", (object,),\n dict(__array_struct__=a.__array_struct__))\n ## wasn't what I expected... is np.array(o) supposed to equal a ?\n ## instead we get a array([...], dtype=\">V18\")\n assert_equal(str(np.array(o).data), str(a.data))\n\n # test array\n o = type(\"o\", (object,),\n dict(__array__=lambda *x: np.array(100.0, dtype=np.float64)))()\n assert_equal(np.array(o, dtype=np.float64), np.array(100.0, np.float64))\n\n # test recursion\n nested = 1.5\n for i in range(np.MAXDIMS):\n nested = [nested]\n\n # no error\n np.array(nested)\n\n # Exceeds recursion limit\n assert_raises(ValueError, np.array, [nested], dtype=np.float64)\n\n # Try with lists...\n assert_equal(np.array([None] * 10, dtype=np.float64),\n np.full((10,), np.nan, dtype=np.float64))\n assert_equal(np.array([[None]] * 10, dtype=np.float64),\n np.full((10, 1), np.nan, dtype=np.float64))\n assert_equal(np.array([[None] * 10], dtype=np.float64),\n np.full((1, 10), np.nan, dtype=np.float64))\n assert_equal(np.array([[None] * 10] * 10, dtype=np.float64),\n np.full((10, 10), np.nan, dtype=np.float64))\n\n assert_equal(np.array([1.0] * 10, dtype=np.float64),\n np.ones((10,), dtype=np.float64))\n assert_equal(np.array([[1.0]] * 10, dtype=np.float64),\n np.ones((10, 1), dtype=np.float64))\n assert_equal(np.array([[1.0] * 10], dtype=np.float64),\n np.ones((1, 10), dtype=np.float64))\n assert_equal(np.array([[1.0] * 10] * 10, dtype=np.float64),\n np.ones((10, 10), dtype=np.float64))\n\n # Try with tuples\n assert_equal(np.array((None,) * 10, dtype=np.float64),\n np.full((10,), np.nan, dtype=np.float64))\n assert_equal(np.array([(None,)] * 10, dtype=np.float64),\n np.full((10, 1), np.nan, dtype=np.float64))\n assert_equal(np.array([(None,) * 10], dtype=np.float64),\n np.full((1, 10), np.nan, dtype=np.float64))\n assert_equal(np.array([(None,) * 10] * 10, dtype=np.float64),\n np.full((10, 10), np.nan, dtype=np.float64))\n\n assert_equal(np.array((1.0,) * 10, dtype=np.float64),\n np.ones((10,), dtype=np.float64))\n assert_equal(np.array([(1.0,)] * 10, dtype=np.float64),\n np.ones((10, 1), dtype=np.float64))\n assert_equal(np.array([(1.0,) * 10], dtype=np.float64),\n np.ones((1, 10), dtype=np.float64))\n assert_equal(np.array([(1.0,) * 10] * 10, dtype=np.float64),\n np.ones((10, 10), dtype=np.float64))\n\n\ndef test_fastCopyAndTranspose():\n # 0D array\n a = np.array(2)\n b = np.fastCopyAndTranspose(a)\n assert_equal(b, a.T)\n assert_(b.flags.owndata)\n\n # 1D array\n a = np.array([3, 2, 7, 0])\n b = np.fastCopyAndTranspose(a)\n assert_equal(b, a.T)\n assert_(b.flags.owndata)\n\n # 2D array\n a = np.arange(6).reshape(2, 3)\n b = np.fastCopyAndTranspose(a)\n assert_equal(b, a.T)\n assert_(b.flags.owndata)\n\ndef test_array_astype():\n a = np.arange(6, dtype='f4').reshape(2, 3)\n # Default behavior: allows unsafe casts, keeps memory layout,\n # always copies.\n b = a.astype('i4')\n assert_equal(a, b)\n assert_equal(b.dtype, np.dtype('i4'))\n assert_equal(a.strides, b.strides)\n b = a.T.astype('i4')\n assert_equal(a.T, b)\n assert_equal(b.dtype, np.dtype('i4'))\n assert_equal(a.T.strides, b.strides)\n b = a.astype('f4')\n assert_equal(a, b)\n assert_(not (a is b))\n\n # copy=False parameter can sometimes skip a copy\n b = a.astype('f4', copy=False)\n assert_(a is b)\n\n # order parameter allows overriding of the memory layout,\n # forcing a copy if the layout is wrong\n b = a.astype('f4', order='F', copy=False)\n assert_equal(a, b)\n assert_(not (a is b))\n assert_(b.flags.f_contiguous)\n\n b = a.astype('f4', order='C', copy=False)\n assert_equal(a, b)\n assert_(a is b)\n assert_(b.flags.c_contiguous)\n\n # casting parameter allows catching bad casts\n b = a.astype('c8', casting='safe')\n assert_equal(a, b)\n assert_equal(b.dtype, np.dtype('c8'))\n\n assert_raises(TypeError, a.astype, 'i4', casting='safe')\n\n # subok=False passes through a non-subclassed array\n b = a.astype('f4', subok=0, copy=False)\n assert_(a is b)\n\n a = np.matrix([[0, 1, 2], [3, 4, 5]], dtype='f4')\n\n # subok=True passes through a matrix\n b = a.astype('f4', subok=True, copy=False)\n assert_(a is b)\n\n # subok=True is default, and creates a subtype on a cast\n b = a.astype('i4', copy=False)\n assert_equal(a, b)\n assert_equal(type(b), np.matrix)\n\n # subok=False never returns a matrix\n b = a.astype('f4', subok=False, copy=False)\n assert_equal(a, b)\n assert_(not (a is b))\n assert_(type(b) is not np.matrix)\n\n # Make sure converting from string object to fixed length string\n # does not truncate.\n a = np.array([b'a'*100], dtype='O')\n b = a.astype('S')\n assert_equal(a, b)\n assert_equal(b.dtype, np.dtype('S100'))\n a = np.array([sixu('a')*100], dtype='O')\n b = a.astype('U')\n assert_equal(a, b)\n assert_equal(b.dtype, np.dtype('U100'))\n\n # Same test as above but for strings shorter than 64 characters\n a = np.array([b'a'*10], dtype='O')\n b = a.astype('S')\n assert_equal(a, b)\n assert_equal(b.dtype, np.dtype('S10'))\n a = np.array([sixu('a')*10], dtype='O')\n b = a.astype('U')\n assert_equal(a, b)\n assert_equal(b.dtype, np.dtype('U10'))\n\n a = np.array(123456789012345678901234567890, dtype='O').astype('S')\n assert_array_equal(a, np.array(b'1234567890' * 3, dtype='S30'))\n a = np.array(123456789012345678901234567890, dtype='O').astype('U')\n assert_array_equal(a, np.array(sixu('1234567890' * 3), dtype='U30'))\n\n a = np.array([123456789012345678901234567890], dtype='O').astype('S')\n assert_array_equal(a, np.array(b'1234567890' * 3, dtype='S30'))\n a = np.array([123456789012345678901234567890], dtype='O').astype('U')\n assert_array_equal(a, np.array(sixu('1234567890' * 3), dtype='U30'))\n\n a = np.array(123456789012345678901234567890, dtype='S')\n assert_array_equal(a, np.array(b'1234567890' * 3, dtype='S30'))\n a = np.array(123456789012345678901234567890, dtype='U')\n assert_array_equal(a, np.array(sixu('1234567890' * 3), dtype='U30'))\n\n a = np.array(sixu('a\\u0140'), dtype='U')\n b = np.ndarray(buffer=a, dtype='uint32', shape=2)\n assert_(b.size == 2)\n\n a = np.array([1000], dtype='i4')\n assert_raises(TypeError, a.astype, 'S1', casting='safe')\n\n a = np.array(1000, dtype='i4')\n assert_raises(TypeError, a.astype, 'U1', casting='safe')\n\ndef test_copyto_fromscalar():\n a = np.arange(6, dtype='f4').reshape(2, 3)\n\n # Simple copy\n np.copyto(a, 1.5)\n assert_equal(a, 1.5)\n np.copyto(a.T, 2.5)\n assert_equal(a, 2.5)\n\n # Where-masked copy\n mask = np.array([[0, 1, 0], [0, 0, 1]], dtype='?')\n np.copyto(a, 3.5, where=mask)\n assert_equal(a, [[2.5, 3.5, 2.5], [2.5, 2.5, 3.5]])\n mask = np.array([[0, 1], [1, 1], [1, 0]], dtype='?')\n np.copyto(a.T, 4.5, where=mask)\n assert_equal(a, [[2.5, 4.5, 4.5], [4.5, 4.5, 3.5]])\n\ndef test_copyto():\n a = np.arange(6, dtype='i4').reshape(2, 3)\n\n # Simple copy\n np.copyto(a, [[3, 1, 5], [6, 2, 1]])\n assert_equal(a, [[3, 1, 5], [6, 2, 1]])\n\n # Overlapping copy should work\n np.copyto(a[:, :2], a[::-1, 1::-1])\n assert_equal(a, [[2, 6, 5], [1, 3, 1]])\n\n # Defaults to 'same_kind' casting\n assert_raises(TypeError, np.copyto, a, 1.5)\n\n # Force a copy with 'unsafe' casting, truncating 1.5 to 1\n np.copyto(a, 1.5, casting='unsafe')\n assert_equal(a, 1)\n\n # Copying with a mask\n np.copyto(a, 3, where=[True, False, True])\n assert_equal(a, [[3, 1, 3], [3, 1, 3]])\n\n # Casting rule still applies with a mask\n assert_raises(TypeError, np.copyto, a, 3.5, where=[True, False, True])\n\n # Lists of integer 0's and 1's is ok too\n np.copyto(a, 4.0, casting='unsafe', where=[[0, 1, 1], [1, 0, 0]])\n assert_equal(a, [[3, 4, 4], [4, 1, 3]])\n\n # Overlapping copy with mask should work\n np.copyto(a[:, :2], a[::-1, 1::-1], where=[[0, 1], [1, 1]])\n assert_equal(a, [[3, 4, 4], [4, 3, 3]])\n\n # 'dst' must be an array\n assert_raises(TypeError, np.copyto, [1, 2, 3], [2, 3, 4])\n\ndef test_copyto_permut():\n # test explicit overflow case\n pad = 500\n l = [True] * pad + [True, True, True, True]\n r = np.zeros(len(l)-pad)\n d = np.ones(len(l)-pad)\n mask = np.array(l)[pad:]\n np.copyto(r, d, where=mask[::-1])\n\n # test all permutation of possible masks, 9 should be sufficient for\n # current 4 byte unrolled code\n power = 9\n d = np.ones(power)\n for i in range(2**power):\n r = np.zeros(power)\n l = [(i & x) != 0 for x in range(power)]\n mask = np.array(l)\n np.copyto(r, d, where=mask)\n assert_array_equal(r == 1, l)\n assert_equal(r.sum(), sum(l))\n\n r = np.zeros(power)\n np.copyto(r, d, where=mask[::-1])\n assert_array_equal(r == 1, l[::-1])\n assert_equal(r.sum(), sum(l))\n\n r = np.zeros(power)\n np.copyto(r[::2], d[::2], where=mask[::2])\n assert_array_equal(r[::2] == 1, l[::2])\n assert_equal(r[::2].sum(), sum(l[::2]))\n\n r = np.zeros(power)\n np.copyto(r[::2], d[::2], where=mask[::-2])\n assert_array_equal(r[::2] == 1, l[::-2])\n assert_equal(r[::2].sum(), sum(l[::-2]))\n\n for c in [0xFF, 0x7F, 0x02, 0x10]:\n r = np.zeros(power)\n mask = np.array(l)\n imask = np.array(l).view(np.uint8)\n imask[mask != 0] = c\n np.copyto(r, d, where=mask)\n assert_array_equal(r == 1, l)\n assert_equal(r.sum(), sum(l))\n\n r = np.zeros(power)\n np.copyto(r, d, where=True)\n assert_equal(r.sum(), r.size)\n r = np.ones(power)\n d = np.zeros(power)\n np.copyto(r, d, where=False)\n assert_equal(r.sum(), r.size)\n\ndef test_copy_order():\n a = np.arange(24).reshape(2, 1, 3, 4)\n b = a.copy(order='F')\n c = np.arange(24).reshape(2, 1, 4, 3).swapaxes(2, 3)\n\n def check_copy_result(x, y, ccontig, fcontig, strides=False):\n assert_(not (x is y))\n assert_equal(x, y)\n assert_equal(res.flags.c_contiguous, ccontig)\n assert_equal(res.flags.f_contiguous, fcontig)\n # This check is impossible only because\n # NPY_RELAXED_STRIDES_CHECKING changes the strides actively\n if not NPY_RELAXED_STRIDES_CHECKING:\n if strides:\n assert_equal(x.strides, y.strides)\n else:\n assert_(x.strides != y.strides)\n\n # Validate the initial state of a, b, and c\n assert_(a.flags.c_contiguous)\n assert_(not a.flags.f_contiguous)\n assert_(not b.flags.c_contiguous)\n assert_(b.flags.f_contiguous)\n assert_(not c.flags.c_contiguous)\n assert_(not c.flags.f_contiguous)\n\n # Copy with order='C'\n res = a.copy(order='C')\n check_copy_result(res, a, ccontig=True, fcontig=False, strides=True)\n res = b.copy(order='C')\n check_copy_result(res, b, ccontig=True, fcontig=False, strides=False)\n res = c.copy(order='C')\n check_copy_result(res, c, ccontig=True, fcontig=False, strides=False)\n res = np.copy(a, order='C')\n check_copy_result(res, a, ccontig=True, fcontig=False, strides=True)\n res = np.copy(b, order='C')\n check_copy_result(res, b, ccontig=True, fcontig=False, strides=False)\n res = np.copy(c, order='C')\n check_copy_result(res, c, ccontig=True, fcontig=False, strides=False)\n\n # Copy with order='F'\n res = a.copy(order='F')\n check_copy_result(res, a, ccontig=False, fcontig=True, strides=False)\n res = b.copy(order='F')\n check_copy_result(res, b, ccontig=False, fcontig=True, strides=True)\n res = c.copy(order='F')\n check_copy_result(res, c, ccontig=False, fcontig=True, strides=False)\n res = np.copy(a, order='F')\n check_copy_result(res, a, ccontig=False, fcontig=True, strides=False)\n res = np.copy(b, order='F')\n check_copy_result(res, b, ccontig=False, fcontig=True, strides=True)\n res = np.copy(c, order='F')\n check_copy_result(res, c, ccontig=False, fcontig=True, strides=False)\n\n # Copy with order='K'\n res = a.copy(order='K')\n check_copy_result(res, a, ccontig=True, fcontig=False, strides=True)\n res = b.copy(order='K')\n check_copy_result(res, b, ccontig=False, fcontig=True, strides=True)\n res = c.copy(order='K')\n check_copy_result(res, c, ccontig=False, fcontig=False, strides=True)\n res = np.copy(a, order='K')\n check_copy_result(res, a, ccontig=True, fcontig=False, strides=True)\n res = np.copy(b, order='K')\n check_copy_result(res, b, ccontig=False, fcontig=True, strides=True)\n res = np.copy(c, order='K')\n check_copy_result(res, c, ccontig=False, fcontig=False, strides=True)\n\ndef test_contiguous_flags():\n a = np.ones((4, 4, 1))[::2,:,:]\n if NPY_RELAXED_STRIDES_CHECKING:\n a.strides = a.strides[:2] + (-123,)\n b = np.ones((2, 2, 1, 2, 2)).swapaxes(3, 4)\n\n def check_contig(a, ccontig, fcontig):\n assert_(a.flags.c_contiguous == ccontig)\n assert_(a.flags.f_contiguous == fcontig)\n\n # Check if new arrays are correct:\n check_contig(a, False, False)\n check_contig(b, False, False)\n if NPY_RELAXED_STRIDES_CHECKING:\n check_contig(np.empty((2, 2, 0, 2, 2)), True, True)\n check_contig(np.array([[[1], [2]]], order='F'), True, True)\n else:\n check_contig(np.empty((2, 2, 0, 2, 2)), True, False)\n check_contig(np.array([[[1], [2]]], order='F'), False, True)\n check_contig(np.empty((2, 2)), True, False)\n check_contig(np.empty((2, 2), order='F'), False, True)\n\n # Check that np.array creates correct contiguous flags:\n check_contig(np.array(a, copy=False), False, False)\n check_contig(np.array(a, copy=False, order='C'), True, False)\n check_contig(np.array(a, ndmin=4, copy=False, order='F'), False, True)\n\n if NPY_RELAXED_STRIDES_CHECKING:\n # Check slicing update of flags and :\n check_contig(a[0], True, True)\n check_contig(a[None, ::4, ..., None], True, True)\n check_contig(b[0, 0, ...], False, True)\n check_contig(b[:,:, 0:0,:,:], True, True)\n else:\n # Check slicing update of flags:\n check_contig(a[0], True, False)\n # Would be nice if this was C-Contiguous:\n check_contig(a[None, 0, ..., None], False, False)\n check_contig(b[0, 0, 0, ...], False, True)\n\n # Test ravel and squeeze.\n check_contig(a.ravel(), True, True)\n check_contig(np.ones((1, 3, 1)).squeeze(), True, True)\n\ndef test_broadcast_arrays():\n # Test user defined dtypes\n a = np.array([(1, 2, 3)], dtype='u4,u4,u4')\n b = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)], dtype='u4,u4,u4')\n result = np.broadcast_arrays(a, b)\n assert_equal(result[0], np.array([(1, 2, 3), (1, 2, 3), (1, 2, 3)], dtype='u4,u4,u4'))\n assert_equal(result[1], np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)], dtype='u4,u4,u4'))\n\nif __name__ == \"__main__\":\n run_module_suite()\n"
] |
[
[
"numpy.matrix",
"numpy.ndarray",
"numpy.dtype",
"numpy.copyto",
"numpy.testing.assert_equal",
"numpy.arange",
"numpy.full",
"numpy.copy",
"numpy.zeros",
"numpy.testing.assert_raises",
"numpy.testing.assert_",
"numpy.broadcast_arrays",
"numpy.compat.sixu",
"numpy.array",
"numpy.testing.run_module_suite",
"numpy.fastCopyAndTranspose",
"numpy.ones",
"numpy.testing.assert_array_equal",
"numpy.empty"
]
] |
almaan/sepal
|
[
"9befea4b8960cb3cb6f09634886f3b57e8c56bcb"
] |
[
"compare/run-SpatialDE.py"
] |
[
"#!/usr/bin/env python3\n\n##-------------------------------------------------------------\n## SpatialDE Data Analysis \n##-------------------------------------------------------------\n\n## From : https://github.com/Teichlab/SpatialDE/README.md\n## Downloaded : 2020-08-07\n\n## Modified to time the analysis\n\nimport pandas as pd\nimport time\nimport yaml\n\nimport NaiveDE\nimport SpatialDE\n\nimport sepal.utils as ut\nimport argparse as arp\nimport os.path as osp\n\nprs = arp.ArgumentParser()\naa = prs.add_argument\n\naa(\"-c\",\"--count_data\",required = True)\naa(\"-m\",\"--meta_data\",required = True)\naa(\"-o\",\"--out_dir\",required = True)\naa(\"-t\",\"--tag\",default = None)\naa(\"-z\",\"--timeit\",default = False, action = \"store_true\")\n\n\nargs = prs.parse_args()\n\nif args.tag is None:\n tag = \"\"\nelse:\n tag = args.tag + \"-\"\n\ncounts = pd.read_csv(args.count_data,\n index_col=0)\n\ncounts = counts.T[counts.sum(0) >= 3].T # Filter practically unobserved genes\n\nsample_info = pd.read_csv(args.meta_data,\n index_col=0)\n\ncounts = counts.loc[sample_info.index] # Align count matrix with metadata table\n\nnorm_expr = NaiveDE.stabilize(counts.T).T\nresid_expr = NaiveDE.regress_out(sample_info,\n norm_expr.T,\n 'np.log(total_counts)').T\n\n# sample_resid_expr = resid_expr.sample(n=100,\n# axis=1,\n# random_state=1)\n\nX = sample_info[['x', 'y']]\n\nt_0 = time.time()\nresults = SpatialDE.run(X, resid_expr)\nt_end = time.time()\n\ntiming_dct = ut.format_timing(t_0,t_end,results,method =\"SpatialDE\")\n\nresults.to_csv(osp.join(args.out_dir,tag + \".tsv\"),\n sep = '\\t',\n header = True,\n index = True)\n\nif args.timeit:\n with open(osp.join(args.out_dir,tag +\"timing.yaml\"),\"w\") as f:\n _ = yaml.dump(timing_dct,f,default_flow_style = False)\n"
] |
[
[
"pandas.read_csv"
]
] |
jostmey/RWA
|
[
"41d73d0bd9ffba71ea5ead5b3de2704dacbe531d"
] |
[
"copy_problem_1000/dataset/input_data.py"
] |
[
"#!/usr/bin/env python3\n##########################################################################################\n# Author: Jared L. Ostmeyer\n# Date Started: 2017-01-01\n# Purpose: Load dataset or generate it if it does not exist yet.\n# License: For legal information see LICENSE in the home directory.\n##########################################################################################\n\n##########################################################################################\n# Libraries\n##########################################################################################\n\nimport os\nimport numpy as np\n\n##########################################################################################\n# Settings\n##########################################################################################\n\n# Configure dataset\n#\nS = 10\nT = 1000\nN_symbols = 8\n\n# Data dimensions\n#\nnum_train = 100000\nnum_test = 10000\nmax_length = 2*S+T\nnum_features = N_symbols+1\nnum_classes = N_symbols\n\n##########################################################################################\n# Generate/Load dataset\n##########################################################################################\n\n# Make directory\n#\n_path = '/'.join(__file__.split('/')[:-1])\nos.makedirs(_path+'/bin', exist_ok=True)\n\n# Training data\n#\nif not os.path.isfile(_path+'/bin/pattern_train.npy') or not os.path.isfile(_path+'/bin/recall_train.npy'):\n\tpattern_train = np.random.randint(num_features-2, size=(num_train, S))\n\trecall_train = 2*S+np.random.randint(1, T, size=num_train)\n\tnp.save(_path+'/bin/pattern_train.npy', pattern_train)\n\tnp.save(_path+'/bin/recall_train.npy', recall_train)\nelse:\n\tpattern_train = np.load(_path+'/bin/pattern_train.npy')\n\trecall_train = np.load(_path+'/bin/recall_train.npy')\nxs_train = np.zeros((num_train, max_length, num_features))\nls_train = max_length*np.ones((num_train))\nys_train = np.zeros((num_train, max_length, num_classes))\nxs_train[:,S:,num_features-2] = 1.0\nys_train[:,:,num_features-2] = 1.0\nfor i in range(num_train):\n\tfor j in range(S):\n\t\tk = pattern_train[i,j]\n\t\txs_train[i,j,k] = 1.0\n\t\tl = recall_train[i]\n\t\txs_train[i,l-S-1,num_features-2] = 0.0\n\t\txs_train[i,l-S-1,num_features-1] = 1.0\n\t\tys_train[i,(l-S):l,:num_classes] = xs_train[i,:S,:num_classes]\n\n# Test data\n#\nif not os.path.isfile(_path+'/bin/pattern_test.npy') or not os.path.isfile(_path+'/bin/recall_test.npy'):\n\tpattern_test = np.random.randint(num_features-2, size=(num_test, S))\n\trecall_test = 2*S+np.random.randint(1, T, size=num_test)\n\tnp.save(_path+'/bin/pattern_test.npy', pattern_test)\n\tnp.save(_path+'/bin/recall_test.npy', recall_test)\nelse:\n\tpattern_test = np.load(_path+'/bin/pattern_test.npy')\n\trecall_test = np.load(_path+'/bin/recall_test.npy')\nxs_test = np.zeros((num_test, max_length, num_features))\nls_test = max_length*np.ones((num_test))\nys_test = np.zeros((num_test, max_length, num_classes))\nxs_test[:,S:,num_features-2] = 1.0\nys_test[:,:,num_classes-1] = 1.0\nfor i in range(num_test):\n\tfor j in range(S):\n\t\tk = pattern_test[i,j]\n\t\txs_test[i,j,k] = 1.0\n\t\tl = recall_test[i]\n\t\txs_test[i,l-S-1,num_features-2] = 0.0\n\t\txs_test[i,l-S-1,num_features-1] = 1.0\n\t\tys_test[i,(l-S):l,:num_classes] = xs_test[i,:S,:num_classes]\n\n"
] |
[
[
"numpy.save",
"numpy.ones",
"numpy.load",
"numpy.zeros",
"numpy.random.randint"
]
] |
c60evaporator/param_tuning_utility
|
[
"8518b76369dcc918172a87ab4c975ee3a12f7045"
] |
[
"examples/muscle_brain_tuning/muscle_multiclass.py"
] |
[
"# %% MuscleTuning, multiclass, no argument\nimport parent_import\nfrom muscle_tuning import MuscleTuning\nimport seaborn as sns\n\niris = sns.load_dataset(\"iris\")\nOBJECTIVE_VARIALBLE = 'species' # 目的変数\nUSE_EXPLANATORY = ['petal_width', 'petal_length', 'sepal_width', 'sepal_length'] # 説明変数\ny = iris[OBJECTIVE_VARIALBLE].values\nX = iris[USE_EXPLANATORY].values\n\nkinnikun = MuscleTuning()\nkinnikun.muscle_brain_tuning(X, y, x_colnames=USE_EXPLANATORY)\nkinnikun.df_scores\n\n# %% MuscleTuning, multiclass, all arguments\nimport parent_import\nfrom muscle_tuning import MuscleTuning\nimport seaborn as sns\nfrom sklearn.svm import SVC\nfrom xgboost import XGBClassifier\n\niris = sns.load_dataset(\"iris\")\nOBJECTIVE_VARIALBLE = 'species' # 目的変数\nUSE_EXPLANATORY = ['petal_width', 'petal_length', 'sepal_width', 'sepal_length'] # 説明変数\ny = iris[OBJECTIVE_VARIALBLE].values\nX = iris[USE_EXPLANATORY].values\n\nnot_opt_params_svm = {'kernel': 'rbf'}\nnot_opt_params_xgb = {'objective': 'multi:softmax',\n 'random_state': 42,\n 'booster': 'gbtree',\n 'n_estimators': 100,\n 'use_label_encoder': False}\nfit_params_xgb = {'verbose': 0,\n 'eval_metric': 'mlogloss'}\ntuning_params_svm = {'gamma': (0.001, 1000),\n 'C': (0.001, 1000)\n }\ntuning_params_xgb = {'learning_rate': (0.05, 0.3),\n 'min_child_weight': (1, 10),\n 'max_depth': (2, 9),\n 'colsample_bytree': (0.2, 1.0),\n 'subsample': (0.2, 1.0)\n }\nkinnikun = MuscleTuning()\nkinnikun.muscle_brain_tuning(X, y, x_colnames=USE_EXPLANATORY,\n objective='classification', \n scoring='auc_ovo',\n other_scores=['accuracy', 'precision_macro', 'recall_macro', 'f1_micro', 'f1_macro', 'f1_weighted', 'auc_ovr', 'auc_ovo'],\n learning_algos=['svm', 'xgboost'], \n n_trials={'svm': 50,\n 'xgboost': 20},\n cv=3, tuning_algo='optuna', seed=42,\n estimators={'svm': SVC(),\n 'xgboost': XGBClassifier()},\n tuning_params={'svm': tuning_params_svm,\n 'xgboost': tuning_params_xgb},\n tuning_kws={'svm': {'not_opt_params': not_opt_params_svm},\n 'xgboost': {'not_opt_params': not_opt_params_xgb,\n 'fit_params': fit_params_xgb}}\n )\nkinnikun.print_estimator('xgboost')\nkinnikun.df_scores\n# %%\n"
] |
[
[
"sklearn.svm.SVC"
]
] |
0b10010010/KalmanMPI
|
[
"e82f900ac41173643fffec2b08250cddcb56dca8"
] |
[
"KalmanGUI.py"
] |
[
"import sys\nimport platform\nimport numpy as np # this has to be imported before the ones in line 11 and 12\nfrom math import floor\nimport control\nimport control.matlab as matlab\n#import matplotlib.animation as animation\n\nfrom PyQt5.QtWidgets import (QMainWindow, QApplication, QDialog, QLineEdit, \n QVBoxLayout, QAction, QMessageBox, QFileDialog,\n QSizePolicy, QPushButton, QHBoxLayout, QLabel,\n QGridLayout, QShortcut)\nfrom PyQt5.QtCore import QT_VERSION_STR, PYQT_VERSION_STR, Qt\nfrom PyQt5.QtGui import QIcon, QKeySequence\n\nfrom matplotlib.backends.backend_qt5agg import FigureCanvas\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT\nfrom matplotlib.figure import Figure \n\nclass MainWindow(QMainWindow) :\n \n def __init__(self, parent=None) :\n super(MainWindow, self).__init__(parent)\n \n # Add an Icon\n self.setWindowIcon(QIcon('guiIcon.png'))\n \n # Add Window Title\n self.setWindowTitle('Kalman Filter Simulation')\n \n # Add Shortcuts\n self.shortPlot1 = QShortcut(QKeySequence('Ctrl+p'), self)\n self.shortPlot1.activated.connect(self.runButton1)\n self.shortPlot2 = QShortcut(QKeySequence('Ctrl+v'), self)\n self.shortPlot2.activated.connect(self.runButton2)\n self.shortPlot3 = QShortcut(QKeySequence('Ctrl+c'), self)\n self.shortPlot3.activated.connect(self.clearPlot)\n self.shortPlot4 = QShortcut(QKeySequence('Ctrl+z'), self)\n self.shortPlot4.activated.connect(self.zoom)\n self.shortPlot5 = QShortcut(QKeySequence('Ctrl+a'), self)\n self.shortPlot5.activated.connect(self.pan)\n self.shortPlot6 = QShortcut(QKeySequence('Ctrl+h'), self)\n self.shortPlot6.activated.connect(self.home)\n self.shortSave = QShortcut(QKeySequence('Ctrl+s'), self)\n self.shortSave.activated.connect(self.saveas)\n self.shortClose = QShortcut(QKeySequence('Ctrl+w'), self)\n self.shortClose.activated.connect(self.close)\n\n #######################################################################\n # ADD MENU ITEMS\n #######################################################################\n \n # Create the File menu\n self.menuFile = self.menuBar().addMenu(\"&File\")\n self.actionSaveAs = QAction(\"&Save As\", self)\n self.actionSaveAs.triggered.connect(self.saveas)\n self.actionQuit = QAction(\"&Quit\", self)\n self.actionQuit.triggered.connect(self.close)\n self.menuFile.addActions([self.actionSaveAs, self.actionQuit])\n \n # Create the Help menu\n self.menuHelp = self.menuBar().addMenu(\"&Help\")\n self.actionAbout = QAction(\"&About\",self)\n self.actionAbout.triggered.connect(self.about)\n self.menuHelp.addActions([self.actionAbout])\n\n #######################################################################\n # CREATE CENTRAL WIDGET\n #######################################################################\n\n self.widget = QDialog()\n self.plot = MatplotlibCanvas()\n self.toolbar = NavigationToolbar2QT(self.plot, self)\n self.toolbar.hide()\n \n #######################################################################\n # PARAMETER EDIT BOX\n #######################################################################\n \n # Horizontal Time entries\n TimeStep = QLabel('Time Step =')\n SimLen = QLabel(' Final Time =')\n unit0 = QLabel('sec. ')\n unit1= QLabel('sec. ')\n self.dtEdit = QLineEdit('0.05')\n self.dtEdit.setFixedWidth(50)\n self.simEdit = QLineEdit('20')\n self.simEdit.setFixedWidth(50)\n\n # System Parameter\n mass = QLabel('Mass =')\n Ks = QLabel('Ks =')\n Kd = QLabel('Kd =')\n unitMass = QLabel('kg ')\n unitKs = QLabel('N/m ')\n unitKd = QLabel('N-sec/m ')\n self.massEdit = QLineEdit('1')\n self.KsEdit = QLineEdit('4')\n self.KdEdit = QLineEdit('1') \n self.massEdit.setFixedWidth(50)\n self.KsEdit.setFixedWidth(50)\n self.KdEdit.setFixedWidth(50)\n\n # State Space\n FGrid = QGridLayout()\n F = QLabel('F =')\n self.FEdit1, self.FEdit2 = QLineEdit('0.0'), QLineEdit('1.0 ')\n self.FEdit3, self.FEdit4 = QLineEdit('-Ks/m'), QLineEdit('-Kd/m ')\n self.FEdit1.setFixedWidth(40)\n self.FEdit2.setFixedWidth(40)\n self.FEdit3.setFixedWidth(40)\n self.FEdit4.setFixedWidth(40)\n FGrid.addWidget(F, 3, 0)\n FGrid.addWidget(self.FEdit1, 3, 1, 1, 1)\n FGrid.addWidget(self.FEdit2, 3, 2, 1, 1)\n FGrid.addWidget(self.FEdit3, 4, 1, 1, 1)\n FGrid.addWidget(self.FEdit4, 4, 2, 1, 1)\n \n GGrid = QGridLayout()\n G = QLabel(' G =')\n self.GEdit1, self.GEdit2 = QLineEdit('0.0'), QLineEdit('1/m')\n self.GEdit1.setFixedWidth(40)\n self.GEdit2.setFixedWidth(40)\n GGrid.addWidget(G, 3, 3)\n GGrid.addWidget(self.GEdit1, 3, 4)\n GGrid.addWidget(self.GEdit2, 4, 4)\n \n # Initial Condition\n InitCond = QGridLayout()\n IC = QLabel(' I.C. X0 =')\n self.ICEdit1, self.ICEdit2 = QLineEdit('0.25'), QLineEdit('0.0')\n self.ICEdit1.setFixedWidth(40)\n self.ICEdit2.setFixedWidth(40)\n InitCond.addWidget(IC, 3, 5)\n InitCond.addWidget(self.ICEdit1, 3, 6)\n InitCond.addWidget(self.ICEdit2, 3, 7)\n InitCond.setAlignment(Qt.AlignTop)\n \n # Noise Parameter\n distNoise = QLabel(' Disturbance Cov. =')\n self.distNoiseEdit = QLineEdit('0.0005')\n self.distNoiseEdit.setFixedWidth(80)\n distNoise.setBuddy(self.distNoiseEdit)\n AccelNoise = QLabel('Accel. Meas. Noise =')\n self.AccelNoiseEdit = QLineEdit('0.02')\n self.AccelNoiseEdit.setFixedWidth(80)\n measNoise = QLabel(' Meas. Noise =')\n self.measNoiseEdit = QLineEdit('0.001')\n self.measNoiseEdit.setFixedWidth(80)\n \n # Input Signal\n inputSignal = QLabel('Input Signal =')\n self.inputSignalEdit = QLineEdit('10*np.sin(2*np.pi*0.05*t)')\n\n # Horizontal Buttons Layout\n self.b1 = QPushButton('&Position Tracking')\n self.b2 = QPushButton('&Velocity Tracking')\n self.b3 = QPushButton('&Clear')\n \n # Horizontal Plot Toolbar\n self.b4 = QPushButton('&Zoom')\n self.b5 = QPushButton('P&an')\n self.b6 = QPushButton('&Home')\n \n # Plot window\n Graph = QVBoxLayout()\n Graph.addWidget(self.plot)\n \n # Plot Toolbar\n PlotButtons = QHBoxLayout()\n PlotButtons.addWidget(self.b6)\n PlotButtons.addWidget(self.b4)\n PlotButtons.addWidget(self.b5)\n \n # Run and clear buttons \n Buttons = QHBoxLayout()\n Buttons.addWidget(self.b1)\n Buttons.addWidget(self.b2)\n Buttons.addWidget(self.b3)\n \n # Buttons and Toolbar\n Button = QVBoxLayout()\n Button.addLayout(Buttons)\n Button.addLayout(PlotButtons)\n \n # Time parameter \n TimeLayout = QHBoxLayout()\n TimeLayout.addWidget(TimeStep)\n TimeLayout.addWidget(self.dtEdit)\n TimeLayout.addWidget(unit0)\n TimeLayout.addWidget(SimLen)\n TimeLayout.addWidget(self.simEdit)\n TimeLayout.addWidget(unit1)\n\n # System parameter \n SysParam = QHBoxLayout()\n SysParam.addWidget(mass)\n SysParam.addWidget(self.massEdit)\n SysParam.addWidget(unitMass)\n SysParam.addWidget(Ks)\n SysParam.addWidget(self.KsEdit)\n SysParam.addWidget(unitKs)\n SysParam.addWidget(Kd)\n SysParam.addWidget(self.KdEdit)\n SysParam.addWidget(unitKd)\n \n # Grid layouts \n States = QHBoxLayout()\n States.addLayout(FGrid)\n States.addLayout(GGrid)\n States.addLayout(InitCond)\n States.addStretch(1)\n \n # Noise parameter \n NoiseParam1 = QHBoxLayout()\n NoiseParam1.addWidget(distNoise)\n NoiseParam1.addWidget(self.distNoiseEdit)\n NoiseParam1.addStretch()\n NoiseParam2 = QHBoxLayout()\n NoiseParam2.addWidget(measNoise)\n NoiseParam2.addWidget(self.measNoiseEdit)\n NoiseParam2.addStretch()\n NoiseParam3 = QHBoxLayout()\n NoiseParam3.addWidget(AccelNoise)\n NoiseParam3.addWidget(self.AccelNoiseEdit)\n NoiseParam3.addStretch(1)\n\n InputParam = QHBoxLayout()\n InputParam.addWidget(inputSignal)\n InputParam.addWidget(self.inputSignalEdit)\n \n # Vertical layouts\n layoutV = QVBoxLayout()\n layoutV.addLayout(TimeLayout)\n layoutV.addLayout(SysParam)\n layoutV.addLayout(States)\n layoutV.addLayout(NoiseParam1)\n layoutV.addLayout(NoiseParam2)\n layoutV.addLayout(NoiseParam3)\n layoutV.addLayout(InputParam)\n layoutV.addLayout(Button)\n layoutV.addStretch(1)\n \n # Fianl GUI Layout \n layout = QHBoxLayout()\n layout.addLayout(Graph, 5)\n layout.addLayout(layoutV, 1)\n self.widget.setLayout(layout)\n self.setCentralWidget(self.widget)\n\n # Signals:\n # Pressing Enter returns Output\n self.inputSignalEdit.returnPressed.connect(self.runButton1)\n # Button clicks to run and clear\n self.b1.clicked.connect(self.runButton1)\n self.b2.clicked.connect(self.runButton2)\n self.b3.clicked.connect(self.clearPlot)\n self.b4.clicked.connect(self.zoom)\n self.b5.clicked.connect(self.pan)\n self.b6.clicked.connect(self.home)\n \n # Plot Toolbar functions\n def zoom(self):\n self.toolbar.zoom()\n \n def pan(self):\n self.toolbar.pan()\n \n def home(self):\n self.toolbar.home()\n\n def kalmanfilterInit(self, mode=1):\n \"\"\"\n \"\"\"\n m = eval(self.massEdit.text())\n Ks = eval(self.KsEdit.text())\n Kd = eval(self.KdEdit.text())\n F1 = eval(self.FEdit1.text())\n F2 = eval(self.FEdit2.text())\n F3 = eval(self.FEdit3.text())\n F4 = eval(self.FEdit4.text())\n G1 = eval(self.GEdit1.text())\n G2 = eval(self.GEdit2.text())\n X0_0 = eval(self.ICEdit1.text())\n X0_1 = eval(self.ICEdit2.text())\n dt = eval(self.dtEdit.text())\n time = eval(self.simEdit.text())\n \n self.m = m\n self.Ks = Ks\n self.Kd = Kd\n self.F1 = F1\n self.F2 = F2\n self.F3 = F3\n self.F4 = F4\n self.G1 = G1\n self.G2 = G2\n self.X0 = [X0_0, X0_1]\n self.dt = dt\n self.time = time \n \n F = np.array([[self.F1, self.F2], [self.F3, self.F4]])\n G = np.array([[self.G1], [self.G2]])\n H = np.array([1.0, 0.0])\n J = 0\n sysc = control.ss(F,G,H,J)\n \n # initialize simulations and Kalman Filter\n tf = max(self.time, floor(1000*self.dt))\n n = 0\n t = np.zeros((int(tf/self.dt),1))\n for i in np.arange(0,tf,self.dt):\n t[n] = i\n n += 1\n nSteps = len(t)\n Qc2 = eval(self.distNoiseEdit.text())\n Qd2 = Qc2/self.dt\n w = np.sqrt(Qd2)*np.random.randn(nSteps,1)\n R = eval(self.measNoiseEdit.text())\n v = np.sqrt(R)*np.random.randn(nSteps,1)\n sysd = control.c2d(sysc,self.dt)\n [Phi, Gamma, H, J] = control.ssdata(sysd)\n K = np.zeros((2,nSteps))\n xp = np.zeros((2,nSteps))\n Pp = np.identity(2)\n xp[:,0]=[0, 0]\n \n # initialize INS/GPS\n Fi = np.array([[0.0, 1.0],[0.0, 0.0]])\n Gi = np.array([[0],[1]])\n Hi = H*1\n Ji = 0\n Qdi2 = eval(self.AccelNoiseEdit.text())\n Qdi2 = Qdi2*Qdi2\n wi = np.sqrt(Qdi2)*np.random.randn(nSteps,1)\n Ri = R*1\n sysdi = control.c2d(control.ss(Fi,Gi,Hi,Ji),self.dt)\n [Phii, Gammai, Hi, Ji] = control.ssdata(sysdi)\n Ki = K*1\n xpi = xp*1\n Ppi = Pp*1\n \n u = eval(self.inputSignalEdit.text())\n u = 1*u.T\n yt, t, xt = matlab.lsim(sysc, u.T+w, t, self.X0) # simulate with input noise\n xt = xt.T\n y = yt+v\n \n accel = np.array([0, 1])@(F@xt + G*(u+w.T))\n accelmeas = accel + wi.T\n \n for k in range(1, nSteps):\n # MSD Filtering\n xm = Phi@xp[:,[(k-1)]] + Gamma*u[:,k-1]\n Pm = Phi@[email protected] + Gamma*Qd2*Gamma.T\n \n K[:,[k]] = [email protected]*np.linalg.inv(H@[email protected] + R) # Kalman gain K\n xp[:,[k]] = xm + K[:,[k]]*(y[0,k]-H*xm)\n Pp = Pm - K[:,[k]]@H@Pm\n \n # INS/GPS Filtering\n xmi = Phii@xpi[:,[(k-1)]] + Gammai*accelmeas[:, k-1]\n Pmi = Phii@[email protected] + Gammai*Qdi2*Gammai.T\n \n Ki[:,[k]] = [email protected]*np.linalg.inv(Hi@[email protected] + Ri) \n xpi[:,[k]] = xmi + Ki[:,[k]]*(y[0,k]-Hi*xmi)\n Ppi = Pmi - Ki[:,[k]]@Hi@Pmi\n \n if mode == 1: # returns position, estimate, and INS/GPS estimate\n return(t, xt[0,:], t, xp[0,:], t, xpi[0,:])\n elif mode == 2: # returns velocity\n return(t, xt[1,:], t, xp[1,:], t, xpi[1,:])\n \n def saveas(self):\n \"\"\"Save input and output to a text file as seperate columns\n \"\"\"\n name = QFileDialog.getSaveFileName(self, \"saveas\")[0]\n f = open(name, 'w')\n out = self.kalmanfilterInit()\n out = np.array(out)\n t = out[0] # time\n xt = out[1] # X\n xp = out[3] # MSD Estimate\n xpi = out[5] # INS/GPS Estimate\n f.write(\" Time X MSD INS/GPS\\n\")\n for i in range(len(t)):\n f.write(\"%5.4f %5.4f %5.4f %5.4f\\n\" % (t[i], xt[i], xp[i], xpi[i]))\n f.close()\n \n self.plot.savePlot()\n \n def about(self):\n QMessageBox.about(self, \n \"About Function Evaluator\",\n \"\"\"<b>Function Evaluator</b>\n <p>Copyright © 2016 Jeremy Roberts, All Rights Reserved.\n <p>Python %s -- Qt %s -- PyQt %s on %s\"\"\" %\n (platform.python_version(),\n QT_VERSION_STR, PYQT_VERSION_STR, platform.system()))\n \n def runButton1(self):\n kf = self.kalmanfilterInit()\n try:\n self.plot.redraw(kf[0], kf[1], kf[2], kf[3], kf[4], kf[5], 1)\n\n except:\n print('Input Error! Check the input')\n \n def runButton2(self):\n kf = self.kalmanfilterInit(mode=2)\n try:\n self.plot.redraw(kf[0], kf[1], kf[2], kf[3], kf[4], kf[5], 2)\n\n except:\n print('Input Error! Check the input')\n \n def clearPlot(self):\n self.plot.clear() \n\n\nclass MatplotlibCanvas(FigureCanvas):\n \"\"\" This is borrowed heavily from the matplotlib documentation;\n specifically, see:\n http://matplotlib.org/examples/user_interfaces/embedding_in_qt5.html\n \"\"\"\n def __init__(self):\n \n # Initialize the figure and axes\n self.fig = Figure()\n self.axes = self.fig.add_subplot(111)\n \n # Give it some default empty plot\n x = 0\n y = 0\n self.axes.plot(x, y)\n self.axes.set_xlabel('Time (s)')\n self.axes.set_title('Kalman Filter Simulation')\n \n # Now do the initialization of the super class\n FigureCanvas.__init__(self, self.fig)\n #self.setParent(parent)\n FigureCanvas.setSizePolicy(self,\n QSizePolicy.Expanding,\n QSizePolicy.Expanding)\n FigureCanvas.updateGeometry(self)\n \n def redraw(self, x, y, u, v, i, j, mode=1): # plots position vs time\n \"\"\" Redraw the figure with new x and y values.\n \"\"\"\n # clear the old image (axes.hold is deprecated)\n self.axes.clear()\n self.axes.set_xlabel('Time (s)')\n if mode==1:\n self.axes.set_title('Position: MSD VS. INS/GPS Estimates')\n self.axes.plot(x, y, '--', label='True Position')\n self.axes.plot(u, v, '.', label='MSD Kalman Estimate')\n self.axes.plot(i, j, label='INS/GPS Estimate')\n self.axes.set_ylabel('Position (m)')\n elif mode==2:\n self.axes.set_title('Velocity: MSD VS. INS/GPS Estimates')\n self.axes.plot(x, y, '--', label='True Position')\n self.axes.plot(u, v, '.', label='MSD Kalman Estimate')\n self.axes.plot(i, j, label='INS/GPS Estimate')\n self.axes.set_ylabel('Velocity (m/s)') \n self.axes.legend()\n self.draw()\n \n def clear(self):\n self.axes.clear()\n self.axes.set_title('Kalman Filter Simulation')\n self.axes.set_xlabel('Time (s)')\n self.draw()\n \n def savePlot(self):\n self.fig.savefig('result.png', bbpx_inches='tight')\n \napp = QApplication(sys.argv)\nform = MainWindow()\nform.resize(1000, 300)\nform.show()\napp.exec_()\n"
] |
[
[
"numpy.sqrt",
"matplotlib.figure.Figure",
"numpy.linalg.inv",
"numpy.arange",
"matplotlib.backends.backend_qt5agg.NavigationToolbar2QT",
"numpy.identity",
"numpy.random.randn",
"matplotlib.backends.backend_qt5agg.FigureCanvas.__init__",
"matplotlib.backends.backend_qt5agg.FigureCanvas.updateGeometry",
"numpy.array",
"numpy.zeros",
"matplotlib.backends.backend_qt5agg.FigureCanvas.setSizePolicy"
]
] |
arthurelmes/geo_tools
|
[
"6621d134aff0d05f185a1fcfbf9431a5f1f9764e",
"6621d134aff0d05f185a1fcfbf9431a5f1f9764e"
] |
[
"validation/plot_two_tifs.py",
"time_series/extract_samples_modviirs43.py"
] |
[
"import pandas as pd\nimport rasterio as rio\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\nimport numpy as np\nimport os, sys\n\n\nf1 = sys.argv[1]\nf2 = sys.argv[2]\nf1_qa = sys.argv[3]\nf2_qa = sys.argv[4]\n\nf1_name = os.path.basename(f1)\nf2_name = os.path.basename(f2)\nout_file_name = f1_name + \"_vs_\" + f2_name\n\nwith rio.open(f1) as b1:\n b1_data = b1.read(1)\n\nwith rio.open(f2) as b2:\n b2_data = b2.read(1)\n\nwith rio.open(f1_qa) as b1_qa:\n b1_data_qa = b1_qa.read(1)\n\nwith rio.open(f2_qa) as b2_qa:\n b2_data_qa = b2_qa.read(1)\n\n# qa screen\nb1_data = b1_data.flatten()\nb2_data = b2_data.flatten()\nb1_data_qa = b1_data_qa.flatten()\nb2_data_qa = b2_data_qa.flatten()\ndf = pd.DataFrame({'b1':b1_data, 'b2':b2_data, 'b1_qa':b1_data_qa, 'b2_qa':b2_data_qa})\n\nmask_b1 = df[ df['b1_qa'] > 0].index\ndf.drop(mask_b1, inplace=True)\n\nmask_b2 = df[ df['b2_qa'] > 0].index\ndf.drop(mask_b2, inplace=True)\n\ndf['b1'] = df['b1'] * 0.001\ndf['b2'] = df['b2'] * 0.001\n\n# plot\n\nfig, ax = plt.subplots(figsize=(15,10))\nfig.patch.set_facecolor('black')\n\n#plt.figure(figsize=(10,10))\n\nhist = plt.hist2d(df['b1'], df['b2'], bins=200,\n norm=LogNorm(), range=[[0, 1.0], [0, 1.0]], cmap=plt.cm.YlGn)\nax.set_facecolor('black')\nax.tick_params(colors='white')\nax.spines['bottom'].set_color('white')\nax.spines['left'].set_color('white')\nax.xaxis.label.set_color('white')\nax.yaxis.label.set_color('white')\n\n#fig = plt.colorbar(hist[3])\nax.set_ylim(0.0, 1.0)\nax.set_xlim(0.0, 1.0)\nax.set_xlabel(f1_name)\nax.set_ylabel(f2_name)\nax.set_title('')\n\n# 1:1 line\nlims = [\n np.min([plt.xlim(), plt.ylim()]), # min of both axes\n np.max([plt.xlim(), plt.ylim()]), # max of both axes\n]\nplt.plot(lims, lims, 'deeppink', alpha=0.75, zorder=1)\nplt.xlim(lims)\nplt.ylim(lims)\n\nprint('Saving plot to: ' + '{plt_name}.png'.format(plt_name=out_file_name))\nfig.savefig('{out_dir}/{plt_name}.png'.format(out_dir=sys.argv[5], plt_name=out_file_name), facecolor='black')",
"'''\nCreated Sep 19 10:04:10 2018\nSignificant updates March 17th 2020\n@author: arthur elmes [email protected]\n\n'''\nimport os, glob, sys, pyproj, csv, statistics\nfrom argparse import ArgumentParser\nfrom osgeo import gdal\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom pyhdf.SD import SD, SDC\nfrom h5py import File\nfrom datetime import datetime\nimport seaborn as sns\n\n\ndef hdf_to_np(hdf_fname, sds):\n #TODO close the dataset, probably using 'with'\n hdf_ds = SD(hdf_fname, SDC.READ)\n dataset_3d = hdf_ds.select(sds)\n data_np = dataset_3d[:,:]\n return data_np\n\n\ndef h5_to_np(h5_fname, sds):\n with File(h5_fname, 'r') as h5_ds:\n data_np = h5_ds['HDFEOS']['GRIDS']['VIIRS_Grid_BRDF']['Data Fields'][sds][()]\n return data_np\n\n\ndef convert_ll_vnp(lat, lon, tile, in_dir, prdct):\n # prdct = prdct\n # Convert the lat/long point of interest to a row/col location\n template_h_list = glob.glob(os.path.join(in_dir, '*.A*{tile}*.h*'.format(tile=tile)))\n try:\n template_h_file = template_h_list[0]\n except IndexError:\n print('Sorry, due to gdal not liking VIIRS h5 files, you need to download an MCD image of the same tile'\n ' and put it in ../input_dir/copy_srs/')\n sys.exit(1)\n template_h_ds = gdal.Open(template_h_file, gdal.GA_ReadOnly)\n template_h_band = gdal.Open(template_h_ds.GetSubDatasets()[0][0], gdal.GA_ReadOnly)\n # Use pyproj to create a geotransform between\n # WGS84 geographic (lat/long; epsg 4326) and\n # the funky crs that modis/viirs use.\n # Note that this modis crs seems to have units\n # in meters from the geographic origin, i.e.\n # lat/long (0, 0), and has 2400 rows/cols per tile.\n # gdal does NOT read the corner coords correctly,\n # but they ARE stored correctly in the hdf metadata. Although slightly\n # difft than reported by gdal...\n\n # Using pyproj to transform coords of interes to meters\n in_proj = pyproj.Proj(init='epsg:4326')\n # out_proj = pyproj.Proj(template_h_band.GetProjection())\n out_proj = pyproj.Proj('+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m +no_defs')\n\n # Current sample location convert from ll to m\n smpl_x, smpl_y = pyproj.transform(in_proj, out_proj, lon, lat)\n\n # FOR VIIRS, use manual\n # h12v04 UL: -6671703.1179999997839332 5559752.5983330002054572 LR: -5559752.5983330002054572 4447802.0786669999361038\n # out_proj = pyproj.Proj('+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m +no_defs')\n\n # Getting bounding coords from meta\n # Perhaps no longer neededm but they're slilghtly difft than gdal geotransofrm\n # NOTE gdal works fine if you call the geotransform\n # on the BAND!!! (sds), not the DS\n meta = template_h_ds.GetMetadata_Dict()\n # FOR MODIS, us ALL CAPS\n y_origin_meta = float(meta['NORTHBOUNDINGCOORDINATE'])\n y_min_meta = float(meta['SOUTHBOUNDINGCOORDINATE'])\n x_max_meta = float(meta['EASTBOUNDINGCOORDINATE'])\n x_origin_meta = float(meta['WESTBOUNDINGCOORDINATE'])\n # n_rows_meta = 1200 # int(meta['DATAROWS'])\n # n_cols_meta = 1200 # int(meta['DATACOLUMNS'])\n pixel_height_meta_m = 926.6254330558330139 #(y_origin_meta - y_min_meta) / n_rows_meta\n pixel_width_meta_m = 926.6254330558330139 #pixel_height_meta_m\n\n # # Make calculations to get row/col value\n # # NOTE that for geotifs, it would also be possible\n # # to simply open with rasterio, then use .index()\n # # to return the row/col. This does not work for hdf\n x_origin_meta_m, y_origin_meta_m = pyproj.transform(in_proj, out_proj, x_origin_meta, y_origin_meta)\n # x_max_meta_m, y_min_meta_m = pyproj.transform(in_proj, out_proj, x_max_meta, y_min_meta)\n\n col_m = int((smpl_x - x_origin_meta_m) / pixel_width_meta_m)\n row_m = int(-1 * (smpl_y - y_origin_meta_m) / pixel_height_meta_m)\n smp_rc = row_m, col_m\n return smp_rc\n\n\ndef convert_ll(lat, lon, tile, in_dir, prdct):\n prdct = prdct\n # Convert the lat/long point of interest to a row/col location\n if 'h' in tile:\n template_h_list = glob.glob(os.path.join(in_dir,\n '{prdct}.A*{tile}*.h*'.format(prdct=prdct,\n tile=tile)))\n else:\n template_h_list = glob.glob(os.path.join(in_dir, '{prdct}*{tile}*.h*'.format(prdct=prdct,\n tile=tile)))\n template_h_file = template_h_list[0]\n template_h_ds = gdal.Open(template_h_file, gdal.GA_ReadOnly)\n template_h_band = gdal.Open(template_h_ds.GetSubDatasets()[0][0],\n gdal.GA_ReadOnly)\n # Use pyproj to create a geotransform betweensds\n # WGS84 geographic (lat/l1200ong; epsg 4326) and\n # the funky crs that modis/viirs use.\n # Note that this modis crs seems to have units\n # in meters from the geographic origin, i.e.\n # lat/long (0, 0), and has 2400 rows/cols per tile.\n # gdal does NOT read the corner coords correctly,\n # but they ARE stored correctly in the hdf metadata. Although slightly\n # difft than reported by gdal, which is odd.\n\n # # Using pyproj to transform coords of interes to meters\n in_proj = pyproj.Proj(init='epsg:4326')\n out_proj = pyproj.Proj(template_h_band.GetProjection())\n\n # # Current sample location convert from ll to m\n smpl_x, smpl_y = pyproj.transform(in_proj, out_proj, lon, lat)\n\n # Getting bounding coords from meta\n # Perhaps no longer neededm but they're slilghtly difft than gdal geotransofrm\n # NOTE gdal works fine if you call the geotransform\n # on the BAND!!! (sds), not the DS\n # meta = template_h_ds.GetMetadata_Dict()\n # FOR MODIS, us ALL CAPS\n # y_origin_meta = float(meta['NORTHBOUNDINGCOORDINATE'])\n # y_min_meta = float(meta['SOUTHBOUNDINGCOORDINATE'])\n # x_max_meta = float(meta['EASTBOUNDINGCOORDINATE'])\n # x_origin_meta = float(meta['WESTBOUNDINGCOORDINATE'])\n # n_rows_meta = int(meta['DATAROWS'])\n # n_cols_meta = int(meta['DATACOLUMNS'])\n # pixel_height_meta_m = float(meta['CHARACTERISTICBINSIZE'])\n # pixel_width_meta_m = float(meta['CHARACTERISTICBINSIZE'])\n\n #TESTING these are conversions of the metadata extents to meters\n # x_origin_meta_m, y_origin_meta_m = pyproj.transform(in_proj, out_proj, x_origin_meta, y_origin_meta)\n # x_max_meta_m, y_min_meta_m= pyproj.transform(in_proj, out_proj, x_max_meta, y_min_meta)\n # pixel_width_meta_m = (x_max_meta_m - x_origin_meta_m) / n_cols_meta\n # pixel_height_meta_m = (y_origin_meta_m - y_min_meta_m) / n_rows_meta\n # col_meta_m = int((smpl_x - x_origin_meta_m) / pixel_width_meta_m)\n # row_meta_m = int(-1 * (smpl_y - y_origin_meta_m) / pixel_height_meta_m)\n # smp_rc_meta = row_meta_m, col_meta_m\n\n # Getting bounding coords etc from gdal geotransform\n n_cols = template_h_band.RasterXSize\n n_rows = template_h_band.RasterYSize\n x_origin, x_res, x_skew, y_origin, y_skew, y_res = template_h_band.GetGeoTransform()\n # Using the skew is in case there is any affine transformation\n # in place in the input raster. Not so for modis tiles, so not really necessary, but complete.\n x_max = x_origin + n_cols * x_res + n_cols * x_skew\n y_min = y_origin + n_rows * y_res + n_rows * y_skew\n\n # # Make calculations to get row/col value\n # # NOTE that for geotifs, it would also be possible\n # # to simply open with rasterio, then use .index()\n # # to return the row/col. This does not work for hdf\n pixel_width_m = (x_max - x_origin) / n_cols\n pixel_height_m = (y_origin - y_min) / n_rows\n col_m = int((smpl_x - x_origin) / pixel_width_m)\n row_m = int( -1 * (smpl_y - y_origin) / pixel_height_m)\n smp_rc = row_m, col_m\n print(smp_rc)\n return smp_rc\n\n\ndef make_prod_list(in_dir, prdct, year, day, tile):\n if 'MCD' in prdct or 'VNP' in prdct or 'VJ1' in prdct:\n h_file_list = glob.glob(os.path.join(in_dir,\n '{prdct}.A{year}{day:03d}*.h*'.format(prdct=prdct,\n day=day, year=year)))\n elif 'LC08' in prdct:\n dt_string = str(year) + '-' + str(day)\n date_complete = datetime.strptime(dt_string, '%Y-%j')\n mm = date_complete.strftime('%m')\n dd = date_complete.strftime('%d')\n h_file_list = glob.glob(os.path.join(in_dir, '{prdct}*{tile}_{year}{month}{day}_*.h*'.format(prdct=prdct,\n tile=tile,\n month=mm,\n day=dd,\n year=year)))\n else:\n print('Product type unknown! Please check that input is MCD, VNP, VJ1 or LC08.')\n sys.exit()\n\n return h_file_list\n\n\ndef extract_pixel_value(in_dir, site, prdct, h_file_day, sds_names, base_dir):\n # Open tifs as gdal ds\n # print('Opening: ' + h_file_day + ' ' + sds_name_wsa_sw)\n if 'VNP' in prdct or 'VJ1' in prdct:\n # print('Found VIIRS product.')\n copy_srs_dir = os.path.join(base_dir, 'copy_srs')\n wsa_band = h5_to_np(h_file_day, sds_names[0])\n bsa_band = h5_to_np(h_file_day, sds_names[1])\n qa_band = h5_to_np(h_file_day, sds_names[2])\n elif 'MCD' in prdct or 'LC08' in prdct:\n # print('Found MODIS product.')\n wsa_band = hdf_to_np(h_file_day, sds_names[0])\n bsa_band = hdf_to_np(h_file_day, sds_names[1])\n qa_band = hdf_to_np(h_file_day, sds_names[2])\n else:\n print('Unknown product! This only works for MCD, VNP, VJ1 or LC8/LC08 hdf or h5 files!')\n sys.exit()\n\n # Mask out nodata values\n wsa_swir_masked = np.ma.masked_array(wsa_band, wsa_band == 32767)\n wsa_swir_masked_qa = np.ma.masked_array(wsa_swir_masked, qa_band > 0)\n bsa_swir_masked = np.ma.masked_array(bsa_band, bsa_band == 32767)\n bsa_swir_masked_qa = np.ma.masked_array(bsa_swir_masked, qa_band > 0)\n\n #TODO is the plotting in this script appropriately ignoring values masked here?\n\n # Extract pixel value from product by converting lat/lon to row/col\n if 'VNP' in prdct or 'VJ1' in prdct:\n smp_rc = convert_ll_vnp(site[1][0], site[1][1], site[1][2], copy_srs_dir, prdct)\n elif 'MCD' in prdct:\n smp_rc = convert_ll(site[1][0], site[1][1], site[1][2], in_dir, prdct)\n elif 'LC08' in prdct:\n smp_rc = convert_ll(site[1][0], site[1][1], site[1][2], in_dir, prdct)\n else:\n print('Unknown product! This only works for MCD, VNP/VJ1, or LC8/LC08 hdf or h5 files!')\n sys.exit()\n\n # Take just the sampled location's value, and scale to float\n wsa_swir_subset = wsa_swir_masked_qa[smp_rc]\n wsa_swir_subset_flt = np.multiply(wsa_swir_subset, 0.001)\n bsa_swir_subset = bsa_swir_masked_qa[smp_rc]\n bsa_swir_subset_flt = np.multiply(bsa_swir_subset, 0.001)\n \n # Return a tuple of numpy arrays for wsa and bsa (and probably also qa?)\n print(wsa_swir_subset_flt, bsa_swir_subset_flt)\n print(wsa_swir_subset, bsa_swir_subset)\n return wsa_swir_subset_flt, bsa_swir_subset_flt\n\n\ndef draw_plot(year, year_smpl_cmb_df, fig_dir, prdct, sites_dict):\n sns.set_style('darkgrid')\n\n for site in sites_dict.keys():\n for sds in ['wsa', 'bsa']:\n col_name = str(site) + '_' + str(sds)\n\n # Create a seaborn scatterplot (or replot for now, small differences)\n sct = sns.regplot(x='doy', y=col_name, data=year_smpl_cmb_df, marker='o', label='sw ' + str(sds),\n fit_reg=False, scatter_kws={'color':'darkblue', 'alpha':0.3,'s':20})\n sct.set_ylim(0, 1.0)\n sct.set_xlim(1, 366)\n sct.legend(loc='best')\n\n # Access the figure, add title\n plt_name = str(year + ' ' + prdct + ' SW ' + str(sds))\n plt.title(plt_name)\n #plt.show()\n\n plt_name = plt_name.replace(' ', '_') + '_' + str(site)\n # Save each plot to figs dir\n print('Saving plot to: ' + '{fig_dir}/{plt_name}.png'.format(fig_dir=fig_dir, plt_name=plt_name))\n plt.savefig('{fig_dir}/{plt_name}.png'.format(fig_dir=fig_dir, plt_name=plt_name))\n plt.clf()\n\n\ndef check_leap(year):\n leap_status = False\n year = int(year)\n if (year % 4) == 0:\n if (year % 100) == 0:\n if (year % 400) == 0:\n leap_status = True\n else:\n leap_status = False\n else:\n leap_status = True\n else:\n leap_status = False\n\n return leap_status\n\n\ndef main():\n # CLI args\n parser = ArgumentParser()\n parser.add_argument('-y', '--years', dest='years', help='Years to extract data for.', metavar='YEARS')\n #TODO why include a required tile option if the tile has to be in the csv? change this.\n parser.add_argument('-d', '--input-dir', dest='base_dir',\n help='Base directory containing sample and dir of imagery data called the product name'\n ', e.g. ../MCD43A3/',\n metavar='IN_DIR')\n parser.add_argument('-s', '--sites', dest='sites_csv_fname', help='CSV with no headings containing smpls. '+\\\n 'must look like: id,lat,long,tile_it_is_in',\n metavar='SITES')\n parser.add_argument('-p', '--product', dest='prdct', help='Imagery product to be input, e.g. LC08, MCD43A3.',\n metavar='PRODUCT')\n args = parser.parse_args()\n\n # Note: I have chosen to call the landsat product LC08, rather than LC8, due to the file naming convention\n # of the inputs specific to the albedo code. LC8 is also used in different Landsat data products, annoyingly.\n prdct = args.prdct\n base_dir = args.base_dir\n years = [args.years]\n sites_csv_input = os.path.join(base_dir, args.sites_csv_fname)\n sites_dict = {}\n with open(sites_csv_input, mode='r') as sites_csv:\n reader = csv.reader(sites_csv)\n for row in reader:\n key = row[0]\n sites_dict[key] = row[1:]\n\n # TODO this 'copy_srs_dir' location is here because currently VNP43 has broken spatial reference\n # TODO information. Check V002 and remove this if it has been fixed, as this is ludicrously clunky.\n\n sds_name_wsa_sw = 'Albedo_WSA_shortwave'\n sds_name_bsa_sw = 'Albedo_BSA_shortwave'\n #TODO: the LC08 hdfs have a differently named qa sds. yaay.\n sds_name_qa_sw = 'BRDF_Albedo_Band_Mandatory_Quality_shortwave'\n #sds_name_qa_sw = 'Albedo_Band_Quality_shortwave'\n sds_names = [sds_name_wsa_sw, sds_name_bsa_sw, sds_name_qa_sw]\n\n # Loop through the years provided, and extract the pixel values at the provided coordinates. Outputs CSV and figs.\n for year in years:\n doy_list = []\n if check_leap(year):\n for i in range(1, 367):\n doy_list.append(i)\n else:\n for i in range(1, 366):\n doy_list.append(i)\n\n # Make a blank pandas dataframe that results will be appended to,\n # and start it off with all possible doys (366)\n year_smpl_cmb_df = pd.DataFrame(doy_list, columns=['doy'])\n # Loop through each site and extract the pixel values\n for site in sites_dict.items():\n tile = site[1][2]\n in_dir = os.path.join(base_dir, prdct, year, tile)\n print(in_dir)\n fig_dir = os.path.join(base_dir, 'figs')\n if not os.path.isdir(fig_dir):\n os.makedirs(fig_dir)\n print('Made new folder for figs: ' + str(fig_dir))\n else:\n pass\n try:\n os.chdir(in_dir)\n except FileNotFoundError:\n print('Sorry, data directory must be organized like: ../MCD43A3/2016/h12v04/ e.g.')\n sys.exit(1)\n print('Processing site: ' + str(site))\n\n # Create empty arrays for mean, sd\n wsa_swir_mean = []\n wsa_swir_sd = []\n bsa_swir_mean = []\n bsa_swir_sd = []\n for day in doy_list:\n # Open the shortwave white sky albedo band.\n # The list approach is because of the processing date part of the file\n # name, which necessitates the wildcard -- this was just the easiest way.\n h_file_list = make_prod_list(in_dir, prdct, year, day, tile)\n file_name = '{in_dir}/{prdct}.A{year}{day:03d}*.h*'.format(in_dir=in_dir, prdct=prdct, day=day,\n year=year)\n # See if there is a raster for the date, if not use a fill value for the graph\n if len(h_file_list) == 0: # or len(bsa_tif_list) == 0 or len(qa_tif_list) == 0:\n print('File not found: ' + file_name)\n # wsa_swir_subset_flt = float('nan')\n # bsa_swir_subset_flt = float('nan')\n #TODO change the below to be nulls, not zeros.\n pixel_values = np.nan, np.nan\n elif len(h_file_list) > 1:\n print('Multiple matching files found for same date! Please remove one.')\n sys.exit()\n else:\n # print('Found file: ' + file_name)\n h_file_day = h_file_list[0]\n # Extract pixel values and append to dataframe\n # Note the base_dir argument should go away when the correctly georeferenced VNP43 are available,\n # because I can likely eliminate the vnp-specific value extractor function\n try:\n pixel_values = extract_pixel_value(in_dir, site, prdct, h_file_day, sds_names, base_dir)\n except:\n print('Warning! Pixel out of tile boundaries!')\n pixel_values = np.nan, np.nan\n # Add each point to a temporary list\n wsa_smpl_results = []\n bsa_smpl_results = []\n wsa_smpl_results.append(pixel_values[0])\n bsa_smpl_results.append(pixel_values[1])\n #TODO this is currently silly, but ultimately will be replaced by an averaging\n #TODO function for points of the same sample area\n try:\n wsa_tmp_mean = statistics.mean(wsa_smpl_results)\n wsa_swir_mean.append(wsa_tmp_mean)\n bsa_tmp_mean = statistics.mean(bsa_smpl_results)\n bsa_swir_mean.append(bsa_tmp_mean)\n except:\n wsa_swir_mean.append(np.nan)\n bsa_swir_mean.append(np.nan)\n\n wsa_smpl_results_df = pd.DataFrame(wsa_swir_mean)\n bsa_smpl_results_df = pd.DataFrame(bsa_swir_mean)\n cmb_smpl_results_df = pd.concat([wsa_smpl_results_df, bsa_smpl_results_df], axis=1, ignore_index=True)\n cmb_smpl_results_df.set_axis([str(site[0]) +'_wsa', str(site[0]) + '_bsa'], axis=1, inplace=True)\n\n # Append the site's results to the existing yearly dataframe, initiated above\n year_smpl_cmb_df = pd.concat([year_smpl_cmb_df, cmb_smpl_results_df], axis=1)\n\n # Do plotting and save output PER YEAR (individual csv per year)\n draw_plot(year, year_smpl_cmb_df, fig_dir, prdct, sites_dict)\n\n # Export data to csv\n os.chdir(fig_dir)\n output_name = str(sites_csv_input[:-4] + '_extracted_values')\n csv_name = str(output_name + '_' + prdct + '.csv')\n print('writing csv: ' + csv_name)\n year_smpl_cmb_df.to_csv(csv_name, index=False)\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"matplotlib.colors.LogNorm",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.subplots",
"pandas.DataFrame",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlim"
],
[
"pandas.concat",
"matplotlib.pyplot.title",
"numpy.multiply",
"pandas.DataFrame",
"matplotlib.pyplot.clf",
"numpy.ma.masked_array"
]
] |
behjava/automatic_data_reduction
|
[
"dd1eb78b22db7c27ccd26d496babc8ffe12d41c0"
] |
[
"modules/master_maker.py"
] |
[
"import numpy as np\n\n####### Master making function ###########################\ndef MASTER(cube, method):\n\tif method=='sum':\n\t\tout=np.sum(cube, axis=2)\n\tif method=='mean':\n\t\tout=np.mean(cube, axis=2)\n\tif method=='median':\n\t\tout=np.median(cube, axis=2)\n\treturn out\n##########################################################\n"
] |
[
[
"numpy.median",
"numpy.mean",
"numpy.sum"
]
] |
chuckie82/ami
|
[
"7adb72c709afe4c1af53ef7f0d2b0e3639c63bf3"
] |
[
"ami/graph_nodes.py"
] |
[
"import abc\nimport operator\nimport numpy as np\nfrom networkfox import operation\n\n\nclass Transformation(abc.ABC):\n\n def __init__(self, **kwargs):\n \"\"\"\n Keyword Arguments:\n name (str): Name of node\n inputs (list): List of inputs\n outputs (list): List of outputs\n func (function): Function node will call\n \"\"\"\n\n self.name = kwargs['name']\n\n inputs = kwargs['inputs']\n if type(inputs) is dict:\n self.inputs = list(inputs.values())\n else:\n self.inputs = inputs\n\n outputs = kwargs['outputs']\n if type(outputs) is dict:\n self.outputs = list(outputs.values())\n else:\n self.outputs = outputs\n\n self.func = kwargs['func']\n self.parent = kwargs.get('parent', None)\n self.color = kwargs.get('color', \"\")\n self.begin_run_func = kwargs.get('begin_run', None)\n self.end_run_func = kwargs.get('end_run', None)\n self.begin_step_func = kwargs.get('begin_step', None)\n self.end_step_func = kwargs.get('end_step', None)\n self.is_global_operation = False\n\n def __hash__(self):\n return hash(self.name)\n\n def __eq__(self, other):\n \"\"\"\n Two nodes are considered equal if their name is equal.\n\n Args:\n other (Transformation): Node to compare against.\n \"\"\"\n return bool(self.name is not None and\n self.name == getattr(other, 'name', None))\n\n def __repr__(self):\n return u\"%s(name='%s', color='%s', inputs=%s, outputs=%s)\" % \\\n (self.__class__.__name__, self.name, self.color, self.inputs, self.outputs)\n\n def to_operation(self):\n \"\"\"\n Return NetworkFoX operation node.\n \"\"\"\n return operation(name=self.name, needs=self.inputs, provides=self.outputs, color=self.color,\n metadata={'parent': self.parent})(self.func)\n\n def begin_run(self, color=\"\"):\n if color == self.color and callable(self.begin_run_func):\n return self.begin_run_func()\n\n def end_run(self, color=\"\"):\n if color == self.color and callable(self.end_run_func):\n return self.end_run_func()\n\n def begin_step(self, step, color=\"\"):\n if color == self.color and callable(self.begin_step_func):\n return self.begin_step_func(step)\n\n def end_step(self, step, color=\"\"):\n if color == self.color and callable(self.end_step_func):\n return self.end_step_func(step)\n\n\nclass Map(Transformation):\n\n def __init__(self, **kwargs):\n \"\"\"\n Keyword Arguments:\n name (str): Name of node\n inputs (list): List of inputs\n outputs (list): List of outputs\n func (function): Function node will call\n \"\"\"\n super().__init__(**kwargs)\n\n\nclass StatefulTransformation(Transformation):\n\n def __init__(self, **kwargs):\n \"\"\"\n Keyword Arguments:\n name (str): Name of node\n inputs (list): List of inputs\n outputs (list): List of outputs\n reduction (function): Reduction function\n \"\"\"\n\n reduction = kwargs.pop('reduction', None)\n\n kwargs.setdefault('func', None)\n super().__init__(**kwargs)\n\n if reduction:\n assert hasattr(reduction, '__call__'), 'reduction is not callable'\n self.reduction = reduction\n\n @abc.abstractmethod\n def __call__(self, *args, **kwargs):\n return\n\n @abc.abstractmethod\n def reset(self):\n \"\"\"\n Reset nodes state.\n \"\"\"\n return\n\n def heartbeat_finished(self):\n \"\"\"\n Execute at the end of a heartbeat.\n \"\"\"\n return\n\n def to_operation(self):\n return operation(name=self.name, needs=self.inputs, provides=self.outputs,\n color=self.color, metadata={'parent': self.parent})(self)\n\n\nclass GlobalTransformation(StatefulTransformation):\n\n def __init__(self, **kwargs):\n \"\"\"\n Keyword Arguments:\n name (str): Name of node\n inputs (list): List of inputs\n outputs (list): List of outputs\n reduction (function): Reduction function\n is_expanded (bool): Indicates this node's input comes another part\n of the expanded operation\n num_contributors (int): the number of contributors providing input\n to this part of the global operation\n \"\"\"\n is_expanded = kwargs.pop('is_expanded', False)\n num_contributors = kwargs.pop('num_contributors', None)\n super().__init__(**kwargs)\n self.is_global_operation = True\n self.is_expanded = is_expanded\n self.num_contributors = num_contributors\n\n def on_expand(self):\n \"\"\"\n Called when expanding a global operation to get an extra kwargs that\n should be passed to the expanded nodes when they are constructed.\n\n This is intended to be overrided by subclasses if they need this!\n\n Returns:\n Dictionary of keyword arguments to pass when constructing the\n globally expanded version of this operation\n \"\"\"\n return {\"parent\": self.parent}\n\n\nclass ReduceByKey(GlobalTransformation):\n\n def __init__(self, **kwargs):\n kwargs.setdefault('reduction', operator.add)\n super().__init__(**kwargs)\n self.res = {}\n\n def __call__(self, *args, **kwargs):\n if len(args) == 2:\n # worker\n k, v = args\n if k in self.res:\n self.res[k] = self.reduction(self.res[k], v)\n else:\n self.res[k] = v\n else:\n # localCollector, globalCollector\n for r in args:\n for k, v in r.items():\n if k in self.res:\n self.res[k] = self.reduction(self.res[k], v)\n else:\n self.res[k] = v\n return self.res\n\n def reset(self):\n self.res = {}\n\n def heartbeat_finished(self):\n if self.color != 'globalCollector':\n self.reset()\n\n\nclass Accumulator(GlobalTransformation):\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.res_factory = kwargs.pop('res_factory', lambda: 0)\n assert hasattr(self.res_factory, '__call__'), 'res_factory is not callable'\n self.res = self.res_factory()\n\n def __call__(self, *args, **kwargs):\n self.res = self.reduction(self.res, *args)\n return self.res\n\n def reset(self):\n self.res = self.res_factory()\n\n def heartbeat_finished(self):\n if self.color != 'globalCollector':\n self.reset()\n\n def on_expand(self):\n return {'parent': self.parent, 'res_factory': self.res_factory}\n\n\nclass PickN(GlobalTransformation):\n\n def __init__(self, **kwargs):\n N = kwargs.pop('N', 1)\n super().__init__(**kwargs)\n self.N = N\n self.idx = 0\n self.res = [None]*self.N\n self.clear = False\n\n def __call__(self, *args, **kwargs):\n if self.clear:\n self.res = [None]*self.N\n self.clear = False\n\n if not args and kwargs:\n args = list(kwargs.values())\n if len(args) > 1:\n args = [args]\n elif self.is_expanded and len(args) == 1 and type(args[0]) is list and self.N > 1:\n args = args[0]\n\n for arg in args:\n self.res[self.idx] = arg\n self.idx = (self.idx + 1) % self.N\n\n if not any(x is None for x in self.res):\n self.clear = True\n if self.N > 1:\n return self.res\n elif self.N == 1:\n return self.res[0]\n\n def reset(self):\n self.res = [None]*self.N\n\n\nclass RollingBuffer(GlobalTransformation):\n\n def __init__(self, **kwargs):\n N = kwargs.pop('N', 1)\n use_numpy = kwargs.pop('use_numpy', False)\n unique = kwargs.pop('unique', False)\n super().__init__(**kwargs)\n self.N = N\n self.use_numpy = use_numpy\n self.unique = unique\n self.idx = 0\n self.count = 0\n self.res = None if use_numpy else []\n\n def __call__(self, *args, **kwargs):\n if len(args) == 1:\n dims = 0\n args = args[0]\n elif args:\n dims = len(args)\n elif kwargs:\n args = [kwargs.get(arg, np.nan) for arg in self.inputs]\n dims = len(args)\n if len(args) == 1:\n dims = 0\n args = args[0]\n\n if self.use_numpy:\n if self.is_expanded:\n dtype = args.dtype\n if len(args) > self.N:\n nelem = self.N\n args = args[..., -self.N:]\n else:\n nelem = len(args)\n else:\n dtype = type(args)\n nelem = 1\n if self.res is None:\n self.res = np.zeros(self.N, dtype=dtype)\n self.idx += nelem\n self.res = np.roll(self.res, -nelem)\n self.res[..., -nelem:] = [args] if dims else args\n else:\n if self.is_expanded:\n self.res.extend(args)\n self.idx = min(self.idx + len(args), self.N)\n else:\n if not self.unique:\n self.res.append(args)\n self.idx = min(self.idx + 1, self.N)\n elif self.unique:\n if len(self.res) == 0:\n self.res.append(args)\n self.idx = min(self.idx + 1, self.N)\n elif self.res[self.idx-1] != args:\n self.res.append(args)\n self.idx = min(self.idx + 1, self.N)\n self.res = self.res[-self.idx:]\n\n return self.res[-self.idx:]\n\n def on_expand(self):\n return {'parent': self.parent, 'use_numpy': self.use_numpy, 'unique': self.unique}\n\n def reset(self):\n self.idx = 0\n"
] |
[
[
"numpy.zeros",
"numpy.roll"
]
] |
chohner/sound_field_analysis-py
|
[
"9d3686ae77e96654450fd454de24fe845c363ac8"
] |
[
"test/time_sph_harm.py"
] |
[
"\"\"\"This test the equality and execution speed of different implementations to\ngenerate spherical harmonics.\n\nExemplary execution:\n======================\n_TIMEIT_REPEAT = 5\n_TIMEIT_NUMBER = 5000\n_N_MAX = 8\n_KIND = real\n======================\nnode \"C18TTLT\"\n======================\n\nsph_harm_1\ntime: 0.88s\n\nspaudiopy.sh_matrix\ntime: 3.98s\ntime factor: 4.54 ... WORSE\nresult sum: 0.7027539767877192 ... MISMATCH\nresult max: 0.12727637177922763 ... MISMATCH\n\npyshtools\ntime: 0.52s\ntime factor: 0.60 ... BETTER\nresult sum: 0.702753976787717 ... MISMATCH\nresult max: 0.9629001108439836 ... MISMATCH\n\nsph_harm_2\ntime: 0.63s\ntime factor: 0.72 ... BETTER\nresult sum: 0.0 ... PERFECT\nresult max: 0.0 ... PERFECT\n\nsph_harm_3\ntime: 0.57s\ntime factor: 0.65 ... BETTER\nresult sum: 0.0 ... PERFECT\nresult max: 0.0 ... PERFECT\n\nsph_harm_4\ntime: 0.55s\ntime factor: 0.62 ... BETTER\nresult sum: 0.0 ... PERFECT\nresult max: 0.0 ... PERFECT\n\nsph_harm_5\ntime: 0.56s\ntime factor: 0.64 ... BETTER\nresult sum: 0.0 ... PERFECT\nresult max: 0.0 ... PERFECT\n\nsph_harm COMPLEX\ntime: 0.40s\n\"\"\"\n\nimport platform\n\nimport numpy as _np\nfrom scipy import special as scy\n\nfrom sound_field_analysis.sph import mnArrays\nfrom sound_field_analysis.utils import time_it\n\n\ndef sh_matrix(N, azi, colat, SH_type=\"complex\", weights=None):\n \"\"\"\n From https://github.com/chris-hld/spaudiopy/blob/master/spaudiopy/sph.py\n\n Notes\n -----\n Imports are not done inside the function in order to not compromise\n execution time (this has a minor impact). Therefore, the `scyspecial`\n and `np` calls have been adapted to the convention used in the other\n functions.\n \"\"\"\n azi = _np.asarray(azi)\n colat = _np.asarray(colat)\n if azi.ndim == 0:\n Q = 1\n else:\n Q = len(azi)\n if weights is None:\n weights = _np.ones(Q)\n if SH_type == \"complex\":\n Ymn = _np.zeros([Q, (N + 1) ** 2], dtype=_np.complex_)\n elif SH_type == \"real\":\n Ymn = _np.zeros([Q, (N + 1) ** 2], dtype=_np.float_)\n else:\n raise ValueError(\"SH_type unknown.\")\n\n idx = 0\n for n in range(N + 1):\n for m in range(-n, n + 1):\n if SH_type == \"complex\":\n Ymn[:, idx] = weights * scy.sph_harm(m, n, azi, colat)\n elif SH_type == \"real\":\n if m == 0:\n Ymn[:, idx] = weights * _np.real(scy.sph_harm(0, n, azi, colat))\n if m < 0:\n Ymn[:, idx] = (\n weights\n * _np.sqrt(2)\n * (-1) ** abs(m)\n * _np.imag(scy.sph_harm(abs(m), n, azi, colat))\n )\n if m > 0:\n Ymn[:, idx] = (\n weights\n * _np.sqrt(2)\n * (-1) ** abs(m)\n * _np.real(scy.sph_harm(abs(m), n, azi, colat))\n )\n\n idx += 1\n return Ymn\n\n\ndef sph_harm_all_func(func, _N_MAX, az, co, kind=\"complex\"):\n m, n = mnArrays(_N_MAX)\n mA, azA = _np.meshgrid(m, az)\n nA, coA = _np.meshgrid(n, co)\n return func(mA, nA, azA, coA, kind=kind)\n\n\ndef sph_harm_1(m, n, az, co, kind=\"complex\"):\n Y = scy.sph_harm(m, n, az, co)\n if kind == \"complex\":\n return Y\n else: # kind == 'real'\n Y[_np.where(m > 0)] = (\n _np.float_power(-1.0, m)[_np.where(m > 0)]\n * _np.sqrt(2)\n * _np.real(Y[_np.where(m > 0)])\n )\n Y[_np.where(m == 0)] = _np.real(Y[_np.where(m == 0)])\n Y[_np.where(m < 0)] = _np.sqrt(2) * _np.imag(Y[_np.where(m < 0)])\n return _np.real(Y)\n\n\ndef sph_harm_2(m, n, az, co, kind=\"complex\"):\n Y = scy.sph_harm(m, n, az, co)\n if kind == \"complex\":\n return Y\n else: # kind == 'real'\n Y[_np.where(m > 0)] = (\n _np.float_power(-1.0, m)[_np.where(m > 0)]\n * _np.sqrt(2)\n * _np.real(Y[_np.where(m > 0)])\n )\n Y[_np.where(m < 0)] = _np.sqrt(2) * _np.imag(Y[_np.where(m < 0)])\n return _np.real(Y)\n\n\ndef sph_harm_3(m, n, az, co, kind=\"complex\"):\n Y = scy.sph_harm(m, n, az, co)\n if kind == \"complex\":\n return Y\n else: # kind == 'real'\n Y[m > 0] = _np.float_power(-1.0, m)[m > 0] * _np.sqrt(2) * _np.real(Y[m > 0])\n Y[m < 0] = _np.sqrt(2) * _np.imag(Y[m < 0])\n return _np.real(Y)\n\n\ndef sph_harm_4(m, n, az, co, kind=\"complex\"):\n Y = scy.sph_harm(m, n, az, co)\n if kind == \"complex\":\n return Y\n else: # kind == 'real'\n mg0 = m > 0\n ml0 = m < 0\n Y[mg0] = _np.float_power(-1.0, m)[mg0] * _np.sqrt(2) * _np.real(Y[mg0])\n Y[ml0] = _np.sqrt(2) * _np.imag(Y[ml0])\n return _np.real(Y)\n\n\ndef sph_harm_5(m, n, az, co, kind=\"complex\"):\n Y = scy.sph_harm(m, n, az, co)\n if kind == \"complex\":\n return Y\n else: # kind == 'real'\n mg0 = m > 0\n me0 = m == 0\n ml0 = m < 0\n Y_real = _np.zeros(Y.shape, dtype=_np.float_)\n Y_real[mg0] = _np.float_power(-1.0, m)[mg0] * _np.sqrt(2) * _np.real(Y[mg0])\n Y_real[me0] = _np.real(Y[me0])\n Y_real[ml0] = _np.sqrt(2) * _np.imag(Y[ml0])\n return Y_real\n\n\n# set parameters\n_TIMEIT_REPEAT = 5\n_TIMEIT_NUMBER = 5000\n(_N_MAX, _AZ, _CO, _KIND) = (8, 0.1, 0.1, \"real\")\n\nprint(\"======================\")\nprint(f\"_TIMEIT_REPEAT = {_TIMEIT_REPEAT}\")\nprint(f\"_TIMEIT_NUMBER = {_TIMEIT_NUMBER}\")\nprint(f\"_N_MAX = {_N_MAX}\")\nprint(f\"_KIND = {_KIND}\")\nprint(\"======================\")\nprint(f'node \"{platform.node()}\"')\nprint(\"======================\\n\")\n\nref = time_it(\n description=\"sph_harm_1\",\n stmt=\"sph_harm_all_func(sph_harm_1, _N_MAX, _AZ, _CO, kind=_KIND)\",\n setup=\"\",\n _globals=locals(),\n repeat=_TIMEIT_REPEAT,\n number=_TIMEIT_NUMBER,\n)\n\ntime_it(\n description=\"spaudiopy.sh_matrix\",\n stmt=\"sh_matrix(N=_N_MAX, azi=_AZ, colat=_CO, SH_type=_KIND, weights=None)\",\n setup=\"\",\n _globals=locals(),\n repeat=_TIMEIT_REPEAT,\n number=_TIMEIT_NUMBER,\n reference=ref,\n) # slowest, not sure if mismatch is due to a bug or a different convention\n\ntime_it(\n description=\"pyshtools\",\n stmt=\"\"\"\\\nresult = spharm(lmax=_N_MAX, theta=_CO, phi=_AZ, kind=_KIND, degrees=False,\n normalization='ortho', csphase=1, packed=False)\nresult = SHCilmToVector(result)[_np.newaxis, :]\"\"\",\n setup=\"\"\"\\\nfrom pyshtools.expand import spharm\nfrom pyshtools.shio import SHCilmToVector\"\"\",\n _globals=locals(),\n repeat=_TIMEIT_REPEAT,\n number=_TIMEIT_NUMBER,\n reference=ref,\n) # fastest, but does not result in similar coefficient order yet\n\"\"\"\nNotes\n-----\npyshtools has a lot of additional dependencies that are not required for the\npurpose of generating the spherical harmonic basis functions. The following\ndependencies can be added to the environment.yml for a minimal setup.\n\nchannels:\n - defaults\n - conda-forge\ndependencies:\n - pyshtools [--no-deps] # to not get tons of additional dependencies\n - openblas # required dependency for pyshtools\n\"\"\"\n\ntime_it(\n description=\"sph_harm_2\",\n stmt=\"sph_harm_all_func(sph_harm_2, _N_MAX, _AZ, _CO, kind=_KIND)\",\n setup=\"\",\n _globals=locals(),\n repeat=_TIMEIT_REPEAT,\n number=_TIMEIT_NUMBER,\n reference=ref,\n)\ntime_it(\n description=\"sph_harm_3\",\n stmt=\"sph_harm_all_func(sph_harm_3, _N_MAX, _AZ, _CO, kind=_KIND)\",\n setup=\"\",\n _globals=locals(),\n repeat=_TIMEIT_REPEAT,\n number=_TIMEIT_NUMBER,\n reference=ref,\n)\ntime_it(\n description=\"sph_harm_4\",\n stmt=\"sph_harm_all_func(sph_harm_4, _N_MAX, _AZ, _CO, kind=_KIND)\",\n setup=\"\",\n _globals=locals(),\n repeat=_TIMEIT_REPEAT,\n number=_TIMEIT_NUMBER,\n reference=ref,\n) # fastest (apart from pyshtools(\ntime_it(\n description=\"sph_harm_5\",\n stmt=\"sph_harm_all_func(sph_harm_5, _N_MAX, _AZ, _CO, kind=_KIND)\",\n setup=\"\",\n _globals=locals(),\n repeat=_TIMEIT_REPEAT,\n number=_TIMEIT_NUMBER,\n reference=ref,\n)\ntime_it(\n description=\"sph_harm COMPLEX\",\n stmt=\"sph_harm_all_func(sph_harm_1, _N_MAX, _AZ, _CO, kind='complex')\",\n setup=\"\",\n _globals=locals(),\n repeat=_TIMEIT_REPEAT,\n number=_TIMEIT_NUMBER,\n) # for timing reference (mismatch in case of 'real' kind is expected)\n"
] |
[
[
"numpy.imag",
"numpy.sqrt",
"numpy.float_power",
"numpy.asarray",
"scipy.special.sph_harm",
"numpy.ones",
"numpy.real",
"numpy.meshgrid",
"numpy.zeros",
"numpy.where"
]
] |
guoshzhao/antares
|
[
"30a6338dd6ce4100922cf26ec515e615b449f76a",
"30a6338dd6ce4100922cf26ec515e615b449f76a"
] |
[
"frameworks/tensorflow/perf_tests/transpose.py",
"frameworks/pytorch/examples/3_multi_outputs.py"
] |
[
"#!/usr/bin/env python3\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nimport tensorflow as tf\nfrom tensorflow.contrib import antares\n\nif tf.version.VERSION.startswith('2.'):\n tf = tf.compat.v1\n tf.disable_eager_execution()\n\nfrom _common import *\n\nx = create_variable([64, 224, 224, 3], dtype=tf.float32)\n\ncompare_ops(\n tf.transpose(x, [0, 3, 1, 2]),\n antares.make_op('output0[N, C, H, W] = input0[N, H, W, C]', [x]),\n)\n\n",
"#!/usr/bin/env python3\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nimport torch\nfrom torch.contrib.antares.custom_op import CustomOp\n\ndevice = torch.device(\"cuda\")\ndtype = torch.float32\n\nkwargs = {'dtype': dtype,\n 'device': device,\n 'requires_grad': False}\n\ninput0 = torch.ones(1024 * 512, **kwargs)\ninput1 = torch.ones(1024 * 512, **kwargs)\n\ncustom_op = CustomOp(ir='output0[N] = input0[N] + input1[N]; output1[N] = input0[N].call(`exp`); output2[N] = input1[N] + output1[N];', extra_outputs=['output0', 'output1', 'output2'], feed_dict={'input0': input0, 'input1': input1}).to(device, dtype).tune(step=100, use_cache=True, timeout=600).emit()\n\nresult = custom_op()\nprint('The result of tensor `%s, %s` is:\\n%s' % (result[0].id, result[1].id, result))\n"
] |
[
[
"tensorflow.version.VERSION.startswith",
"tensorflow.disable_eager_execution",
"tensorflow.transpose",
"tensorflow.contrib.antares.make_op"
],
[
"torch.device",
"torch.contrib.antares.custom_op.CustomOp",
"torch.ones"
]
] |
MBravoS/splotch
|
[
"6b7f5d368f1d1457e6fa3ea6b83596e325fb4383"
] |
[
"src/splotch/plots_2d.py"
] |
[
"########################################################################\n############## Definition of all wrappers for 2D plotting ##############\n########################################################################\n\n####################################\n# Level contours\n####################################\ndef contour(z,x=None,y=None,filled=None,xlim=None,ylim=None,xinvert=False,yinvert=False,xlog=False,ylog=False,title=None,xlabel=None,\n ylabel=None,lab_loc=0,ax=None,grid=None,plot_kw={},**kwargs):\n \n \"\"\"Level contour plotting function.\n \n This is a wrapper for pyplot.contour() and pyplot.contourf().\n \n Parameters\n ----------\n z : array-like\n The height values to draw the contours.\n x : array-like, optional\n Position of data points in the x axis.\n y : array-like, optional\n Position of data points in the y axis.\n filled: boolean, optional\n If True, draws filled contours. If not given defaults to the value defined in splotch.Params.\n xlim : tuple-like, optional\n Defines the limits of the x-axis, it must contain two elements (lower and higer limits).\n ylim : tuple-like, optional\n Defines the limits of the y-axis, it must contain two elements (lower and higer limits).\n xinvert : bool, optional\n If True, inverts the x-axis.\n yinvert : bool, optional\n If True, inverts the y-axis.\n xlog : bool, optional\n If True, the scale of the x-axis is logarithmic. If not given defaults to the value defined in splotch.Params.\n ylog : bool, optional\n If True, the scale of the x-axis is logarithmic. If not given defaults to the value defined in splotch.Params.\n title : str, optional\n Sets the title of the plot\n xlabel : str, optional\n Sets the label of the x-axis.\n ylabel : str, optional\n Sets the label of the y-axis.\n lab_loc : int, optional\n Defines the position of the legend\n ax : pyplot.Axes, optional\n Use the given axes to make the plot, defaults to the current axes.\n grid : boolean, optional\n If not given defaults to the value defined in splotch.Params.\n output : boolean, optional\n If True, returns the edges and values of the underlying histogram plus the levels of the contours.\n plot_kw : dict, optional\n Passes the given dictionary as a kwarg to the plotting function. Valid kwargs are QuadContourSet properties.\n **kwargs: QuadContourSet properties, optional\n kwargs are used to specify matplotlib specific properties such as cmap, linewidths, hatches, etc.\n The list of available properties can be found here: \n https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.contour.html\n \n Returns\n -------\n bin_edges_x : array\n The bin edges for the x axis.\n bin_edges_y : array\n The bin edges for the y axis.\n n : array\n The values of the underlying histogram.\n l : array\n The levels for the contours.\n \"\"\"\n \n from numpy import shape, linspace\n from matplotlib.pyplot import contour,contourf, legend\n from .base_func import axes_handler,dict_splicer,plot_finalizer\n \n if ax is not None:\n old_axes=axes_handler(ax)\n if filled is None:\n from .defaults import Params\n filled=Params.cont_filled\n if x is None:\n x=linspace(0,1,z.shape[0])\n if y is None:\n y=linspace(0,1,z.shape[1])\n \n # Combine the `explicit` plot_kw dictionary with the `implicit` **kwargs dictionary\n #plot_par={**plot_kw, **kwargs} # For Python > 3.5\n plot_par=plot_kw.copy()\n plot_par.update(kwargs)\n \n # Create 'L' number of plot kwarg dictionaries to parse into each plot call\n \n plotf={False:contour,True:contourf}\n plotf[filled](x,y,z,**plot_par)\n \n plot_finalizer(xlog,ylog,xlim,ylim,title,xlabel,ylabel,xinvert,yinvert,grid)\n if ax is not None:\n old_axes=axes_handler(old_axes)\n\n####################################\n# Contours from density histograms\n####################################\ndef contourp(x,y,percent=None,filled=None,bin_type=None,bins=None,smooth=0.0,max_spacing=True,xlim=None,ylim=None,xinvert=False,yinvert=False,\n xlog=False,ylog=False,title=None,plabel=None,xlabel=None,ylabel=None,lab_loc=0,ax=None,grid=None,output=None,plot_kw={},**kwargs):\n \n \"\"\"Contour function, encircling the highest density regions that contain the given percentages of the sample.\n \n Parameters\n ----------\n x : array-like\n Position of data points in the x axis.\n y : array-like\n Position of data points in the y axis.\n percent : float or array-like, optional.\n The percentages of the sample that the contours encircle.\n bin_type : {'number','width','edges','equal'}, optional\n Defines how is understood the value given in bins: 'number' for givinf the desired number\n of bins, 'width' forthe width of the bins, 'edges' for the edges of bins, and 'equal' for\n making bins with equal number of elements (or as close as possible). If not given it is\n inferred from the data type of bins: 'number' if int, 'width' if float and 'edges' if ndarray.\n bins : int, float, array-like, optional\n Gives the values for the bins, according to bin_type.\n smooth : float, optional\n The standard deviation for the Gaussian kernel. Default: 0.0 (No smoothing).\n max_spacing : boolean, optional\n If True, maximises the separation between colours drawn from the colour map. Default: True.\n xlim : tuple-like, optional\n Defines the limits of the x-axis, it must contain two elements (lower and higer limits).\n ylim : tuple-like, optional\n Defines the limits of the y-axis, it must contain two elements (lower and higer limits).\n xinvert : bool, optional\n If True, inverts the x-axis.\n yinvert : bool, optional\n If True, inverts the y-axis.\n xlog : bool, optional\n If True, the scale of the x-axis is logarithmic.\n ylog : bool, optional\n If True, the scale of the x-axis is logarithmic.\n title : str, optional\n Sets the title of the plot\n plabel : array-like or boolean, optional\n Specifies label(s) for the contour(s). If False, do not create a legend. If an array of\n strings, sets the labels for each contour. Must be of equal length to number specified by 'percent'.\n xlabel : str, optional\n Sets the label of the x-axis.\n ylabel : str, optional\n Sets the label of the y-axis.\n lab_loc : int, optional\n Defines the position of the legend\n ax : pyplot.Axes, optional\n Use the given axes to make the plot, defaults to the current axes.\n grid : boolean, optional\n If not given defaults to the value defined in splotch.Params.\n output : boolean, optional\n If True, returns the edges and values of the underlying histogram plus the levels of the contours.\n plot_kw : dict, optional\n Passes the given dictionary as a kwarg to the plotting function. Valid kwargs are QuadContourSet properties.\n **kwargs: QuadContourSet properties, optional\n kwargs are used to specify matplotlib specific properties such as cmap, linewidths, hatches, etc.\n The list of available properties can be found here: \n https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.contour.html\n \n Returns\n -------\n bin_edges_x : array\n The bin edges for the x axis.\n bin_edges_y : array\n The bin edges for the y axis.\n n : array\n The values of the underlying histogram.\n l : array\n The levels for the contours.\n \"\"\"\n \n from warnings import warn\n from matplotlib import lines, patches, rcParams\n from matplotlib.cm import get_cmap, ScalarMappable\n from matplotlib.colors import Normalize\n from matplotlib.pyplot import gca, sca, contour, contourf, legend, Normalize, colorbar \n from numpy import array, linspace, round, ndarray, ceil\n from scipy.ndimage.filters import gaussian_filter\n from .base_func import axes_handler,basehist2D,percent_finder,plot_finalizer,dict_splicer,is_numeric\n from .defaults import Params\n \n # Initialise defaults\n if filled is None:\n filled=Params.cont_filled\n if percent is None:\n percent=Params.contp_percent \n if 'cmap' not in kwargs.keys() and 'cmap' not in plot_kw.keys() and 'colors' not in kwargs.keys() and 'colors' not in plot_kw.keys():\n plot_kw['cmap']=Params.cont_cmap\n if output is None:\n output=Params.contp_output\n \n func_dict={True:contourf,False:contour}\n \n # Assign current axis\n if ax is not None:\n old_axes=axes_handler(ax)\n else:\n ax = gca()\n old_axes=ax\n \n if type(percent) is not ndarray:\n percent=array([percent]).flatten()\n if type(bin_type) not in [list, tuple, ndarray]:\n bin_type=[bin_type]*2\n if type(bins) not in [list,tuple]:\n if bins is None:\n bins = max([10,int(len(x)**0.4)]) # Defaults to min of 10 bins\n bins=[bins]*2\n percent=percent[::-1]\n \n # Combine the `explicit` plot_kw dictionary with the `implicit` **kwargs dictionary\n #plot_par = {**plot_kw, **kwargs} # For Python > 3.5\n plot_par=plot_kw.copy()\n plot_par.update(kwargs)\n \n if filled:\n plot_par['extend']='max'\n \n if not filled and len(percent)<4 and 'colors' not in plot_par.keys(): # if drawing <4 lines with no color specified, get first color of color cycler\n plot_par['colors']=[next(ax._get_lines.prop_cycler)['color']]*len(percent)\n if 'colors' in plot_par.keys():\n if type(plot_par['colors']) is str:\n plot_par['colors']=[plot_par['colors'] for i in range(len(percent))]\n if 'cmap' in plot_par.keys():\n plot_par.pop('cmap')\n elif max_spacing:\n if type(plot_par['cmap']) is str:\n plot_par['cmap']=get_cmap(plot_par['cmap'])\n plot_par['colors']=[plot_par['cmap'](i) for i in linspace(0,1,len(percent))]\n plot_par.pop('cmap')\n if not filled and len(percent)<4 and 'linestyles' not in plot_par.keys(): # if drawing <4 lines with no color specified, use 'solid', 'dashed' and then 'dotted'\n plot_par['linestyles']=[['solid','dashed','dotted'][i] for i in range(len(percent))][::-1]\n \n # Validate labels array\n if (type(plabel) in [list, tuple, ndarray]):\n if (len(plabel) != len(percent)):\n raise ValueError(f\"Length of labels ({len(plabel)}) does not match length of percent ({len(percent)}).\")\n else:\n if plabel is None:\n if rcParams['text.usetex']:\n plabel=[f'{round(p,1)}\\%' for p in percent]\n else:\n plabel=[f'{round(p,1)}%' for p in percent]\n \n X,Y,Z=basehist2D(x,y,None,bin_type,bins,None,None,None,xlog,ylog)\n X=(X[:-1]+X[1:])/2\n Y=(Y[:-1]+Y[1:])/2\n \n level=array([percent_finder(Z,p/100) for p in percent])\n plot_return=func_dict[filled](X,Y,gaussian_filter(Z.T,sigma=smooth),levels=level,**plot_par)\n \n if plabel:\n plot_par['colors']=plot_return.colors\n if type(plot_par['colors']) is str:\n plot_par['colors']=[plot_par['colors'] for i in range(len(percent))]\n plot_par['linestyles']=plot_return.linestyles\n if type(plot_par['linestyles']) is str:\n plot_par['linestyles']=[plot_return.linestyles for i in range(len(percent))]\n elif plot_par['linestyles'] is None:\n plot_par['linestyles']=['solid' for i in range(len(percent))]\n plot_par['alpha']=plot_return.alpha\n if type(plot_par['alpha']) is float:\n plot_par['alpha']=[plot_return.alpha for i in range(len(percent))]\n elif plot_par['alpha'] is None:\n plot_par['alpha']=[1.0 for i in range(len(percent))]\n if filled:\n legend([patches.Patch(color=plot_par['colors'][i],alpha=plot_par['alpha'][i])for i in range(len(percent))],\n plabel,numpoints=1,loc=lab_loc)\n else:\n legend([lines.Line2D([0,1],[0,1],color=plot_par['colors'][i],linestyle=plot_par['linestyles'][i],\n alpha=plot_par['alpha'][i]) for i in range(len(percent))],\n plabel,numpoints=1,loc=lab_loc)\n \n plot_finalizer(xlog,ylog,xlim,ylim,title,xlabel,ylabel,xinvert,yinvert,grid)\n if ax is not None:\n old_axes=axes_handler(old_axes)\n if output:\n return(X,Y,Z.T,array(level))\n\n####################################\n# Error bands\n####################################\ndef errorband(x,y,yerr,line=False,xlim=None,ylim=None,\n xinvert=False,yinvert=False,xlog=False,ylog=None,title=None,xlabel=None,ylabel=None,\n label=None,lab_loc=0,ax=None,grid=None,line_kw={},band_kw={},**kwargs):\n \n \"\"\"Error line and band plotting function.\n \n Parameters\n ----------\n x : array-like or list\n If list it is assumed that each elemement is array-like.\n y : array-like or list\n If list it is assumed that each elemement is array-like.\n yerr : array-like or list, optional\n Defines the length of the errobars in the y-axis. If list it is assumed that each elemement is array-like.\n line : boolean, optional\n If True, draw a line that follows the statistic defined in line_stat.\n xlim : tuple-like, optional\n Defines the limits of the x-axis, it must contain two elements (lower and higer limits).\n ylim : tuple-like, optional\n Defines the limits of the y-axis, it must contain two elements (lower and higer limits).\n xinvert : bool or list, optional\n If True, inverts the x-axis.\n yinvert : bool or list, optional\n If True, inverts the y-axis.\n xlog : bool or list, optional\n If True, the scale of the x-axis is logarithmic.\n ylog : bool or list, optional\n If True, the scale of the x-axis is logarithmic.\n title : str, optional\n Sets the title of the plot\n xlabel : str, optional\n Sets the label of the x-axis.\n ylabel : str, optional\n Sets the label of the y-axis.\n label : str, optional\n Sets the label for the plot.\n lab_loc : int, optional\n Defines the position of the legend\n ax : pyplot.Axes, optional\n Use the given axes to make the plot, defaults to the current axes.\n grid : boolean, optional\n If not given defaults to the value defined in splotch.Params.\n plot_kw : dict, optional\n Passes the given dictionary as a kwarg to the plotting function. Valid kwargs are Line2D properties.\n **kwargs: Line2D properties, optional\n kwargs are used to specify matplotlib specific properties such as linecolor, linewidth, antialiasing, etc.\n A list of available `Line2D` properties can be found here: \n https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D\n \n Returns\n -------\n None\n \"\"\"\n \n from splotch.base_func import axes_handler,bin_axis,plot_finalizer\n \n import numpy as np\n from numbers import Number\n import scipy.stats as stats\n from numpy import array,percentile\n from functools import partial\n import matplotlib.colors as clr\n import matplotlib.pyplot as plt\n from matplotlib.pyplot import gca\n from warnings import warn\n \n # Handle deprecated variables\n deprecated = {'plabel':'label'}\n for dep in deprecated:\n if dep in kwargs:\n warn(f\"'{dep}' will be deprecated in future verions, using '{deprecated[dep]}' instead\")\n if (dep=='plabel'): label = kwargs.pop(dep)\n \n if ax is not None:\n old_axes=axes_handler(ax)\n else:\n ax=gca()\n old_axes=ax\n if ylog is None:\n from splotch.defaults import Params\n ylog=Params.hist1D_yaxis_log\n if 'linewidth' not in band_kw.keys():\n band_kw['linewidth']=0\n if 'alpha' not in band_kw.keys():\n band_kw['alpha']=0.4\n \n # Combine the `explicit` plot_kw dictionary with the `implicit` **kwargs dictionary\n #band_par={**plot_kw, **kwargs} # For Python > 3.5\n band_kw.update(kwargs)\n \n if len(array(yerr).shape)==2:\n plt.fill_between(x,y-yerr[0],y+yerr[1],label=label,**band_kw)\n else:\n plt.fill_between(x,y-yerr,y+yerr,label=label,**band_kw)\n \n if line:\n plt.plot(x,y,**line_kw)\n if label is not None:\n plt.legend(loc=lab_loc)\n \n plot_finalizer(xlog,ylog,xlim,ylim,title,xlabel,ylabel,xinvert,yinvert,grid)\n if ax is not None:\n old_axes=axes_handler(old_axes)\n\n####################################\n# Error bars\n####################################\ndef errorbar(x,y,xerr=None,yerr=None,xlim=None,ylim=None,xinvert=False,yinvert=False,xlog=False,ylog=False,\n title=None,xlabel=None,ylabel=None,label=None,lab_loc=0,ax=None,grid=None,plot_kw={},**kwargs):\n \n \"\"\"Errorbar plotting function.\n \n This is a wrapper for pyplot.errorbar().\n \n Parameters\n ----------\n x : array-like or list\n If list it is assumed that each elemement is array-like.\n y : array-like or list\n If list it is assumed that each elemement is array-like.\n xerr : array-like or list, optional\n Defines the length of the errobars in the x-axis. If list it is assumed that each elemement is array-like.\n yerr : array-like or list, optional\n Defines the length of the errobars in the y-axis. If list it is assumed that each elemement is array-like.\n xlim : tuple-like, optional\n Defines the limits of the x-axis, it must contain two elements (lower and higer limits).\n ylim : tuple-like, optional\n Defines the limits of the y-axis, it must contain two elements (lower and higer limits).\n xinvert : bool or list, optional\n If True, inverts the x-axis.\n yinvert : bool or list, optional\n If True, inverts the y-axis.\n xlog : bool or list, optional\n If True, the scale of the x-axis is logarithmic.\n ylog : bool or list, optional\n If True, the scale of the x-axis is logarithmic.\n title : str, optional\n Sets the title of the plot\n xlabel : str, optional\n Sets the label of the x-axis.\n ylabel : str, optional\n Sets the label of the y-axis.\n label : str, optional\n Sets the label for the plot.\n lab_loc : int, optional\n Defines the position of the legend\n ax : pyplot.Axes, optional\n Use the given axes to make the plot, defaults to the current axes.\n grid : boolean, optional\n If not given defaults to the value defined in splotch.Params.\n plot_kw : dict, optional\n Passes the given dictionary as a kwarg to the plotting function. Valid kwargs are Line2D properties.\n **kwargs: Line2D properties, optional\n kwargs are used to specify matplotlib specific properties such as linecolor, linewidth, antialiasing, etc.\n A list of available `Line2D` properties can be found here: \n https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D\n \n Returns\n -------\n None\n \"\"\"\n \n from .base_func import axes_handler,dict_splicer,plot_finalizer\n \n from matplotlib.pyplot import errorbar, legend, gca\n from warnings import warn\n \n # Handle deprecated variables\n deprecated = {'plabel':'label'}\n for dep in deprecated:\n if dep in kwargs:\n warn(f\"'{dep}' will be deprecated in future verions, using '{deprecated[dep]}' instead\")\n if (dep=='plabel'): label = kwargs.pop(dep)\n \n if ax is not None:\n old_axes=axes_handler(ax)\n else:\n ax=gca()\n old_axes=ax\n if type(x) is not list:\n x=[x]\n if type(y) is not list:\n y=[y]\n if type(xerr) is not list:\n xerr=[xerr]\n if type(yerr) is not list:\n yerr=[yerr]\n L=len(x)\n if type(label) is not list:\n label=[label for i in range(L)]\n \n # Combine the `explicit` plot_kw dictionary with the `implicit` **kwargs dictionary\n #plot_par={**plot_kw, **kwargs} # For Python > 3.5\n plot_par=plot_kw.copy()\n plot_par.update(kwargs)\n \n # Create 'L' number of plot kwarg dictionaries to parse into each plot call\n plot_par=dict_splicer(plot_par,L,[1]*L)\n \n for i in range(L):\n errorbar(x[i],y[i],xerr=xerr[i],yerr=yerr[i],label=label[i],**plot_par[i])\n if any(label):\n legend(loc=lab_loc)\n plot_finalizer(xlog,ylog,xlim,ylim,title,xlabel,ylabel,xinvert,yinvert,grid)\n if ax is not None:\n old_axes=axes_handler(old_axes)\n\n####################################\n# Error boxes\n####################################\ndef errorbox(x,y,xerr=None,yerr=None,xlim=None,ylim=None,xinvert=False,yinvert=False,xlog=False,ylog=False,box_type='ellipse',\n title=None,xlabel=None,ylabel=None,label=None,grid=None,lab_loc=0,ax=None,plot_kw={},**kwargs):\n \n \"\"\"Errorbox plotting function.\n \n This is a wrapper around matplotlib PatchCollections with a matplotlib errorbar functionality.\n \n Parameters\n ----------\n x : array-like or list\n If list it is assumed that each elemement is array-like.\n y : array-like or list\n If list it is assumed that each elemement is array-like.\n xerr : array-like or list, optional\n Defines the length of the errobars in the x-axis. If list it is assumed that each elemement is array-like.\n yerr : array-like or list, optional\n Defines the length of the errobars in the y-axis. If list it is assumed that each elemement is array-like.\n xlim : tuple-like, optional\n Defines the limits of the x-axis, it must contain two elements (lower and higer limits).\n ylim : tuple-like, optional\n Defines the limits of the y-axis, it must contain two elements (lower and higer limits).\n xinvert : bool or list, optional\n If True, inverts the x-axis.\n yinvert : bool or list, optional\n If True, inverts the y-axis.\n xlog : bool or list, optional\n If True, the scale of the x-axis is logarithmic.\n ylog : bool or list, optional\n If True, the scale of the x-axis is logarithmic.\n box_type : str\n The type of box to plot, patch types include: ellipse | rectangle (Default: ellipse).\n title : str, optional\n Sets the title of the plot\n xlabel : str, optional\n Sets the label of the x-axis.\n ylabel : str, optional\n Sets the label of the y-axis.\n label : str, optional\n Sets the label for the plot.\n lab_loc : int, optional\n Defines the position of the legend\n ax : pyplot.Axes, optional\n Use the given axes to make the plot, defaults to the current axes.\n grid : boolean, optional\n If not given defaults to the value defined in splotch.Params.\n plot_kw : dict, optional\n Passes the given dictionary as a kwarg to the plotting function. Valid kwargs are Patches properties.\n **kwargs: Patch properties, optional\n kwargs are used to specify matplotlib specific properties such as facecolor, linestyle, alpha, etc.\n A list of available `Patch` properties can be found here: \n https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.patches.Rectangle.html\n \n Returns\n -------\n None\n \"\"\"\n \n from .base_func import axes_handler,dict_splicer,plot_finalizer\n \n from matplotlib.pyplot import errorbar, legend, gca\n from numpy import shape, full, array\n from matplotlib.collections import PatchCollection\n from matplotlib.patches import Ellipse, Rectangle, Patch\n \n from warnings import warn\n \n # Handle deprecated variables\n deprecated = {'plabel':'label','boxtype':'box_type'}\n for dep in deprecated:\n if dep in kwargs:\n warn(f\"'{dep}' will be deprecated in future verions, using '{deprecated[dep]}' instead\")\n if (dep=='plabel'): label = kwargs.pop(dep)\n if (dep=='boxtype'): box_type = kwargs.pop(dep)\n \n if ax is not None:\n old_axes=axes_handler(ax)\n else:\n ax=gca()\n old_axes=ax\n if type(x) is not list:\n x=[x]\n if type(y) is not list:\n y=[y]\n if type(xerr) is not list:\n xerr=[xerr]\n if type(yerr) is not list:\n yerr=[yerr]\n \n boxdict = {'rec':Rectangle,'ell':Ellipse}\n if (box_type.lower()[:3] not in ['rec','ell']):\n raise ValueError(f\"box_type '{box_type}' not recognised.\")\n \n L=len(x)\n if type(label) is not list:\n label=[label for i in range(L)]\n \n # Validate format of xerr and yerr\n for i in range(L):\n # x-axis errors\n if (shape(xerr[i]) == ()): # single error for all points\n xerr[i]=full((2,len(x[i])), xerr[i])\n else:\n if (len(shape(xerr[i])) == 1):\n if (shape(xerr[i])[0] == len(x[i])): # single error for each point\n xerr[i]=array([xerr[i], xerr[i]])\n elif (shape(xerr[i])[0] == 2): # separate upper and lower errors for all points\n xerr[i]=full((len(x[i]), 2), xerr[i]).T\n else:\n raise ValueError(f\"Invalid shape ({shape(xerr[i])}) for 'xerr' array.\")\n elif (len(shape(xerr[i])) == 2): # separate upper and lower errors for each point\n xerr[i]=array(xerr[i])\n if (shape(xerr[i])[0] != 2 or shape(xerr[i])[1] != len(x[i])):\n raise ValueError(f\"Invalid shape ({shape(xerr[i])}) for 'xerr' array.\")\n \n # y-axis errors\n if (shape(yerr[i]) == ()): # single error for all points\n yerr[i]=full((2,len(y[i])), yerr[i])\n else:\n if (len(shape(yerr[i])) == 1):\n if (shape(yerr[i])[0] == len(y[i])): # single error for each point\n yerr[i]=array([yerr[i], yerr[i]])\n elif (shape(yerr[i])[0] == 2): # separate upper and lower errors for all points\n yerr[i]=full((len(y[i]), 2), yerr[i]).T\n else:\n raise ValueError(f\"Invalid shape ({shape(yerr[i])}) for 'yerr' array.\")\n elif (len(shape(yerr[i])) == 2): # separate upper and lower errors for each point\n yerr[i]=array(yerr[i])\n if (shape(yerr[i])[0] != 2 or shape(yerr[i])[1] != len(y[i])):\n raise ValueError(f\"Invalid shape ({shape(yerr[i])}) for 'yerr' array.\")\n \n # Combine the `explicit` plot_kw dictionary with the `implicit` **kwargs dictionary\n #plot_par={**plot_kw, **kwargs} # For Python > 3.5\n plot_par=plot_kw.copy()\n plot_par.update(kwargs)\n \n # Create 'L' number of plot kwarg dictionaries to parse into each plot call\n plot_par=dict_splicer(plot_par,L,[1]*L)\n \n PathColls=[]\n # Loop over data points; create box/ellipse from errors at each point\n boxdict = {'rec':Rectangle,'ell':Ellipse}\n boxhandles = []\n for i in range(L):\n errorboxes=[]\n for j, (xx, yy, xe, ye) in enumerate(zip(x[i], y[i], xerr[i].T, yerr[i].T)):\n errorboxes.append( boxdict[box_type.lower()[:3]]((xx - xe[0], yy - ye[0]), xe.sum(), ye.sum()) )\n \n \n # Create and add patch collection with specified colour/alpha\n pc=PatchCollection(errorboxes, **plot_par[i])\n boxhandles.append(Patch(**plot_par[i]))\n ax.add_collection(pc)\n \n if any(label):\n legend(handles=boxhandles,labels=label,loc=lab_loc)\n plot_finalizer(xlog,ylog,xlim,ylim,title,xlabel,ylabel,xinvert,yinvert,grid)\n if ax is not None:\n old_axes=axes_handler(old_axes)\n\n####################################\n# Hexagonal 2D histogram\n####################################\ndef hexbin(x,y,bins=None,binlim=None,dens=True,scale=None,\n c=None,cstat=None,xlim=None,ylim=None,clim=[None,None],nmin=0, \n xinvert=False,yinvert=False,cbar_invert=False,xlog=False,ylog=False,clog=None,title=None,xlabel=None,\n ylabel=None,clabel=None,lab_loc=0,ax=None,grid=None,output=None,plot_kw={},**kwargs):\n \n \"\"\"Hexagonal 2D bins function.\n \n Parameters\n ----------\n x : array-like\n Position of data points in the x axis.\n y : array-like\n Position of data points in the y axis.\n bins : int or list, optional\n Gives the number of bins\n binlim : array-like, optional\n Defines the limits for the bins. It must have one dimension and contain four elements,\n with the expected order being (left, right, bottom, top).\n dens : bool or list, optional\n If false the histogram returns raw counts.\n c : array-like, optional\n If a valid argument is given in cstat, defines the value used for the binned statistics.\n cstat : str or function, optional\n Must be one of the valid str arguments for the statistics variable in scipy.stats.binned_statistic_2d\n ('mean’, 'median’, 'count’, 'sum’, 'min’ or 'max’) or a function that takes a 1D array and\n outputs an integer or float.\n xlim : tuple-like, optional\n Defines the limits of the x-axis, it must contain two elements (lower and higer limits).\n ylim : tuple-like, optional\n Defines the limits of the y-axis, it must contain two elements (lower and higer limits).\n clim : list, optional\n Defines the limits of the colour map ranges, it must contain two elements (lower and higer limits).\n nmin : int, optional (default: 0)\n The minimum number of points required in a bin in order to be plotted.\n xinvert : bool, optional\n If True, inverts the x-axis.\n yinvert : bool, optional\n If True, inverts the y-axis.\n cbar_invert : bool, optional\n If True, inverts the direction of the colour bar (not the colour map).\n xlog : bool, optional\n If True, the scale of the x-axis is logarithmic.\n ylog : bool, optional\n If True, the scale of the x-axis is logarithmic.\n clog : bool, optional\n If True, the colour map is changed from linear to logarithmic.\n title : str, optional\n Sets the title of the plot\n xlabel : str, optional\n Sets the label of the x-axis.\n ylabel : str, optional\n Sets the label of the y-axis.\n clabel : str, optional\n Setting `clabel` triggers the generation of a colourbar with axis label given by its value.\n lab_loc : int, optional\n Defines the position of the legend\n ax : pyplot.Axes, optional\n Use the given axes to make the plot, defaults to the current axes.\n grid : boolean, optional\n If not given defaults to the value defined in splotch.Params.\n output : boolean, optional\n If True, returns the edges and values of the histogram.\n plot_kw : dict, optional\n Explicit dictionary of kwargs to be parsed to matplotlib hexbin function.\n Parameters will be overwritten if also given implicitly as a **kwarg.\n **kwargs : pcolormesh properties, optional\n kwargs are used to specify matplotlib specific properties such as cmap, norm, edgecolors etc.\n https://matplotlib.org/api/_as_gen/matplotlib.pyplot.hexbin.html\n \n Returns\n -------\n n : array\n The values of the histogram. Only provided if output is True.\n x_edges : array\n The bin edges for the x axis. Only provided if output is True.\n y_edges : array\n The bin edges for the y axis. Only provided if output is True.\n \"\"\"\n #dens : bool or list, optional\n # If false the histogram returns raw counts.\n #scale : float or list, optional\n # Scaling of the data counts.\n \n from numpy import diff, log10, nan, nanmin, nanmax, nanmedian, nanmax, nanstd, unique, size, zeros, shape\n from matplotlib.colors import LogNorm\n from matplotlib.pyplot import hexbin, colorbar\n from .base_func import axes_handler,plot_finalizer\n \n if ax is not None:\n old_axes=axes_handler(ax)\n if type(bins) not in [list,tuple]:\n if bins is None:\n bins=max([10,int(len(x)**0.4)]) # Defaults to min of 10 bins\n bins=[bins,int(bins/(3**0.5))]\n \n if None in (clog,output):\n from .defaults import Params\n if clog is None:\n clog=Params.hist2D_caxis_log\n if output is None:\n output=Params.hist2D_output\n \n if size([x,y])==0: # Zero-sized arrays given\n if (clog == True): raise ValueError(\"Cannot set 'clog'=True if zero-size array given.\")\n if (cstat != None): raise ValueError(f\"Cannot compute statistic (cstat='{cstat}') on zero-size array, set cstat=None if no data given.\")\n \n temp_x=x*1.0\n temp_y=y*1.0\n \n # Combine the `explicit` plot_kw dictionary with the `implicit` **kwargs dictionary\n #plot_par={**plot_kw, **kwargs} # For Python > 3.5\n plot_par=plot_kw.copy()\n plot_par.update(kwargs)\n if binlim:\n plot_par['extent']=binlim\n #plot_par[]=dens\n #plot_par[]=scale\n if c is not None:\n plot_par['C']=c\n if cstat:\n cstat_func={'min':nanmin,'mean':nanmax,'median':nanmedian,'max':nanmax,'std':nanstd}\n if cstat in cstat_func.keys():\n plot_par['reduce_C_function']=cstat_func[cstat]\n else:\n plot_par['reduce_C_function']=cstat\n if clim:\n plot_par['vmin']=clim[0]\n plot_par['vmax']=clim[1]\n if nmin:\n plot_par['mincnt']=nmin\n if xlog:\n plot_par['xscale']='log'\n temp_x=log10(temp_x)\n if ylog:\n plot_par['yscale']='log'\n temp_y=log10(temp_y)\n if clog:\n plot_par['bins']='log'\n if 'mincnt' not in plot_par.keys():\n plot_par['mincnt']=1\n \n if dens and c is None:\n # This is nasty, but seems to be the quickest way to do this without fully rewriting hexbin here\n hist_return=hexbin(temp_x,temp_y,gridsize=bins)\n hist_return.remove()\n offsets=hist_return.get_offsets()\n offsets_x=unique(offsets[:,0])\n offsets_y=unique(offsets[:,1])\n hex_area=diff(offsets_x)[0]*2*diff(offsets_y)[0]\n \n def density_scaling(bin_data):\n bin_dens=1.0*len(bin_data)/(hex_area)\n if scale:\n bin_dens/=1.0*scale\n else:\n bin_dens/=len(x)\n return(bin_dens)\n \n plot_par['C']=y\n plot_par['reduce_C_function']=density_scaling\n \n hist_return=hexbin(x,y,gridsize=bins,**plot_par)\n \n if clabel is not None:\n cbar=colorbar()\n cbar.set_label(clabel)\n if cbar_invert:\n cbar.ax.invert_yaxis()\n plot_finalizer(xlog,ylog,xlim,ylim,title,xlabel,ylabel,xinvert,yinvert,grid)\n if ax is not None:\n old_axes=axes_handler(old_axes)\n if output:\n return(hist_return.get_array(),hist_return.get_offsets())\n\n####################################\n# 2D histogram and binned statistics\n####################################\ndef hist2D(x,y,bin_type=None,bins=None,dens=True,scale=None,c=None,cstat=None,xlim=None,ylim=None,clim=[None,None],nmin=0, \n xinvert=False,yinvert=False,cbar_invert=False,xlog=False,ylog=False,clog=None,title=None,xlabel=None,\n ylabel=None,clabel=None,lab_loc=0,ax=None,grid=None,output=None,plot_kw={},**kwargs):\n \n \"\"\"2D histogram function.\n \n Parameters\n ----------\n x : array-like\n Position of data points in the x axis.\n y : array-like\n Position of data points in the y axis.\n bin_type : {'number','width','edges','equal'}, optional\n Defines how is understood the value given in bins: 'number' for givinf the desired number of\n bins, 'width' for the width of the bins, 'edges' for the edges of bins, and 'equal' for\n making bins with equal number of elements (or as close as possible). If not given it is\n inferred from the data type of bins: 'number' if int, 'width' if float and 'edges' if ndarray.\n bins : int, float, array-like or list, optional\n Gives the values for the bins, according to bin_type.\n dens : bool or list, optional\n If false the histogram returns raw counts.\n scale : float or list, optional\n Scaling of the data counts.\n c : array-like, optional\n If a valid argument is given in cstat, defines the value used for the binned statistics.\n cstat : str or function, optional\n Must be one of the valid str arguments for the statistics variable in scipy.stats.binned_statistic_2d\n ('mean’, 'median’, 'count’, 'sum’, 'min’ or 'max’) or a function that takes a 1D array and\n outputs an integer or float.\n xlim : tuple-like, optional\n Defines the limits of the x-axis, it must contain two elements (lower and higer limits).\n ylim : tuple-like, optional\n Defines the limits of the y-axis, it must contain two elements (lower and higer limits).\n clim : list, optional\n Defines the limits of the colour map ranges, it must contain two elements (lower and higer limits).\n nmin : int, optional (default: 0)\n The minimum number of points required in a bin in order to be plotted.\n xinvert : bool, optional\n If True, inverts the x-axis.\n yinvert : bool, optional\n If True, inverts the y-axis.\n cbar_invert : bool, optional\n If True, inverts the direction of the colour bar (not the colour map).\n xlog : bool, optional\n If True, the scale of the x-axis is logarithmic.\n ylog : bool, optional\n If True, the scale of the x-axis is logarithmic.\n clog : bool, optional\n If True, the colour map is changed from linear to logarithmic.\n title : str, optional\n Sets the title of the plot\n xlabel : str, optional\n Sets the label of the x-axis.\n ylabel : str, optional\n Sets the label of the y-axis.\n clabel : str, optional\n Setting `clabel` triggers the generation of a colourbar with axis label given by its value.\n lab_loc : int, optional\n Defines the position of the legend\n ax : pyplot.Axes, optional\n Use the given axes to make the plot, defaults to the current axes.\n grid : boolean, optional\n If not given defaults to the value defined in splotch.Params.\n output : boolean, optional\n If True, returns the edges and values of the histogram.\n plot_kw : dict, optional\n Explicit dictionary of kwargs to be parsed to matplotlib pcolormesh function.\n Parameters will be overwritten if also given implicitly as a **kwarg.\n **kwargs : pcolormesh properties, optional\n kwargs are used to specify matplotlib specific properties such as cmap, norm, edgecolors etc.\n https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pcolormesh.html\n \n Returns\n -------\n n : array\n The values of the histogram. Only provided if output is True.\n x_edges : array\n The bin edges for the x axis. Only provided if output is True.\n y_edges : array\n The bin edges for the y axis. Only provided if output is True.\n \"\"\"\n \n from numpy import nan, size, zeros, shape\n from matplotlib.colors import LogNorm\n from matplotlib.pyplot import pcolormesh, colorbar\n from .base_func import axes_handler,basehist2D,plot_finalizer\n \n if ax is not None:\n old_axes=axes_handler(ax)\n if type(bin_type) is not list:\n bin_type=[bin_type]*2\n if type(bins) not in [list,tuple]:\n if bins is None:\n bins=max([10,int(len(x)**0.4)]) # Defaults to min of 10 bins\n bins=[bins]*2\n \n if None in (clog,output):\n from .defaults import Params\n if clog is None:\n clog=Params.hist2D_caxis_log\n if output is None:\n output=Params.hist2D_output\n \n if size([x,y])==0: # Zero-sized arrays given\n if (clog == True): raise ValueError(\"Cannot set 'clog'=True if zero-size array given.\")\n if (cstat != None): raise ValueError(f\"Cannot compute statistic (cstat='{cstat}') on zero-size array, set cstat=None if no data given.\")\n \n X,Y,Z=basehist2D(x,y,c,bin_type,bins,scale,dens,cstat,xlog,ylog)\n \n # Also get counts for number threshold cut\n if (size([x,y])==0):\n counts=zeros(shape=shape(Z))\n else:\n _,_,counts = basehist2D(x,y,c,bin_type,bins,None,False,None,xlog,ylog)\n \n # Cut bins which do not meet the number count threshold\n Z[counts<nmin]=nan\n \n # Combine the `explicit` plot_kw dictionary with the `implicit` **kwargs dictionary\n #plot_par={**plot_kw, **kwargs} # For Python > 3.5\n plot_par=plot_kw.copy()\n plot_par.update(kwargs)\n if clog:\n pcolormesh(X,Y,Z.T,norm=LogNorm(vmin=clim[0],vmax=clim[1],clip=False),**plot_par)\n else:\n pcolormesh(X,Y,Z.T,vmin=clim[0],vmax=clim[1],**plot_par)\n if clabel is not None:\n cbar=colorbar()\n cbar.set_label(clabel)\n if cbar_invert:\n cbar.ax.invert_yaxis()\n plot_finalizer(xlog,ylog,xlim,ylim,title,xlabel,ylabel,xinvert,yinvert,grid)\n if ax is not None:\n old_axes=axes_handler(old_axes)\n if output:\n return(Z.T,X,Y)\n\n####################################\n# Image from 2D array\n####################################\ndef img(im,x=None,y=None,xlim=None,ylim=None,clim=[None,None],cmin=0,xinvert=False,yinvert=False,cbar_invert=False,clog=None,\n title=None,xlabel=None,ylabel=None,clabel=None,lab_loc=0,ax=None,grid=None,plot_kw={},**kwargs):\n \n \"\"\"2D pixel-based image plotting function.\n \n Parameters\n ----------\n im : array-like\n Value for each pixel in an x-y 2D array, where the first dimension is the x-position and the\n second is the y-position.\n x : array-like, optional\n Position of data points in the x axis.\n y : array-like, optional\n Position of data points in the y axis.\n xlim : tuple-like, optional\n Defines the limits of the x-axis, it must contain two elements (lower and higer limits).\n ylim : tuple-like, optional\n Defines the limits of the y-axis, it must contain two elements (lower and higer limits).\n clim : list, optional\n Defines the limits of the colour map ranges, it must contain two elements (lower and higer limits).\n clog : bool, optional\n If True, the colour map is changed from linear to logarithmic.\n xinvert : bool, optional\n If True, inverts the x-axis.\n yinvert : bool, optional\n If True, inverts the y-axis.\n cbar_invert : bool, optional\n If True, inverts the direction of the colour bar (not the colour map).\n title : str, optional\n Sets the title of the plot\n xlabel : str, optional\n Sets the label of the x-axis.\n ylabel : str, optional\n Sets the label of the y-axis.\n clabel : str, optional\n Setting `clabel` triggers the generation of a colourbar with axis label given by its value.\n lab_loc : int, optional\n Defines the position of the legend\n ax : pyplot.Axes, optional\n Use the given axes to make the plot, defaults to the current axes.\n grid : boolean, optional\n If not given defaults to the value defined in splotch.Params.\n plot_kw : dict, optional\n Explicit dictionary of kwargs to be parsed to matplotlib pcolormesh function.\n Parameters will be overwritten if also given implicitly as a **kwarg.\n **kwargs : pcolormesh properties, optional\n kwargs are used to specify matplotlib specific properties such as `cmap`, `marker`, `norm`, etc.\n A list of available `pcolormesh` properties can be found here:\n https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pcolormesh.html\n \n Returns\n -------\n None\n \"\"\"\n \n from numpy import arange, meshgrid\n from matplotlib.colors import LogNorm\n from matplotlib.pyplot import pcolormesh, colorbar\n from .base_func import axes_handler,plot_finalizer\n \n if ax is not None:\n old_axes=axes_handler(ax)\n if x is None:\n x=arange(len(im[:,0])+1)\n if y is None:\n y=arange(len(im[0,:])+1)\n if clog is None:\n from .defaults import Params\n clog=Params.img_caxis_log\n \n X, Y=meshgrid(x, y)\n \n # Combine the `explicit` plot_kw dictionary with the `implicit` **kwargs dictionary\n #plot_par={**plot_kw, **kwargs} # For Python > 3.5\n plot_par=plot_kw.copy()\n plot_par.update(kwargs) \n \n if clog:\n pcolormesh(X,Y,im.T,norm=LogNorm(vmin=clim[0],vmax=clim[1],clip=True),**plot_par)\n else:\n pcolormesh(X,Y,im.T,vmin=clim[0],vmax=clim[1],**plot_par)\n if clabel is not None:\n cbar=colorbar()\n cbar.set_label(clabel)\n if cbar_invert:\n cbar.ax.invert_yaxis()\n plot_finalizer(False,False,xlim,ylim,title,xlabel,ylabel,xinvert,yinvert,grid)\n if ax is not None:\n old_axes=axes_handler(old_axes)\n\n####################################\n# Scatter plots\n####################################\ndef scatter(x,y,c=None,xlim=None,ylim=None,clim=None,density=False,xinvert=False,yinvert=False,cbar_invert=False,xlog=False,ylog=False,title=None,\n xlabel=None,ylabel=None,clabel=None,label=None,lab_loc=0,ax=None,grid=None,plot_kw={},**kwargs):\n \n \"\"\"2D pixel-based image plotting function.\n \n Parameters\n ----------\n x : array-like or list\n Position of data points in the x-axis.\n y : array-like or list\n Position of data points in the y-axis.\n c : array-like or list or str, optional\n Value of data points in the z-axis (colour-axis).\n xlim : tuple-like, optional\n Defines the limits of the x-axis, it must contain two elements (lower and higer limits).\n ylim : tuple-like, optional\n Defines the limits of the y-axis, it must contain two elements (lower and higer limits).\n clim : tuple-like, optional\n Defines the limits of the colour-axis, it must contain two elements (lower and higer limits).\n Functions equivalently to the `vmin, vmax` arguments used by `colors.Normalize`. If both are\n given, `clim` takes priority.\n density : bool, optional\n If True, color-codes points by their spatial density to nearby points using a Gaussian\n kernel density estimate. If 'c' also given, 'density' takes precedence. Default: False.\n xinvert : bool, optional\n If True, inverts the x-axis.\n yinvert : bool, optional\n If True, inverts the y-axis.\n cbar_invert : bool, optional\n If True, inverts the direction of the colour bar (not the colour map).\n xlog : bool, optional\n If True, the scale of the x-axis is logarithmic.\n ylog : bool, optional\n If True, the scale of the x-axis is logarithmic.\n title : str, optional\n Sets the title of the plot\n xlabel : str, optional\n Sets the label of the x-axis.\n ylabel : str, optional\n Sets the label of the y-axis.\n clabel : str, optional\n Setting `clabel` triggers the generation of a colourbar with axis label given by its value.\n label : str, optional\n Sets the label for the scatter plot.\n lab_loc : int, optional\n Defines the position of the legend\n ax : pyplot.Axes, optional\n Use the given axes to make the plot, defaults to the current axes.\n grid : boolean, optional\n If not given defaults to the value defined in splotch.Params.\n plot_kw : dict, optional\n Explicit dictionary of kwargs to be parsed to matplotlib scatter function.\n Parameters will be overwritten if also given implicitly as a **kwarg.\n **kwargs : Collection properties, optional\n kwargs are used to specify matplotlib specific properties such as cmap, marker, norm, etc.\n A list of available `Collection` properties can be found here:\n https://matplotlib.org/api/collections_api.html#matplotlib.collections.Collection\n \n Returns\n -------\n paths\n A list of PathCollection objects representing the plotted data.\n \"\"\"\n \n from numpy import array, dtype, shape, vstack\n from matplotlib.pyplot import scatter, colorbar, legend\n from .base_func import axes_handler,dict_splicer,plot_finalizer\n from scipy.stats import gaussian_kde\n from warnings import warn\n\n # Handle deprecated variables\n deprecated = {'plabel':'label'}\n for dep in deprecated:\n if dep in kwargs:\n warn(f\"'{dep}' will be deprecated in future verions, using '{deprecated[dep]}' instead\")\n if (dep=='plabel'): label = kwargs.pop(dep)\n \n if ax is not None:\n old_axes=axes_handler(ax)\n if type(x) is not list or (len(shape(x))==1 and array(x).dtype is not dtype('O')):\n x=[x]\n if type(y) is not list or (len(shape(y))==1 and array(y).dtype is not dtype('O')):\n y=[y]\n L=len(x)\n if type(c) is not list or (len(shape(c))==1 and array(c).dtype is not dtype('O')):\n c=[c]\n if type(c[0]) is str or c[0] is None:\n c=[c[0] for i in range(L)]\n if type(label) is not list:\n label=[label for i in range(L)]\n \n # Combine the `explicit` plot_kw dictionary with the `implicit` **kwargs dictionary\n #plot_par={**plot_kw, **kwargs} # For Python > 3.5\n plot_par=plot_kw.copy()\n plot_par.update(kwargs)\n \n # Insert clim as vmin, vmax into **kwargs dictionary, if given.\n if (clim != None):\n try:\n _=(e for e in clim)\n if (len(clim) == 2):\n plot_par['vmin']=clim[0]\n plot_par['vmax']=clim[1]\n else:\n raise TypeError(\"`clim` must be of iterable type and have two values only.\")\n except (TypeError):\n raise TypeError(\"`clim` must be of iterable type and have two values only.\")\n \n if (density == True):\n if (all([kk is not None for kk in c])):\n warn(\"Cannot specify both `c` and `density`, ignoring `c`.\")\n c=[None]*L\n for i in range(L):\n xy=vstack([x[i],y[i]])\n c[i]=gaussian_kde(xy)(xy) # Calculate the Gaussian kernel density estimate\n \n # Create 'L' number of plot kwarg dictionaries to parse into each scatter call\n plot_par=dict_splicer(plot_par,L,[len(i) for i in x])\n \n paths=[]\n for i in range(L):\n p=scatter(x[i],y[i],c=c[i],label=label[i],**plot_par[i])\n paths.append(p)\n if clabel is not None:\n cbar=colorbar()\n cbar.set_label(clabel)\n if cbar_invert:\n cbar.ax.invert_yaxis()\n if any(label):\n legend(loc=lab_loc)\n plot_finalizer(xlog,ylog,xlim,ylim,title,xlabel,ylabel,xinvert,yinvert,grid)\n if ax is not None:\n old_axes=axes_handler(old_axes)\n \n return paths[0] if len(paths) == 1 else paths\n\n####################################\n# Sector plots\n####################################\ndef sector(r,theta,rlim=(0.0,1.0),thetalim=(0.0,360.0),clim=None,rotate=0.0,rlabel=\"\",thetalabel=\"\",clabel=None,label=None,rstep=None,\n thetastep=15.0,rticks='auto',thetaticks='auto',cbar_invert=False,fig=None,plot_kw={},**kwargs):\n \n \"\"\" Sector Plot function\n \n Plots a sector plot (a.k.a \"pizza plot\") based on data with one radial axis and an angular axis\n \n Parameters\n ----------\n r : array-like or list\n Radial axis data.\n theta : array-like or list\n Angular axis data (degrees).\n rlim : tuple-like, optional\n The lower and upper limits for the radial axis (degrees).\n thetalim : tuple-like, optional\n The lower and upper limits for the angular axis (degrees).\n clim : tuple-like, optional\n Defines the limits of the colour-axis, it must contain two elements (lower and higer limits).\n Functions equivalently to the `vmin, vmax` arguments used by `colors.Normalize`. If both are\n given, `clim` takes priority.\n rotate : float, optional\n By how many degrees (clockwise) to rotate the entire plot (valid values in [-180, 180]).\n rlabel : str, optional\n Sets the label of the r-axis.\n thetalabel : str, optional\n Sets the label of the theta-axis.\n clabel : str, optional\n Setting `clabel` triggers the generation of a colourbar with axis label given by its value.\n label : str, optional\n Sets the label for the scatter plot.\n rstep : float, optional\n Sets the step size of r ticks.\n thetastep : float, optional, default: 15.0\n Sets the step size of theta ticks (degrees).\n rticks : 'auto', or ticker\n * Not implement *\n thetaticks : 'auto', or ticker\n * Not implement *\n cbar_invert : bool, optional\n If True, inverts the direction of the colour bar (not the colour map).\n fig : pyplot.Figure, optional\n Use the given figure to make the plot, defaults to the current figure.\n plot_kw : dict, optional\n Explicit dictionary of kwargs to be parsed to matplotlib scatter function.\n Parameters will be overwritten if also given implicitly in **kwargs.\n **kwargs : Collection properties, optional\n kwargs are used to specify matplotlib specific properties such as cmap, marker, norm, etc.\n A list of available `Collection` properties can be found here:\n https://matplotlib.org/3.1.0/api/collections_api.html#matplotlib.collections.Collection\n \n Returns\n -------\n ax : The pyplot.Axes object created for the sector plot.\n \"\"\"\n \n from matplotlib.transforms import Affine2D\n from matplotlib.projections.polar import PolarAxes\n from matplotlib.pyplot import gcf, colorbar, legend \n \n from mpl_toolkits.axisartist import floating_axes\n from mpl_toolkits.axisartist.grid_finder import (FixedLocator, MaxNLocator, DictFormatter)\n import mpl_toolkits.axisartist.angle_helper as angle_helper\n \n from numpy import array, linspace, arange, shape, sqrt, floor, round, degrees, radians, pi\n \n if (fig == None):\n fig=gcf()\n \n # rotate a bit for better orientation\n trans_rotate=Affine2D().translate(0.0, 0)\n \n # scale degree to radians\n trans_scale=Affine2D().scale(pi/180.0, 1.)\n trans=trans_rotate + trans_scale + PolarAxes.PolarTransform()\n \n # Get theta ticks\n #if (thetaticks == 'auto'):\n thetaticks=arange(*radians(array(thetalim)-rotate),step=radians(thetastep))\n theta_gridloc=FixedLocator(thetaticks[thetaticks/(2*pi) < 1])\n theta_tickfmtr=DictFormatter(dict(zip(thetaticks,[f\"{(round(degrees(tck)+rotate)):g}\" for tck in thetaticks])))\n \n #tick_fmtr=DictFormatter(dict(angle_ticks))\n #tick_fmtr=angle_helper.Formatter()\n \n if (rstep == None):\n rstep=0.5\n \n r_gridloc=FixedLocator(arange(rlim[0],rlim[1],step=rstep))\n \n grid=floating_axes.GridHelperCurveLinear(\n PolarAxes.PolarTransform(),\n extremes=(*radians(array(thetalim)-rotate), *rlim),\n grid_locator1=theta_gridloc,\n grid_locator2=r_gridloc,\n tick_formatter1=theta_tickfmtr,\n tick_formatter2=None,\n )\n \n ax=floating_axes.FloatingSubplot(fig, 111, grid_helper=grid)\n fig.add_subplot(ax)\n \n # tick references\n thetadir_ref=['top','right','bottom','left']\n rdir_ref=['bottom','left','top','right']\n \n # adjust axes directions\n ax.axis[\"left\"].set_axis_direction('bottom') # Radius axis (displayed)\n ax.axis[\"right\"].set_axis_direction('top') # Radius axis (hidden)\n ax.axis[\"top\"].set_axis_direction('bottom') # Theta axis (outer)\n ax.axis[\"bottom\"].set_axis_direction('top') # Theta axis (inner)\n \n # Top theta axis\n ax.axis[\"top\"].toggle(ticklabels=True, label=True)\n ax.axis[\"top\"].major_ticklabels.set_axis_direction(thetadir_ref[(int(rotate)//90)%4])\n ax.axis[\"top\"].label.set_axis_direction(thetadir_ref[(int(rotate)//90)%4])\n \n # Bottom theta axis\n ax.axis[\"bottom\"].set_visible(False if rlim[0] < (rlim[1]-rlim[0])/3 else True)\n ax.axis[\"bottom\"].major_ticklabels.set_axis_direction(thetadir_ref[(int(rotate)//90+2)%4])\n \n # Visible radius axis \n ax.axis[\"left\"].major_ticklabels.set_axis_direction(rdir_ref[(int(rotate)//90)%4])\n ax.axis[\"left\"].label.set_axis_direction(rdir_ref[(int(rotate)//90)%4])\n \n # Labels\n ax.axis[\"left\"].label.set_text(rlabel)\n ax.axis[\"top\"].label.set_text(thetalabel)\n \n # create a parasite axes whose transData in RA, cz\n sector_ax=ax.get_aux_axes(trans)\n \n # This has a side effect that the patch is drawn twice, and possibly over some other\n # artists. So, we decrease the zorder a bit to prevent this. \n sector_ax.patch=ax.patch \n sector_ax.patch.zorder=0.9\n \n \n L=shape(theta)[0] if len(shape(theta)) > 1 else 1\n plot_par=plot_kw.copy()\n plot_par.update(kwargs)\n \n # Insert clim as vmin, vmax into **kwargs dictionary, if given.\n if (clim != None):\n try:\n _=(e for e in clim)\n if (len(clim) == 2):\n plot_par['vmin']=clim[0]\n plot_par['vmax']=clim[1]\n else:\n raise TypeError(\"`clim` must be of iterable type and have two values only.\")\n except (TypeError):\n raise TypeError(\"`clim` must be of iterable type and have two values only.\")\n \n # Create 'L' number of plot kwarg dictionaries to parse into each plot call\n #plot_par=dict_splicer(plot_par,L,[1]*L)\n \n if (L == 1):\n sctr=sector_ax.scatter(theta-rotate, r, label=label, **plot_par)\n else:\n for ii in range(L):\n sctr=sector_ax.scatter(theta[ii]-rotate, r[ii], label=label[ii],**plot_par[ii])\n \n if clabel is not None:\n cbar=colorbar(sctr)\n cbar.set_label(clabel)\n if cbar_invert:\n cbar.ax.invert_yaxis()\n \n return sector_ax\n\n####################################\n# Statistics bands\n####################################\ndef statband(x,y,bin_type=None,bins=None,stat_mid='mean',stat_low='std',stat_high='std',from_mid=None,line=False,xlim=None,ylim=None,\n xinvert=False,yinvert=False,xlog=False,ylog=None,title=None,xlabel=None,ylabel=None,\n label=None,lab_loc=0,ax=None,grid=None,line_kw={},band_kw={},**kwargs):\n \n \"\"\"Statistics line and band plotting function.\n \n Parameters\n ----------\n x : array-like or list\n If list it is assumed that each elemement is array-like.\n y : array-like or list\n If list it is assumed that each elemement is array-like.\n bin_type : {'number','width','edges','equal'}, optional\n Defines how is understood the value given in bins: 'number' for the desired number of bins, 'width' for the width\n of the bins, 'edges' for the edges of bins, and 'equal' for making bins with equal number of elements (or as close\n as possible). If not given it is inferred from the data type of bins: 'number' if int, 'width' if float and 'edges'\n if ndarray.\n bins : int, float, array-like or list, optional\n Gives the values for the bins, according to bin_type.\n stat_mid : str, int, float or function, optional\n Defines how to calculate the midpoint of the statistics band. When passing a string it must be either one of the options\n for scipy.stats.binned_statistic(), i.e. 'mean', 'std', 'median', 'count', 'sum', 'min', 'max' or a user-defined function.\n If given as an integer or float, the number represents the value for the percentile to calculate in each bin.\n A function can be given which takes (only) a 1D array of values and returns a numerical statistic.\n stat_low / stat_high : str, int, float or function, optional\n Defines how to calculate the lower/upper limits for the statistic band. Can be given as one of the recognised strings above or as\n a string combining 'std' with a number, i.e. '[n]std', where [n] is the number of standard deviations away from the line of `stat_mid`.\n Can also be given as a number (integer or float) or function as described for stat_mid.\n from_mid : boolean, optional\n If True, the lower/upper bounds of the band are determined as the separation from the stat_mid line: i.e. stat_mid +/- stat_[low/high],\n otherwise, they are set to the values returned by stat_[low/high]. Defaults to True if stat_[low/high] are standard deviations.\n line : boolean, optional\n If True, draw a line that follows the statistic defined in line_stat.\n xlim : tuple-like, optional\n Defines the limits of the x-axis, it must contain two elements (lower and higer limits).\n ylim : tuple-like, optional\n Defines the limits of the y-axis, it must contain two elements (lower and higer limits).\n xinvert : bool or list, optional\n If True, inverts the x-axis.\n yinvert : bool or list, optional\n If True, inverts the y-axis.\n xlog : bool or list, optional\n If True, the scale of the x-axis is logarithmic.\n ylog : bool or list, optional\n If True, the scale of the x-axis is logarithmic.\n title : str, optional\n Sets the title of the plot\n xlabel : str, optional\n Sets the label of the x-axis.\n ylabel : str, optional\n Sets the label of the y-axis.\n label : str, optional\n Sets the label for the plot.\n lab_loc : int, optional\n Defines the position of the legend\n ax : pyplot.Axes, optional\n Use the given axes to make the plot, defaults to the current axes.\n grid : boolean, optional\n If not given defaults to the value defined in splotch.Params.\n plot_kw : dict, optional\n Passes the given dictionary as a kwarg to the plotting function. Valid kwargs are Line2D properties.\n **kwargs: Line2D properties, optional\n kwargs are used to specify matplotlib specific properties such as linecolor, linewidth, antialiasing, etc.\n A list of available `Line2D` properties can be found here: \n https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D\n \n Returns\n -------\n None\n \"\"\"\n \n from splotch.base_func import axes_handler,bin_axis,plot_finalizer\n \n import numpy as np\n from numbers import Number\n import scipy.stats as stats\n from numpy import percentile\n from functools import partial\n import matplotlib.colors as clr\n import matplotlib.pyplot as plt\n from matplotlib.pyplot import gca\n from warnings import warn\n\n if ax is not None:\n old_axes=axes_handler(ax)\n else:\n ax=gca()\n old_axes=ax\n if ylog is None:\n from splotch.defaults import Params\n ylog=Params.hist1D_yaxis_log\n if bins is None:\n bins=int((len(x))**0.4)\n if 'linewidth' not in band_kw.keys():\n band_kw['linewidth']=0\n if 'alpha' not in band_kw.keys():\n band_kw['alpha']=0.4\n \n # Combine the `explicit` plot_kw dictionary with the `implicit` **kwargs dictionary\n #band_par={**plot_kw, **kwargs} # For Python > 3.5\n band_kw.update(kwargs)\n \n # Check stat_low/stat_high arguments\n band_stat=np.array([None,None])\n band_multi=np.ones(2)\n for i, stat in enumerate([stat_low,stat_high]): # loop over low/high statistic\n if isinstance(stat,Number): # stat given as a percentile number\n band_stat[i] = partial(percentile,q=stat) # Set as the percentile function with kwargs fixed.\n elif callable(stat): # stat given as a function\n band_stat[i] = stat\n elif isinstance(stat,str) and 'std' in stat: # stat given as a string with 'std'\n band_stat[i] = 'std'\n multi = list(filter(None,stat.split('std'))) # The multiplier for std, if any.\n if len(multi) == 0: # No multiplier given\n band_multi[i] = 1.0\n elif len(multi) == 1: # Multiplier was given\n band_multi[i] = multi[0]\n else: \n raise ValueError(f\"Statistic '{stat}' not valid. Should be given as '[n]std', where [n] is a number.\")\n else:\n raise ValueError(f\"Statistic of type '{type(stat)}' was not recognised. Must be either a Number, function or string in the format '[n]std'.\")\n \n # Check stat_mid argument\n if isinstance(stat_mid,Number):\n stat_mid=partial(percentile,q=stat_mid)\n\n # Assign 'from_mid' if not explicitly set\n if from_mid is None:\n if (band_stat[0] in ['std',np.std,np.nanstd] and (band_stat[1] in ['std',np.std,np.nanstd])): # Band stats a type of standard deviation\n from_mid = True\n else:\n from_mid = False\n \n temp_x,bins_hist,bins_plot=bin_axis(x,bin_type,bins,log=xlog)\n temp_y=stats.binned_statistic(temp_x,y,statistic=stat_mid,bins=bins_hist)[0]\n if band_stat[0]==band_stat[1]:\n band_low,band_high=[stats.binned_statistic(temp_x,y,statistic=band_stat[0],bins=bins_hist)[0]]*2\n else:\n band_low=stats.binned_statistic(temp_x,y,statistic=band_stat[0],bins=bins_hist)[0]\n band_high=stats.binned_statistic(temp_x,y,statistic=band_stat[1],bins=bins_hist)[0]\n\n if from_mid == True: # Band intervals should be taken as the difference from the mid line\n band_low = temp_y-band_multi[0]*band_low\n band_high = temp_y+band_multi[1]*band_high\n \n if ylog:\n temp_y=np.where(temp_y==0,np.nan,temp_y)\n\n x=stats.binned_statistic(temp_x,x,statistic=stat_mid,bins=bins_hist)[0]\n y=temp_y\n \n plt.fill_between(x,band_low,band_high,label=label,**band_kw)\n\n if line:\n plt.plot(x,y,**line_kw)\n if label is not None:\n plt.legend(loc=lab_loc)\n \n plot_finalizer(xlog,ylog,xlim,ylim,title,xlabel,ylabel,xinvert,yinvert,grid)\n if ax is not None:\n old_axes=axes_handler(old_axes)\n\n####################################\n# Statistics bars\n####################################\ndef statbar(x,y,bin_type=None,bins=None,stat_cen='mean',bar_x=True,stat_y='std',line=False,xlim=None,ylim=None,\n xinvert=False,yinvert=False,xlog=False,ylog=None,title=None,xlabel=None,ylabel=None,\n label=None,lab_loc=0,ax=None,grid=None,plot_kw={},**kwargs):\n \n \"\"\"Statistics line and bar plotting function.\n \n Parameters\n ----------\n x : array-like or list\n If list it is assumed that each elemement is array-like.\n y : array-like or list\n If list it is assumed that each elemement is array-like.\n bin_type : {'number','width','edges','equal'}, optional\n Defines how is understood the value given in bins: 'number' for the desired number of bins, 'width' for the width\n of the bins, 'edges' for the edges of bins, and 'equal' for making bins with equal number of elements (or as close\n as possible). If not given it is inferred from the data type of bins: 'number' if int, 'width' if float and 'edges'\n if ndarray.\n bins : int, float, array-like or list, optional\n Gives the values for the bins, according to bin_type.\n stat_cen : str, int, float, function, or 2-element array-like of any of the previous type, optional\n Defines how to calculate the position of centre of each errorbar. When passing an integer or float is\n interpreted as being the percentile for the limit. When passing a function it must have the input and\n ouput characteristics required by scipy.stats.binned_statistic().\n bar_x : bool, optional\n If False turns off the display of the bin widths with bars.\n stat_y : str, int, float, function, or 2-element array-like of any of the previous type, optional\n Defines how to calculate the y error bars. When passing a string it must be either one of the options\n for scipy.stats.binned_statistic(), or a string that combines 'std' with a number (e.g., '2.2std'), where to number is\n interpreted as the number of standard deviations that the limit must cover. When passing an integer or float is\n interpreted as being the percentile for the limit. When passing a function it must have the input and ouput\n characteristics required by scipy.stats.binned_statistic().\n line : boolean, optional\n If True, draw a line that follows the statistic defined in line_stat.\n xlim : tuple-like, optional\n Defines the limits of the x-axis, it must contain two elements (lower and higer limits).\n ylim : tuple-like, optional\n Defines the limits of the y-axis, it must contain two elements (lower and higer limits).\n xinvert : bool or list, optional\n If True, inverts the x-axis.\n yinvert : bool or list, optional\n If True, inverts the y-axis.\n xlog : bool or list, optional\n If True, the scale of the x-axis is logarithmic.\n ylog : bool or list, optional\n If True, the scale of the x-axis is logarithmic.\n title : str, optional\n Sets the title of the plot\n xlabel : str, optional\n Sets the label of the x-axis.\n ylabel : str, optional\n Sets the label of the y-axis.\n label : str, optional\n Sets the label for the plot.\n lab_loc : int, optional\n Defines the position of the legend\n ax : pyplot.Axes, optional\n Use the given axes to make the plot, defaults to the current axes.\n grid : boolean, optional\n If not given defaults to the value defined in splotch.Params.\n plot_kw : dict, optional\n Passes the given dictionary as a kwarg to the plotting function. Valid kwargs are Line2D properties.\n **kwargs: Line2D properties, optional\n kwargs are used to specify matplotlib specific properties such as linecolor, linewidth, antialiasing, etc.\n A list of available `Line2D` properties can be found here: \n https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D\n \n Returns\n -------\n None\n \"\"\"\n \n from splotch.base_func import axes_handler,bin_axis,plot_finalizer\n \n import numpy as np\n from numbers import Number\n import scipy.stats as stats\n from numpy import percentile\n from functools import partial\n import matplotlib.colors as clr\n import matplotlib.pyplot as plt\n from matplotlib.pyplot import gca, errorbar, rcParams\n from warnings import warn\n \n if ax is not None:\n old_axes=axes_handler(ax)\n else:\n ax=gca()\n old_axes=ax\n if ylog is None:\n from splotch.defaults import Params\n ylog=Params.hist1D_yaxis_log\n if bins is None:\n bins=int((len(x))**0.4)\n \n if type(stat_y)!=str:\n try:\n iter(stat_y)\n except TypeError:\n stat_y=[stat_y,stat_y]\n else:\n stat_y=[stat_y,stat_y]\n \n # Combine the `explicit` plot_kw dictionary with the `implicit` **kwargs dictionary\n #plot_par={**plot_kw, **kwargs} # For Python > 3.5\n plot_par=plot_kw.copy()\n plot_par.update(kwargs)\n if 'linewidth' not in plot_par.keys():\n plot_par['linewidth']=0\n if 'elinewidth' not in plot_par.keys():\n plot_par['elinewidth']=rcParams['lines.linewidth']\n \n bar_multi=np.ones(2)\n for i in range(len(stat_y)):\n if isinstance(stat_y[i],Number):\n stat_y[i]=partial(percentile,q=stat_y[i])\n elif 'std' in stat_y[i] and len(stat_y[i].replace('std',''))>0:\n bar_multi[i]=float(stat_y[i].replace('std',''))\n stat_y[i]='std'\n \n if isinstance(stat_cen,Number):\n stat_cen=partial(percentile,q=stat_cen)\n \n temp_x,bins_hist,bins_plot=bin_axis(x,bin_type,bins,log=xlog)\n temp_y=stats.binned_statistic(temp_x,y,statistic=stat_cen,bins=bins_hist)[0]\n if stat_y[0]==stat_y[1]:\n bar_low,bar_high=[stats.binned_statistic(temp_x,y,statistic=stat_y[0],bins=bins_hist)[0]]*2\n else:\n bar_low=stats.binned_statistic(temp_x,y,statistic=stat_y[0],bins=bins_hist)[0]\n bar_high=stats.binned_statistic(temp_x,y,statistic=stat_y[1],bins=bins_hist)[0]\n if stat_y[0]=='std':\n bar_low=bar_multi[0]*bar_low\n else:\n bar_low=temp_y-bar_low\n if stat_y[0]=='std':\n bar_high=bar_multi[0]*bar_high\n else:\n bar_high-=temp_y\n if ylog:\n temp_y=np.where(temp_y==0,np.nan,temp_y)\n x=stats.binned_statistic(temp_x,x,statistic=stat_cen,bins=bins_hist)[0]\n y=temp_y\n if bar_x:\n bar_x=[x-bins_plot[:-1],bins_plot[1:]-x]\n \n if bar_x:\n errorbar(x,y,xerr=bar_x,yerr=[bar_low,bar_high],**plot_par)\n else:\n errorbar(x,y,yerr=[bar_low,bar_high],**plot_par)\n if label is not None:\n plt.legend(loc=lab_loc)\n \n plot_finalizer(xlog,ylog,xlim,ylim,title,xlabel,ylabel,xinvert,yinvert,grid)\n if ax is not None:\n old_axes=axes_handler(old_axes)\n"
] |
[
[
"matplotlib.pyplot.legend",
"numpy.radians",
"numpy.linspace",
"matplotlib.transforms.Affine2D",
"numpy.dtype",
"matplotlib.pyplot.plot",
"numpy.round",
"scipy.stats.gaussian_kde",
"scipy.ndimage.filters.gaussian_filter",
"scipy.stats.binned_statistic",
"numpy.where",
"matplotlib.pyplot.gca",
"matplotlib.patches.Patch",
"numpy.unique",
"numpy.arange",
"matplotlib.pyplot.gcf",
"numpy.size",
"matplotlib.projections.polar.PolarAxes.PolarTransform",
"numpy.diff",
"matplotlib.pyplot.errorbar",
"matplotlib.pyplot.hexbin",
"numpy.log10",
"matplotlib.pyplot.fill_between",
"numpy.meshgrid",
"numpy.array",
"matplotlib.collections.PatchCollection",
"matplotlib.colors.LogNorm",
"matplotlib.pyplot.scatter",
"numpy.degrees",
"matplotlib.lines.Line2D",
"numpy.ones",
"matplotlib.pyplot.colorbar",
"numpy.shape",
"matplotlib.cm.get_cmap",
"matplotlib.pyplot.pcolormesh",
"numpy.vstack"
]
] |
osiriszjq/RND-pytorch
|
[
"17582a90cfcb84b6e0dc8c5cfba8b9c5472c7fb3"
] |
[
"train_sil.py"
] |
[
"import numpy as np\nimport os\n\nimport torch.nn.functional as F\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.distributions.categorical import Categorical\nfrom torch.multiprocessing import Pipe\n\nfrom model import CnnActorCriticNetwork, RNDModel\nfrom SILmodel import SILModel\nfrom envs import *\nfrom utils import RunningMeanStd, RewardForwardFilter\nfrom arguments import get_args\n\nfrom tensorboardX import SummaryWriter\n\ndef get_action(model, device, state):\n state = torch.Tensor(state).to(device)\n state = state.float()\n action_probs, value_ext, value_int = model(state)\n action_dist = Categorical(action_probs)\n action = action_dist.sample()\n\n action = action.data.cpu().numpy().squeeze()\n value_ext = value_ext.data.cpu().numpy().squeeze()\n value_int = value_int.data.cpu().numpy().squeeze()\n action_probs = action_probs.detach().cpu()\n return action, value_ext, value_int, action_probs\n\n\ndef compute_intrinsic_reward(rnd, device, next_obs):\n next_obs = torch.FloatTensor(next_obs).to(device)\n\n target_next_feature = rnd.target(next_obs)\n predict_next_feature = rnd.predictor(next_obs)\n intrinsic_reward = (target_next_feature - predict_next_feature).pow(2).sum(1) / 2\n\n return intrinsic_reward.data.cpu().numpy()\n\n\ndef make_train_data(reward, done, value, gamma, gae_lambda, num_step, num_worker, use_gae):\n discounted_return = np.empty([num_worker, num_step])\n\n # Discounted Return\n if use_gae:\n gae = np.zeros_like([num_worker, ])\n for t in range(num_step - 1, -1, -1):\n delta = reward[:, t] + gamma * value[:, t + 1] * (1 - done[:, t]) - value[:, t]\n gae = delta + gamma * gae_lambda * (1 - done[:, t]) * gae\n\n discounted_return[:, t] = gae + value[:, t]\n\n # For Actor\n adv = discounted_return - value[:, :-1]\n\n else:\n running_add = value[:, -1]\n for t in range(num_step - 1, -1, -1):\n running_add = reward[:, t] + gamma * running_add * (1 - done[:, t])\n discounted_return[:, t] = running_add\n\n # For Actor\n adv = discounted_return - value[:, :-1]\n\n return discounted_return.reshape([-1]), adv.reshape([-1])\n\n\ndef train_model(args, device, output_size, model, rnd, optimizer, s_batch, target_ext_batch,\n target_int_batch, y_batch, adv_batch, next_obs_batch, old_action_probs):\n epoch = 3\n update_proportion = 0.25\n s_batch = torch.FloatTensor(s_batch).to(device)\n target_ext_batch = torch.FloatTensor(target_ext_batch).to(device)\n target_int_batch = torch.FloatTensor(target_int_batch).to(device)\n y_batch = torch.LongTensor(y_batch).to(device)\n adv_batch = torch.FloatTensor(adv_batch).to(device)\n next_obs_batch = torch.FloatTensor(next_obs_batch).to(device)\n\n sample_range = np.arange(len(s_batch))\n forward_mse = nn.MSELoss(reduction='none')\n\n with torch.no_grad():\n action_probs_old_list = torch.stack(old_action_probs).permute(1, 0, 2).contiguous().view(-1, output_size).to(device)\n\n m_old = Categorical(action_probs_old_list)\n log_prob_old = m_old.log_prob(y_batch)\n # ------------------------------------------------------------\n\n for i in range(epoch):\n np.random.shuffle(sample_range)\n for j in range(int(len(s_batch) / args.batch_size)):\n sample_idx = sample_range[args.batch_size * j:args.batch_size * (j + 1)]\n\n # --------------------------------------------------------------------------------\n # for Curiosity-driven(Random Network Distillation)\n predict_next_state_feature, target_next_state_feature = rnd(next_obs_batch[sample_idx])\n\n forward_loss = forward_mse(predict_next_state_feature, target_next_state_feature.detach()).mean(-1)\n # Proportion of exp used for predictor update\n mask = torch.rand(len(forward_loss)).to(device)\n mask = (mask < update_proportion).type(torch.FloatTensor).to(device)\n forward_loss = (forward_loss * mask).sum() / torch.max(mask.sum(), torch.Tensor([1]).to(device))\n # ---------------------------------------------------------------------------------\n\n action_probs, value_ext, value_int = model(s_batch[sample_idx])\n m = Categorical(action_probs)\n log_prob = m.log_prob(y_batch[sample_idx])\n\n ratio = torch.exp(log_prob - log_prob_old[sample_idx])\n\n surr1 = ratio * adv_batch[sample_idx]\n surr2 = torch.clamp(\n ratio,\n 1.0 - args.eps,\n 1.0 + args.eps) * adv_batch[sample_idx]\n\n actor_loss = -torch.min(surr1, surr2).mean()\n critic_ext_loss = F.mse_loss(value_ext.sum(1), target_ext_batch[sample_idx])\n critic_int_loss = F.mse_loss(value_int.sum(1), target_int_batch[sample_idx])\n\n critic_loss = critic_ext_loss + critic_int_loss\n\n entropy = m.entropy().mean()\n\n optimizer.zero_grad()\n loss = actor_loss + 0.5 * critic_loss - args.entropy_coef * entropy + forward_loss\n loss.backward()\n optimizer.step()\n\n\ndef main():\n args = get_args()\n device = torch.device('cuda' if args.cuda else 'cpu')\n\n env = gym.make(args.env_name)\n\n input_size = env.observation_space.shape # 4\n output_size = env.action_space.n # 2\n\n if 'Breakout' in args.env_name:\n output_size -= 1\n\n env.close()\n\n is_render = False\n if not os.path.exists(args.save_dir):\n\t os.makedirs(args.save_dir)\n model_path = os.path.join(args.save_dir, args.env_name + '.model')\n predictor_path = os.path.join(args.save_dir, args.env_name + '.pred')\n target_path = os.path.join(args.save_dir, args.env_name + '.target')\n\n writer = SummaryWriter(log_dir=args.log_dir)\n\n reward_rms = RunningMeanStd()\n obs_rms = RunningMeanStd(shape=(1, 1, 84, 84))\n discounted_reward = RewardForwardFilter(args.ext_gamma)\n\n model = CnnActorCriticNetwork(input_size, output_size, args.use_noisy_net)\n rnd = RNDModel(input_size, output_size)\n model = model.to(device)\n rnd = rnd.to(device)\n optimizer = optim.Adam(list(model.parameters()) + list(rnd.predictor.parameters()), lr=args.lr)\n\n sil = SILModel(model, args, optimizer, device)\n\n if args.load_model:\n if args.cuda:\n model.load_state_dict(torch.load(model_path))\n rnd.predictor.load_state_dict(torch.load(predictor_path))\n rnd.target.load_state_dict(torch.load(target_path))\n print('Load moldes successfully.')\n else:\n model.load_state_dict(torch.load(model_path, map_location='cpu'))\n rnd.predictor.load_state_dict(torch.load(predictor_path))\n rnd.target.load_state_dict(torch.load(target_path))\n\n works = []\n parent_conns = []\n child_conns = []\n for idx in range(args.num_worker):\n parent_conn, child_conn = Pipe()\n work = AtariEnvironment(\n \targs.env_name,\n args.output_path,\n is_render,\n \tidx,\n \tchild_conn,\n \tsticky_action=args.sticky_action,\n \tp=args.sticky_action_prob,\n \tmax_episode_steps=args.max_episode_steps)\n work.start()\n works.append(work)\n parent_conns.append(parent_conn)\n child_conns.append(child_conn)\n\n states = np.zeros([args.num_worker, 4, 84, 84])\n\n sample_env_index = 0 # Sample Environment index to logsample_env_index\n sample_episode = 0\n sample_rall = 0\n sample_step = 0\n sample_i_rall = 0\n global_update = 0\n global_step = 0\n\n # normalize observation\n print('Initializes observation normalization...')\n next_obs = []\n for step in range(args.num_step * args.pre_obs_norm_steps):\n actions = np.random.randint(0, output_size, size=(args.num_worker,))\n\n for parent_conn, action in zip(parent_conns, actions):\n parent_conn.send(action)\n\n for parent_conn in parent_conns:\n next_state, reward, done, realdone, log_reward = parent_conn.recv()\n next_obs.append(next_state[3, :, :].reshape([1, 84, 84]))\n\n if len(next_obs) % (args.num_step * args.num_worker) == 0:\n next_obs = np.stack(next_obs)\n obs_rms.update(next_obs)\n next_obs = []\n\n print('Training...')\n while True:\n total_state, total_reward, total_done, total_next_state, total_action, total_int_reward, total_next_obs, total_ext_values, total_int_values, total_action_probs = [], [], [], [], [], [], [], [], [], []\n global_step += (args.num_worker * args.num_step)\n global_update += 1\n\n # Step 1. n-step rollout\n for _ in range(args.num_step):\n actions, value_ext, value_int, action_probs = get_action(model, device, np.float32(states) / 255.)\n\n for parent_conn, action in zip(parent_conns, actions):\n parent_conn.send(action)\n\n next_states, rewards, dones, real_dones, log_rewards, next_obs = [], [], [], [], [], []\n for parent_conn in parent_conns:\n next_state, reward, done, real_done, log_reward = parent_conn.recv()\n next_states.append(next_state)\n rewards.append(reward)\n dones.append(done)\n real_dones.append(real_done)\n log_rewards.append(log_reward)\n next_obs.append(next_state[3, :, :].reshape([1, 84, 84]))\n\n next_states = np.stack(next_states)\n rewards = np.hstack(rewards)\n dones = np.hstack(dones)\n real_dones = np.hstack(real_dones)\n next_obs = np.stack(next_obs)\n\n # total reward = int reward + ext Reward\n intrinsic_reward = compute_intrinsic_reward(rnd, device,\n ((next_obs - obs_rms.mean) / np.sqrt(obs_rms.var)).clip(-5, 5))\n intrinsic_reward = np.hstack(intrinsic_reward)\n sample_i_rall += intrinsic_reward[sample_env_index]\n\n #put in replay buffer\n sil.step(next_states, actions, rewards, dones)\n\n total_next_obs.append(next_obs)\n total_int_reward.append(intrinsic_reward)\n total_state.append(states)\n total_reward.append(rewards)\n total_done.append(dones)\n total_action.append(actions)\n total_ext_values.append(value_ext)\n total_int_values.append(value_int)\n total_action_probs.append(action_probs)\n\n states = next_states[:, :, :, :]\n\n sample_rall += log_rewards[sample_env_index]\n\n sample_step += 1\n if real_dones[sample_env_index]:\n sample_episode += 1\n writer.add_scalar('data/reward_per_epi', sample_rall, sample_episode)\n writer.add_scalar('data/reward_per_rollout', sample_rall, global_update)\n writer.add_scalar('data/step', sample_step, sample_episode)\n sample_rall = 0\n sample_step = 0\n sample_i_rall = 0\n\n # calculate last next value\n _, value_ext, value_int, _ = get_action(model, device, np.float32(states) / 255.)\n total_ext_values.append(value_ext)\n total_int_values.append(value_int)\n # --------------------------------------------------\n\n total_state = np.stack(total_state).transpose([1, 0, 2, 3, 4]).reshape([-1, 4, 84, 84])\n total_reward = np.stack(total_reward).transpose().clip(-1, 1)\n total_action = np.stack(total_action).transpose().reshape([-1])\n total_done = np.stack(total_done).transpose()\n total_next_obs = np.stack(total_next_obs).transpose([1, 0, 2, 3, 4]).reshape([-1, 1, 84, 84])\n total_ext_values = np.stack(total_ext_values).transpose()\n total_int_values = np.stack(total_int_values).transpose()\n total_logging_action_probs = np.vstack(total_action_probs)\n\n # Step 2. calculate intrinsic reward\n # running mean intrinsic reward\n total_int_reward = np.stack(total_int_reward).transpose()\n total_reward_per_env = np.array([discounted_reward.update(reward_per_step) for reward_per_step in total_int_reward.T])\n mean, std, count = np.mean(total_reward_per_env), np.std(total_reward_per_env), len(total_reward_per_env)\n reward_rms.update_from_moments(mean, std ** 2, count)\n\n # normalize intrinsic reward\n total_int_reward /= np.sqrt(reward_rms.var)\n writer.add_scalar('data/int_reward_per_epi', np.sum(total_int_reward) / args.num_worker, sample_episode)\n writer.add_scalar('data/int_reward_per_rollout', np.sum(total_int_reward) / args.num_worker, global_update)\n # -------------------------------------------------------------------------------------------\n\n # logging Max action probability\n writer.add_scalar('data/max_prob', total_logging_action_probs.max(1).mean(), sample_episode)\n\n # Step 3. make target and advantage\n # extrinsic reward calculate\n ext_target, ext_adv = make_train_data(total_reward,\n total_done,\n total_ext_values,\n args.ext_gamma,\n args.gae_lambda,\n args.num_step,\n args.num_worker,\n args.use_gae)\n\n # intrinsic reward calculate\n # None Episodic\n int_target, int_adv = make_train_data(total_int_reward,\n np.zeros_like(total_int_reward),\n total_int_values,\n args.int_gamma,\n args.gae_lambda,\n args.num_step,\n args.num_worker,\n args.use_gae)\n\n # add ext adv and int adv\n total_adv = int_adv * args.int_coef + ext_adv * args.ext_coef\n # -----------------------------------------------\n\n # Step 4. update obs normalize param\n obs_rms.update(total_next_obs)\n # -----------------------------------------------\n # Step 5. Training!\n train_model(args, device, output_size, model, rnd, optimizer,\n np.float32(total_state) / 255., ext_target, int_target, total_action,\n total_adv, ((total_next_obs - obs_rms.mean) / np.sqrt(obs_rms.var)).clip(-5, 5),\n total_action_probs)\n\n #SIL train\n total_valid_samples = sil.train()\n print('total valid samples:', total_valid_samples)\n\n\n if global_step % (args.num_worker * args.num_step * args.save_interval) == 0:\n print('Now Global Step :{}'.format(global_step))\n torch.save(model.state_dict(), model_path)\n torch.save(rnd.predictor.state_dict(), predictor_path)\n torch.save(rnd.target.state_dict(), target_path)\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"numpy.sqrt",
"torch.load",
"numpy.zeros_like",
"torch.no_grad",
"torch.FloatTensor",
"numpy.mean",
"torch.device",
"numpy.random.randint",
"numpy.hstack",
"numpy.stack",
"numpy.std",
"numpy.float32",
"numpy.zeros",
"torch.LongTensor",
"torch.min",
"torch.exp",
"torch.stack",
"torch.multiprocessing.Pipe",
"numpy.sum",
"torch.distributions.categorical.Categorical",
"torch.Tensor",
"numpy.random.shuffle",
"numpy.empty",
"torch.clamp",
"torch.nn.MSELoss",
"numpy.vstack"
]
] |
Vaibhavs10/jax
|
[
"c9d8acd2e921efdbc01b2208fa9f790a9c312933"
] |
[
"tests/infeed_test.py"
] |
[
"# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport threading\n\nfrom absl.testing import absltest\nimport jax\nfrom jax import lax, numpy as jnp\nfrom jax.config import config\nfrom jax.experimental import host_callback as hcb\nfrom jax.lib import xla_client\nimport jax.test_util as jtu\nimport numpy as np\n\nconfig.parse_flags_with_absl()\nFLAGS = config.FLAGS\n\nclass InfeedTest(jtu.JaxTestCase):\n\n def testInfeed(self):\n @jax.jit\n def f(x):\n token = lax.create_token(x)\n (y,), token = lax.infeed(\n token, shape=(jax.ShapedArray((3, 4), jnp.float32),))\n (z,), _ = lax.infeed(\n token, shape=(jax.ShapedArray((3, 1, 1), jnp.float32),))\n return x + y + z\n\n x = np.float32(1.5)\n y = np.reshape(np.arange(12, dtype=np.float32), (3, 4)) # np.random.randn(3, 4).astype(np.float32)\n z = np.random.randn(3, 1, 1).astype(np.float32)\n device = jax.local_devices()[0]\n device.transfer_to_infeed((y,))\n device.transfer_to_infeed((z,))\n self.assertAllClose(f(x), x + y + z)\n\n def testInfeedThenOutfeed(self):\n hcb.stop_outfeed_receiver()\n @jax.jit\n def f(x):\n token = lax.create_token(x)\n y, token = lax.infeed(\n token, shape=jax.ShapedArray((3, 4), jnp.float32))\n token = lax.outfeed(token, y + np.float32(1))\n return lax.tie_in(token, x - 1)\n\n x = np.float32(7.5)\n y = np.random.randn(3, 4).astype(np.float32)\n execution = threading.Thread(target=lambda: f(x))\n execution.start()\n device = jax.local_devices()[0]\n device.transfer_to_infeed((y,))\n out, = device.transfer_from_outfeed(\n xla_client.shape_from_pyval((y,)).with_major_to_minor_layout_if_absent())\n execution.join()\n self.assertAllClose(out, y + np.float32(1))\n\n def testInfeedThenOutfeedInALoop(self):\n hcb.stop_outfeed_receiver()\n def doubler(_, token):\n y, token = lax.infeed(\n token, shape=jax.ShapedArray((3, 4), jnp.float32))\n return lax.outfeed(token, y * np.float32(2))\n\n @jax.jit\n def f(n):\n token = lax.create_token(n)\n token = lax.fori_loop(0, n, doubler, token)\n return lax.tie_in(token, n)\n\n device = jax.local_devices()[0]\n n = 10\n execution = threading.Thread(target=lambda: f(n))\n execution.start()\n for _ in range(n):\n x = np.random.randn(3, 4).astype(np.float32)\n device.transfer_to_infeed((x,))\n y, = device.transfer_from_outfeed(xla_client.shape_from_pyval((x,))\n .with_major_to_minor_layout_if_absent())\n self.assertAllClose(y, x * np.float32(2))\n execution.join()\n\n\nif __name__ == '__main__':\n absltest.main(testLoader=jtu.JaxTestLoader())\n"
] |
[
[
"numpy.arange",
"numpy.random.randn",
"numpy.float32"
]
] |
AntixK/Ezhil
|
[
"0ed84901852e37cd3cc5ac72cf828642caa35b8d"
] |
[
"kivy/c4.py"
] |
[
"try:\n import numpy as np\nexcept ImportError:\n print(\"Sorry, this example requires Numpy installed !\")\n raise\n\nfrom easyAI import TwoPlayersGame\n\n\nclass ConnectFour(TwoPlayersGame):\n \"\"\"\n The game of Connect Four, as described here:\n http://en.wikipedia.org/wiki/Connect_Four\n \"\"\"\n\n def __init__(self, players, board = None):\n self.players = players\n self.board = board if (board != None) else (\n np.array([[0 for i in range(7)] for j in range(6)]))\n self.nplayer = 1 # player 1 starts.\n\n def possible_moves(self):\n return [i for i in range(7) if (self.board[:, i].min() == 0)]\n\n def make_move(self, column):\n line = np.argmin(self.board[:, column] != 0)\n self.board[line, column] = self.nplayer\n\n def show(self):\n print('\\n' + '\\n'.join(\n ['0 1 2 3 4 5 6', 13 * '-'] +\n [' '.join([['.', 'O', 'X'][self.board[5 - j][i]]\n for i in range(7)]) for j in range(6)]))\n\n def lose(self):\n return find_four(self.board, self.nopponent)\n\n def is_over(self):\n return (self.board.min() > 0) or self.lose()\n\n def scoring(self):\n return -100 if self.lose() else 0\n\n\ndef find_four(board, nplayer):\n \"\"\"\n Returns True iff the player has connected 4 (or more)\n This is much faster if written in C or Cython\n \"\"\"\n for pos, direction in POS_DIR:\n streak = 0\n while (0 <= pos[0] <= 5) and (0 <= pos[1] <= 6):\n if board[pos[0], pos[1]] == nplayer:\n streak += 1\n if streak == 4:\n return True\n else:\n streak = 0\n pos = pos + direction\n return False\n\n\nPOS_DIR = np.array([[[i, 0], [0, 1]] for i in range(6)] +\n [[[0, i], [1, 0]] for i in range(7)] +\n [[[i, 0], [1, 1]] for i in range(1, 3)] +\n [[[0, i], [1, 1]] for i in range(4)] +\n [[[i, 6], [1, -1]] for i in range(1, 3)] +\n [[[0, i], [1, -1]] for i in range(3, 7)])\n\nif __name__ == '__main__':\n # LET'S PLAY !\n\n from easyAI import Human_Player, AI_Player, Negamax, SSS, DUAL\n\n ai_algo_neg = Negamax(5)\n ai_algo_sss = SSS(5)\n game = ConnectFour([AI_Player(ai_algo_neg), AI_Player(ai_algo_sss)])\n game.play()\n if game.lose():\n print(\"Player %d wins.\" % (game.nopponent))\n else:\n print(\"Looks like we have a draw.\")"
] |
[
[
"numpy.argmin"
]
] |
Max-Coy/Physics5CLSpring2022
|
[
"ff2b4a431027569f3d6ec604819fdbb88b03bafc"
] |
[
"Lab 6/Experiment 1 and 4 Analysis.py"
] |
[
"import matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.optimize as opt\nimport math\nimport csv\n\n\ndef sample_stdev(data):\n return np.std(data, ddof = 1, axis = -1)\n\n\ndef standard_error(data):\n return sample_stdev(data) / np.sqrt(len(data) if data.ndim == 1 else len(data[0]))\n\n\ndef data_statistics(data):\n return np.mean(data), sample_stdev(data), standard_error(data)\n\n\ndef covariance(x, y):\n x_bar = np.mean(x)\n y_bar = np.mean(y)\n covariance = 0\n for i in range(len(x)):\n covariance += (x[i] - x_bar) * (y[i] - y_bar)\n\n return covariance / (len(x) - 1.0)\n\n\ndef correlation_coefficient(x, y):\n return covariance(x, y) / np.sqrt((covariance(x, x) * covariance(y, y)))\n\n\ndef chi_squared(predicted, observed, errors):\n res = observed - predicted\n norm_res = res / errors\n return np.sum(np.multiply(norm_res, norm_res))\n\n\nclass WeightedLinearFit(object):\n def __init__(self, x, y, alpha = None):\n self.x = x\n self.y = y\n self.alpha = alpha\n\n self.has_optimized = False\n\n self.linear_model = None\n self.m = 0\n self.c = 0\n self.m_err = 0\n self.c_err = 0\n\n @staticmethod\n def linear_fit(x, m, c):\n return m * x + c\n\n def optimize(self, guess = [0, 0]):\n if self.alpha is not None:\n self.linear_model = opt.curve_fit(WeightedLinearFit.linear_fit, self.x, self.y, sigma = self.alpha, p0 = guess)\n else:\n self.linear_model = opt.curve_fit(WeightedLinearFit.linear_fit, self.x, self.y)\n self.m = self.linear_model[0][0]\n self.c = self.linear_model[0][1]\n self.m_err = np.sqrt(self.linear_model[1][0][0])\n self.c_err = np.sqrt(self.linear_model[1][1][1])\n self.has_optimized = True\n\n def calculate(self, x):\n if self.has_optimized:\n return self.m * x + self.c\n\n raise Exception('Need to optimize model first.')\n\n\nclass Data(object):\n def __init__(self, data, precision_error = 0.05, offset = 0.0):\n self.data = np.array(data) - offset\n self.precision_error = precision_error\n self.average = 0\n self.standard_deviation = 0\n self.standard_error = 0\n self.compute_statistics()\n\n def compute_statistics(self):\n #self.average = np.mean(self.data, axis = -1)\n self.average = []\n self.standard_deviation = []\n self.standard_error = []\n for i in range(len(self.data)):\n self.average.append(np.mean(self.data[i]))\n self.standard_deviation.append(sample_stdev(self.data[i]))\n self.standard_error.append(standard_error(self.data[i]))\n\n self.average = np.array(self.average)\n self.standard_deviation = np.array(self.standard_deviation)\n self.standard_error = np.array(self.standard_error)\n #self.standard_deviation = sample_stdev(self.data)\n #self.standard_error = standard_error(self.data)\n for i in range(len(self.standard_error)):\n if self.standard_error[i] == 0:\n self.standard_error[i] = self.precision_error\n\n def invert_data(self):\n inverted_data = Data(1.0 / self.data, self.precision_error)\n inverted_data.standard_error = -self.standard_error / (self.average * self.average)\n return inverted_data\n\n def covariance(self, other):\n return covariance(self.data, other.data)\n\n\nclass HeatConduction(object):\n def __init__(self, Tbath, T0, L, kappa, rho, c, N):\n self.alpha = kappa / (rho * c)\n self.Tbath = Tbath\n self.T0 = T0\n self.L = L\n self.N = N\n\n def summation_term(self, n, t):\n sign = 1.0 if n % 2 == 0 else -1.0\n k = math.pi * (n + 1.0 / 2.0) / self.L\n return 4.0 * sign * (math.exp(-self.alpha * k * k * t)) / (math.pi * (2.0 * n + 1.0))\n\n def endpoint_temperature(self, t):\n temperature = self.Tbath\n for i in range(self.N):\n temperature += (self.T0 - self.Tbath) * self.summation_term(i, t)\n\n return temperature\n\n\nclass HeatConductionFit(object):\n def __init__(self, t, T, Tbath, T0, L, rho, c, N):\n self.t = t\n self.T = T\n\n self.Tbath = Tbath\n self.T0 = T0\n self.L = L\n self.rho = rho\n self.c = c\n self.N = N\n\n self.kappa = 0.07\n self.kappa_err = 0\n self.t0 = 0\n self.t0_err = 0\n\n self.model = None\n\n def summation_term(self, alpha, n, t, t0):\n sign = 1.0 if n % 2 == 0 else -1.0\n k = math.pi * (n + 1.0 / 2.0) / self.L\n return 4.0 * sign * (np.exp(-alpha * k * k * (t - t0))) / (math.pi * (2.0 * n + 1.0))\n\n def endpoint_temperature(self, t, t0, kappa):\n temperature = self.Tbath\n for i in range(self.N):\n temperature += (self.T0 - self.Tbath) * self.summation_term(kappa / (self.rho * self.c), i, t, t0)\n\n return temperature\n\n def optimize(self, guess = [0]):\n self.model = opt.curve_fit(self.endpoint_temperature, self.t, self.T, p0 = guess,\n bounds = ([0, 0.1]))\n self.kappa = self.model[0][0]\n #self.t0 = self.model[0][1]\n self.kappa_err = np.sqrt(self.model[1][0][0])\n #self.t0_err = np.sqrt(self.model[1][1][1])\n\n def calculate(self, t):\n return self.endpoint_temperature(t, self.t0, self.kappa / (self.rho * self.c))\n\n def compute_cost(self, kappa, t0):\n return np.sqrt(np.mean(np.power(self.T - self.endpoint_temperature(self.t, t0, kappa / (self.rho * self.c)), 2)))\n\n\ndef read_data(filename):\n K = 273.15\n times = []\n temperatures = []\n with open(filename) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter = ',')\n next(csv_reader)\n for row in csv_reader:\n times.append(float(row[0]))\n temperatures.append(float(row[1]) + K)\n\n return np.array([times, temperatures])\n\n\n# --------------------- Experiment 1 ---------------------\nK = 273.15\nhot_mass = np.array([207, 146, 217, 211]) # grams\nhot_temperature = np.array([47.5, 47.2, 47.6, 47.4]) # Kelvin\ncold_mass = np.array([129, 209, 172, 193])\ncold_temperature = np.array([17.5, 17.4, 17.4, 17.4])\nequilibrium_temperature = np.array([35.7, 29.7, 34.2, 33.0])\n\nmass_precision_error = 1.0 # g\ntemperature_precision_error = 0.1 # g\n\nnumerator = hot_mass * hot_temperature + cold_mass * cold_temperature\ndenominator = cold_mass + hot_mass\nequilibrium_temperature_theory = numerator / denominator\nequilibrium_temperature_error = np.sqrt((mass_precision_error * hot_temperature / denominator) ** 2 +\n (mass_precision_error * cold_temperature / denominator) ** 2 +\n 2.0 * (mass_precision_error * numerator / (denominator ** 2)) ** 2 +\n (temperature_precision_error * hot_mass / denominator) ** 2 +\n (temperature_precision_error * cold_mass / denominator) ** 2)\n\nchi = chi_squared(equilibrium_temperature_theory, equilibrium_temperature, equilibrium_temperature_error)\nreduced_chi = chi / 3.0\n\nprint(equilibrium_temperature)\nprint(equilibrium_temperature_theory)\nprint(equilibrium_temperature_error)\nprint(chi, reduced_chi)\n\n\n# --------------------- Experiment 4 ---------------------\nK = 273.15\ncan_height = 7.1 # cm\n\n# Brass\nbrass_density = 8.73 # g / cm^3\nbrass_specific_heat = 0.38 # J / g * K\n\nbrass_depth = 4.0 # cm\ninitial_cold_bath_temperature_brass = 0.7 + K # K\ninitial_brass_temperature = 27.1 + K # K\nprobe_depth = 3.4 # cm\nbrass_length = 20.5 # cm\nbrass_effective_length = brass_length - probe_depth - brass_depth\n\n# Copper\ncopper_density = 8.96 # g / cm^3\ncopper_specific_heat = 0.385 # J / g * K\n\ncopper_depth = 3.5 # cm\ninitial_cold_bath_temperature_copper = 0.3 + K\ninitial_copper_temperature = 24.0 + K\nprobe_depth = 3.4 # cm\ncopper_length = 20.5 # cm\ncopper_effective_length = copper_length - probe_depth - copper_depth\n\n# Aluminum\naluminum_thermal_conductivity = 2.05 # W / cm * K\naluminum_density = 2.7 # g / cm^3\naluminum_specific_heat = 0.89 # J / g * K\n\ninitial_aluminum_temperature = 25.5 + K\ninitial_cold_bath_temperature_aluminum = 0.6 + K\naluminum_depth = 4.5 # cm\nprobe_depth = 3.4 # cm\naluminum_length = 20.5 # cm\naluminum_effective_length = aluminum_length - aluminum_length - probe_depth\n\nbrass_data = read_data('brass_rod.csv')\ncopper_data = read_data('copper_rod.csv')\naluminum_data = read_data('aluminum_rod.csv')\ninitial_brass_temperature = brass_data[1][0]\ninitial_copper_temperature = copper_data[1][0]\ninitial_aluminum_temperature = aluminum_data[1][0]\n\nbrass_fit = HeatConductionFit(brass_data[0], brass_data[1], initial_cold_bath_temperature_brass, initial_brass_temperature,\n brass_effective_length, brass_density, brass_specific_heat, 100)\ncopper_fit = HeatConductionFit(copper_data[0], copper_data[1], initial_cold_bath_temperature_copper, initial_copper_temperature,\n copper_effective_length, copper_density, copper_specific_heat, 100)\naluminum_fit = HeatConductionFit(aluminum_data[0], aluminum_data[1], initial_cold_bath_temperature_aluminum, initial_aluminum_temperature,\n aluminum_effective_length, aluminum_density, aluminum_specific_heat, 100)\n\nn = 1000\nmax_val = 3\nm = 1\nmax_t0 = 0\nkappas = []\nt0s = []\nbrass_costs = []\ncopper_costs = []\naluminum_costs = []\nfor i in range(n):\n for j in range(m):\n kappa = max_val * i / n\n t0 = max_t0 * j / m\n kappas.append(kappa)\n t0s.append(t0)\n brass_costs.append(brass_fit.compute_cost(kappa, t0))\n copper_costs.append(copper_fit.compute_cost(kappa, t0))\n aluminum_costs.append(aluminum_fit.compute_cost(kappa, t0))\n\nbrass_kappa_optimal = kappas[brass_costs.index(min(brass_costs))]\n#brass_t0_optimal = t0s[brass_costs.index(min(brass_costs))]\nprint(brass_kappa_optimal, min(brass_costs) / len(brass_data[0]))\n#print(brass_t0_optimal, min(brass_costs) / len(brass_data[0]))\n\ncopper_kappa_optimal = kappas[copper_costs.index(min(copper_costs))]\nprint(copper_kappa_optimal, min(copper_costs) / len(copper_data[0]))\n\naluminum_kappa_optimal = kappas[aluminum_costs.index(min(aluminum_costs))]\nprint(aluminum_kappa_optimal, min(aluminum_costs) / len(aluminum_data[0]))\n\nbrass_fit.kappa = brass_kappa_optimal\nT_brass = brass_fit.calculate(brass_data[0])\n\ncopper_fit.kappa = copper_kappa_optimal\nT_copper = copper_fit.calculate(copper_data[0])\n\naluminum_fit.kappa = aluminum_kappa_optimal\nT_aluminum = aluminum_fit.calculate(aluminum_data[0])\n\nplt.figure()\nplt.title('Temperature RMS Error vs. Thermal Conductivity of Brass')\nplt.xlabel('Thermal Conductivity of Brass ($\\\\kappa$)')\nplt.ylabel('Temperature RMS Error (K)')\nplt.plot(kappas, brass_costs)\n\nplt.figure()\nplt.title('Temperature RMS Error vs. Thermal Conductivity of Copper')\nplt.xlabel('Thermal Conductivity of Copper ($\\\\kappa$)')\nplt.ylabel('Temperature RMS Error (K)')\nplt.plot(kappas, copper_costs)\n\nplt.figure()\nplt.title('Temperature RMS Error vs. Thermal Conductivity of Aluminum')\nplt.xlabel('Thermal Conductivity of Aluminum ($\\\\kappa$)')\nplt.ylabel('Temperature RMS Error (K)')\nplt.plot(kappas, aluminum_costs)\n\nplt.figure()\nplt.title('Brass Rod Heat Conduction Temperature vs. Time')\nplt.xlabel('Time (s)')\nplt.ylabel('Temperature (K)')\nplt.text(0, 287.5, \"$\\\\kappa$ = %5.4f \\u00b1 %5.4f $\\\\frac{W}{cm\\\\cdot K}$\" % (brass_kappa_optimal, min(brass_costs) / len(brass_data[0])))\nplt.plot(brass_data[0], T_brass, label = 'Heat Conduction Model')\nplt.plot(brass_data[0], brass_data[1], label = 'Experimental Data')\nplt.legend()\n\nplt.figure()\nplt.title('Copper Rod Heat Conduction Temperature vs. Time')\nplt.xlabel('Time (s)')\nplt.ylabel('Temperature (K)')\nplt.text(0, 287, \"$\\\\kappa$ = %5.4f \\u00b1 %5.4f $\\\\frac{W}{cm\\\\cdot K}$\" % (copper_kappa_optimal, min(copper_costs) / len(copper_data[0])))\nplt.plot(copper_data[0], T_copper, label = 'Heat Conduction Model')\nplt.plot(copper_data[0], copper_data[1], label = 'Experimental Data')\nplt.legend()\n\nplt.figure()\nplt.title('Aluminum Rod Heat Conduction Temperature vs. Time')\nplt.xlabel('Time (s)')\nplt.ylabel('Temperature (K)')\nplt.text(0, 285, \"$\\\\kappa$ = %5.4f \\u00b1 %5.4f $\\\\frac{W}{cm\\\\cdot K}$\" % (aluminum_kappa_optimal, min(aluminum_costs) / len(aluminum_data[0])))\nplt.plot(aluminum_data[0], T_aluminum, label = 'Heat Conduction Model')\nplt.plot(aluminum_data[0], aluminum_data[1], label = 'Experimental Data')\nplt.legend()\nplt.show()\n\n"
] |
[
[
"matplotlib.pyplot.legend",
"numpy.sqrt",
"matplotlib.pyplot.title",
"numpy.multiply",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylabel",
"numpy.std",
"numpy.mean",
"numpy.exp",
"matplotlib.pyplot.xlabel",
"numpy.array",
"scipy.optimize.curve_fit",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
joselusl/ars_sim_mapper
|
[
"6d216c0e5e9916203a1dbba167130b25f0dc464d"
] |
[
"source/ars_sim_mapper_ros.py"
] |
[
"#!/usr/bin/env python\n\nimport numpy as np\nfrom numpy import *\n\nimport os\n\nimport copy\n\n\n\n\n# ROS\n\nimport rospy\n\nimport rospkg\n\nimport std_msgs.msg\nfrom std_msgs.msg import Header\n\n\nimport geometry_msgs.msg\nfrom geometry_msgs.msg import PoseStamped\n\nimport visualization_msgs.msg\nfrom visualization_msgs.msg import Marker\nfrom visualization_msgs.msg import MarkerArray\n\n\n\nimport tf_conversions\n\nimport tf2_ros\n\n\n\n\n#\nimport ars_lib_helpers\n\n\n\n\n\nclass ArsSimMapperRos:\n\n #######\n\n # Robot frame\n world_frame = None\n\n # Covariance on mapping of position\n cov_map_stat_pos = None\n cov_map_dyna_pos = None\n\n # Covariance on mapping of sizes\n cov_map_stat_siz = None\n cov_map_dyna_siz = None\n\n # Robot pose subscriber\n robot_pose_sub = None\n\n # Obstacles static sub\n obstacles_static_sub = None\n \n # Obstacles dynamic sub\n obstacles_dynamic_sub = None\n\n # Obstacles detected pub\n flag_pub_obstacles_detected_world = False\n obstacles_detected_world_pub = None\n\n # Obstacles static\n obstacles_static_msg = None\n\n # Obstacles dynamic\n obstacles_dynamic_msg = None\n\n # Obstacles detected\n obstacles_detected_world_msg = None\n\n # Obstacle Detection loop\n # freq\n obstacle_detect_loop_freq = None\n # Timer\n obstacle_detect_loop_timer = None\n \n\n\n #########\n\n def __init__(self):\n\n # Robot frame\n self.world_frame = 'world'\n\n\n # Covariance on mapping of position\n self.cov_map_stat_pos = {'x': 0.0001, 'y': 0.0001, 'z': 0.000001}\n self.cov_map_dyna_pos = {'x': 0.01, 'y': 0.01, 'z': 0.00001}\n\n # Covariance on mapping of sizes\n self.cov_map_stat_siz = {'R': 0.0001, 'h': 0.000001}\n self.cov_map_dyna_siz = {'R': 0.01, 'h': 0.0001}\n\n #\n self.obstacles_static_msg = MarkerArray()\n\n #\n self.obstacles_dynamic_msg = MarkerArray()\n\n #\n self.obstacles_detected_world_msg = MarkerArray()\n\n # Obstacle Detection loop\n # freq\n self.obstacle_detect_loop_freq = 0.1\n # Timer\n self.obstacle_detect_loop_timer = None\n\n\n # end\n return\n\n\n def init(self, node_name='ars_sim_mapper_node'):\n #\n\n # Init ROS\n rospy.init_node(node_name, anonymous=True)\n\n \n # Package path\n pkg_path = rospkg.RosPack().get_path('ars_sim_mapper')\n \n\n #### READING PARAMETERS ###\n \n # TODO\n\n ###\n\n\n \n # End\n return\n\n\n def open(self):\n\n\n # Subscribers\n \n # \n self.obstacles_static_sub = rospy.Subscriber('obstacles_static', MarkerArray, self.obstaclesStaticCallback, queue_size=1)\n #\n self.obstacles_dynamic_sub = rospy.Subscriber('obstacles_dynamic', MarkerArray, self.obstaclesDynamicCallback, queue_size=1)\n\n\n # Publishers\n\n # \n self.obstacles_detected_world_pub = rospy.Publisher('estim_map_world', MarkerArray, queue_size=1, latch=True)\n\n\n\n # Timers\n #\n self.obstacle_detect_loop_timer = rospy.Timer(rospy.Duration(1.0/self.obstacle_detect_loop_freq), self.obstacleDetectorLoopTimerCallback)\n\n\n # End\n return\n\n\n def run(self):\n\n rospy.spin()\n\n return\n\n\n def obstaclesStaticCallback(self, obstacles_static_msg):\n\n self.obstacles_static_msg = obstacles_static_msg\n\n #\n return\n\n\n def obstaclesDynamicCallback(self, obstacles_dynamic_msg):\n\n self.obstacles_dynamic_msg = obstacles_dynamic_msg\n\n #\n return\n\n\n def detectObstacles(self):\n\n #\n self.obstacles_detected_world_msg = MarkerArray()\n self.obstacles_detected_world_msg.markers = []\n\n\n # Obstacles static\n for obst_i_msg in self.obstacles_static_msg.markers:\n\n if(obst_i_msg.action == 0):\n\n # Check distance\n if(obst_i_msg.type == 3):\n\n obst_i_posi_world = np.zeros((3,), dtype=float)\n obst_i_posi_world[0] = obst_i_msg.pose.position.x\n obst_i_posi_world[1] = obst_i_msg.pose.position.y\n obst_i_posi_world[2] = obst_i_msg.pose.position.z\n\n obst_i_rad = obst_i_msg.scale.x/2.0\n\n \n # Noises\n #\n posi_noise = np.zeros((3,), dtype=float)\n posi_noise[0] = np.random.normal(loc = 0.0, scale = math.sqrt(self.cov_map_stat_pos['x']))\n posi_noise[1] = np.random.normal(loc = 0.0, scale = math.sqrt(self.cov_map_stat_pos['y']))\n posi_noise[2] = np.random.normal(loc = 0.0, scale = math.sqrt(self.cov_map_stat_pos['z']))\n #\n radius_noise = np.random.normal(loc = 0.0, scale = math.sqrt(self.cov_map_stat_siz['R']))\n height_noise = np.random.normal(loc = 0.0, scale = math.sqrt(self.cov_map_stat_siz['h']))\n \n\n\n ############\n # obstacle wrt World \n obst_i_world_msg = []\n obst_i_world_msg = copy.deepcopy(obst_i_msg)\n\n # Change color\n obst_i_world_msg.color.r = 0.0\n obst_i_world_msg.color.g = 0.0\n obst_i_world_msg.color.b = 1.0\n obst_i_world_msg.color.a = 0.6\n\n # Lifetime\n obst_i_world_msg.lifetime = rospy.Duration(2.0*1.0/self.obstacle_detect_loop_freq)\n\n #\n obst_i_world_msg.pose.position.x = obst_i_posi_world[0] + posi_noise[0]\n obst_i_world_msg.pose.position.y = obst_i_posi_world[1] + posi_noise[1]\n obst_i_world_msg.pose.position.z = obst_i_posi_world[2] + posi_noise[2]\n\n # Sizes with noise\n obst_i_world_msg.scale.x += 2.0*radius_noise\n obst_i_world_msg.scale.y += 2.0*radius_noise\n obst_i_world_msg.scale.z += height_noise\n\n\n # Append world\n self.obstacles_detected_world_msg.markers.append(obst_i_world_msg)\n\n\n else:\n print(\"Unknown obstacle type:\"+obst_i_msg.type)\n\n\n\n # Obstacles dynamic\n for obst_i_msg in self.obstacles_dynamic_msg.markers:\n\n if(obst_i_msg.action == 0):\n\n # Check distance\n if(obst_i_msg.type == 3):\n\n obst_i_posi_world = np.zeros((3,), dtype=float)\n obst_i_posi_world[0] = obst_i_msg.pose.position.x\n obst_i_posi_world[1] = obst_i_msg.pose.position.y\n obst_i_posi_world[2] = obst_i_msg.pose.position.z\n\n obst_i_rad = obst_i_msg.scale.x/2.0\n\n \n # Noises\n #\n posi_noise = np.zeros((3,), dtype=float)\n posi_noise[0] = np.random.normal(loc = 0.0, scale = math.sqrt(self.cov_map_dyna_pos['x']))\n posi_noise[1] = np.random.normal(loc = 0.0, scale = math.sqrt(self.cov_map_dyna_pos['y']))\n posi_noise[2] = np.random.normal(loc = 0.0, scale = math.sqrt(self.cov_map_dyna_pos['z']))\n #\n radius_noise = np.random.normal(loc = 0.0, scale = math.sqrt(self.cov_map_dyna_siz['R']))\n height_noise = np.random.normal(loc = 0.0, scale = math.sqrt(self.cov_map_dyna_siz['h']))\n \n\n ############\n # obstacle wrt World \n obst_i_world_msg = []\n obst_i_world_msg = copy.deepcopy(obst_i_msg)\n\n # Change color\n obst_i_world_msg.color.r = 0.0\n obst_i_world_msg.color.g = 0.0\n obst_i_world_msg.color.b = 1.0\n obst_i_world_msg.color.a = 0.6\n\n # Lifetime\n obst_i_world_msg.lifetime = rospy.Duration(2.0*1.0/self.obstacle_detect_loop_freq)\n\n #\n obst_i_world_msg.pose.position.x = obst_i_posi_world[0] + posi_noise[0]\n obst_i_world_msg.pose.position.y = obst_i_posi_world[1] + posi_noise[1]\n obst_i_world_msg.pose.position.z = obst_i_posi_world[2] + posi_noise[2]\n\n # Sizes with noise\n obst_i_world_msg.scale.x += 2.0*radius_noise\n obst_i_world_msg.scale.y += 2.0*radius_noise\n obst_i_world_msg.scale.z += height_noise\n\n\n \n\n # Append world\n self.obstacles_detected_world_msg.markers.append(obst_i_world_msg)\n\n \n\n else:\n print(\"Unknown obstacle type!!\")\n\n\n # Publish\n self.obstacles_detected_world_pub.publish(self.obstacles_detected_world_msg)\n\n #\n return\n\n\n def obstacleDetectorLoopTimerCallback(self, timer_msg):\n\n # Get time\n time_stamp_current = rospy.Time.now()\n\n #\n self.detectObstacles()\n\n #\n return\n"
] |
[
[
"numpy.zeros"
]
] |
Daya-Jin/-
|
[
"28787974c40f5c3c151b1c4a567a7eb6c51604ba"
] |
[
"6. catboost.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 6 16:45:27 2018\n@author: wzy\n\"\"\"\nimport pandas as pd\nimport copy\nimport numpy as np\nfrom math import isnan\nimport catboost as cb\nfrom catboost import Pool\n\ntrain = pd.read_csv('data/train.csv')\ntest = pd.read_csv('data/test.csv')\n\n# 房屋朝向的汉字编码处理\ntrain_vec = copy.deepcopy(train['房屋朝向'])\ntrain_vec_dic = list(set(train_vec))\nnum_train_vec_dic = len(train_vec_dic)\nencode_train_vec_dic = list(np.arange(num_train_vec_dic))\ndic_enc_train_vec = dict(map(lambda x, y: [x, y], train_vec_dic, encode_train_vec_dic))\nencode_train_vec = []\nfor i in train_vec:\n temp = dic_enc_train_vec[i]\n encode_train_vec.append(temp)\ntest_vec = copy.deepcopy(test['房屋朝向'])\ntest_vec_dic = list(set(test_vec))\nte_vec_new = []\nfor i in test_vec_dic:\n if i not in train_vec_dic:\n te_vec_new.append(i)\nnum_te_vec_new = len(te_vec_new)\nenc_te_vec_new = list(np.arange(num_train_vec_dic, num_train_vec_dic+num_te_vec_new))\ndic_te_vec_new = dict(map(lambda x, y: [x, y], te_vec_new, enc_te_vec_new))\ndic_te_vec = dict(dic_enc_train_vec, **dic_te_vec_new)\nencode_test_vec = []\nfor i in test_vec:\n temp = dic_te_vec[i]\n encode_test_vec.append(temp)\ntrain['房屋朝向1'] = encode_train_vec\ntest['房屋朝向1'] = encode_test_vec\ndel dic_enc_train_vec, dic_te_vec, dic_te_vec_new, enc_te_vec_new, encode_test_vec\ndel encode_train_vec, encode_train_vec_dic, i, num_te_vec_new, num_train_vec_dic\ndel te_vec_new, temp, test_vec, test_vec_dic, train_vec, train_vec_dic\n\ntrain_vec = list(copy.deepcopy(train['房屋朝向']))\ndiract = []\nfor i in train_vec:\n temp = i.split()\n temp = temp[0]\n diract.append(temp)\nDiract = []\nfor i in diract:\n if i == '南':\n temp = 0\n elif i == '东南':\n temp = 1\n elif i == '东':\n temp = 2\n elif i == '西南':\n temp = 3\n elif i == '北':\n temp = 4\n elif i == '西':\n temp = 5\n elif i == '东北':\n temp = 6\n elif i == '西北':\n temp = 7\n Diract.append(temp)\ntrain.drop('房屋朝向',axis=1, inplace=True)\ntrain['房屋朝向2'] = Diract\ndel train_vec, diract, i, temp, Diract\ntest_vec = list(copy.deepcopy(test['房屋朝向']))\ndiract = []\nfor i in test_vec:\n temp = i.split()\n temp = temp[0]\n diract.append(temp)\nDiract = []\nfor i in diract:\n if i == '南':\n temp = 0\n elif i == '东南':\n temp = 1\n elif i == '东':\n temp = 2\n elif i == '西南':\n temp = 3\n elif i == '北':\n temp = 4\n elif i == '西':\n temp = 5\n elif i == '东北':\n temp = 6\n elif i == '西北':\n temp = 7\n Diract.append(temp)\ntest.drop('房屋朝向',axis=1, inplace=True)\ntest['房屋朝向2'] = Diract\ndel test_vec, diract, i, temp, Diract\n\ntrain_subway = list(copy.deepcopy(train['地铁线路']))\ntest_subway = list(copy.deepcopy(test['地铁线路']))\nTrain_subway = []\nfor i in train_subway:\n if isnan(i):\n Train_subway.append(0)\n else:\n Train_subway.append(i)\nTest_subway = []\nfor i in test_subway:\n if isnan(i):\n Test_subway.append(0)\n else:\n Test_subway.append(i)\n\ntrain.drop('地铁线路',axis=1, inplace=True)\ntrain['地铁线路'] = Train_subway\ntest.drop('地铁线路',axis=1, inplace=True)\ntest['地铁线路'] = Test_subway\ndel Test_subway, Train_subway, i, test_subway, train_subway\n\ntrain_station = list(copy.deepcopy(train['地铁站点']))\ntest_station = list(copy.deepcopy(test['地铁站点']))\nTrain_station = []\nfor i in train_station:\n if isnan(i):\n Train_station.append(0)\n else:\n Train_station.append(i)\nTest_station = []\nfor i in test_station:\n if isnan(i):\n Test_station.append(0)\n else:\n Test_station.append(i)\ntrain.drop('地铁站点',axis=1, inplace=True)\ntrain['地铁站点'] = Train_station\ntest.drop('地铁站点',axis=1, inplace=True)\ntest['地铁站点'] = Test_station\ndel Test_station, Train_station, i, test_station, train_station\n\ntrain = train.sort_values(by=['小区名', '楼层', '时间'], ascending=(True, True, True))\ntrain_num_house = list(copy.deepcopy(train['小区房屋出租数量']))\ncount = []\nnum = len(train_num_house)\nfor i in range(num):\n if isnan(train_num_house[i]):\n count.append(count[i-1])\n else:\n count.append(train_num_house[i])\ntrain.drop('小区房屋出租数量',axis=1, inplace=True)\ntrain['小区房屋出租数量'] = count\ntest = test.sort_values(by=['小区名', '楼层', '时间'], ascending=(True, True, True))\ntest_num_house = list(copy.deepcopy(test['小区房屋出租数量']))\ncount = []\nnum = len(test_num_house)\nfor i in range(num):\n if isnan(test_num_house[i]):\n count.append(count[i-1])\n else:\n count.append(test_num_house[i])\ntest.drop('小区房屋出租数量',axis=1, inplace=True)\ntest['小区房屋出租数量'] = count\ndel count, i, num, test_num_house, train_num_house\n\ntrain_province = list(copy.deepcopy(train['区']))\ntest_province = list(copy.deepcopy(test['区']))\nTrain_province = []\nfor i in train_province:\n if isnan(i):\n Train_province.append(5)\n else:\n Train_province.append(i)\nTest_province = []\nfor i in test_province:\n if isnan(i):\n Test_province.append(5)\n else:\n Test_province.append(i)\ntrain.drop('区',axis=1, inplace=True)\ntrain['区'] = Train_province\ntest.drop('区',axis=1, inplace=True)\ntest['区'] = Test_province\ndel Test_province, Train_province, i, test_province, train_province\n\ntrain_location = list(copy.deepcopy(train['位置']))\ntest_location = list(copy.deepcopy(test['位置']))\nTrain_location = []\nfor i in train_location:\n if isnan(i):\n Train_location.append(76)\n else:\n Train_location.append(i)\nTest_location = []\nfor i in test_location:\n if isnan(i):\n Test_location.append(76)\n else:\n Test_location.append(i)\ntrain.drop('位置',axis=1, inplace=True)\ntrain['位置'] = Train_location\ntest.drop('位置',axis=1, inplace=True)\ntest['位置'] = Test_location\ndel Test_location, Train_location, i, test_location, train_location\n\ntrain_sub = []\ntrain_sub = pd.DataFrame(train_sub)\ntest_sub = []\ntest_sub = pd.DataFrame(test_sub)\ntrain_sub['小区名'] = list(copy.deepcopy(train['小区名']))\ntrain_sub['距离'] = list(copy.deepcopy(train['距离']))\ntrain_sub['地铁线路'] = list(copy.deepcopy(train['地铁线路']))\ntrain_sub['地铁站点'] = list(copy.deepcopy(train['地铁站点']))\ntest_sub['小区名'] = list(copy.deepcopy(test['小区名']))\ntest_sub['距离'] = list(copy.deepcopy(test['距离']))\ntest_sub['地铁线路'] = list(copy.deepcopy(test['地铁线路']))\ntest_sub['地铁站点'] = list(copy.deepcopy(test['地铁站点']))\ntrain_sub = pd.concat([train_sub, test_sub], ignore_index=True)\ntrain_sub = train_sub.drop_duplicates()\ntrain_sub = train_sub.sort_values(by=['小区名'], ascending=(True))\ntrain_sub = train_sub.dropna(axis=0, how='any')\ndel test_sub\ntrain_sub_name = train_sub['小区名']\ntrain_sub_dis = train_sub['距离']\ndic_name_dis = dict(map(lambda x, y: [x, y], train_sub_name, train_sub_dis))\ntrain_distance = list(copy.deepcopy(train['距离']))\ntrain_name = list(copy.deepcopy(train['小区名']))\nnum = len(train_name)\ndistance = []\nfor i in range(num):\n if (train_name[i] in dic_name_dis.keys()) and (isnan(train_distance[i])):\n distance.append(dic_name_dis[train_name[i]])\n else:\n distance.append(train_distance[i])\ntrain.drop('距离',axis=1, inplace=True)\ntrain['距离'] = distance\ntest_distance = list(copy.deepcopy(test['距离']))\ntest_name = list(copy.deepcopy(test['小区名']))\nnum = len(test_name)\ndistance = []\nfor i in range(num):\n if (test_name[i] in dic_name_dis.keys()) and (isnan(test_distance[i])):\n distance.append(dic_name_dis[test_name[i]])\n else:\n distance.append(test_distance[i])\ntest.drop('距离',axis=1, inplace=True)\ntest['距离'] = distance\ndel dic_name_dis, distance, i, num, test_distance, test_name, train_distance\ndel train_name, train_sub_dis, train_sub_name\n\ntrain_sub_name = train_sub['小区名']\ntrain_sub_subway = train_sub['地铁线路']\ndic_name_subway = dict(map(lambda x, y: [x, y], train_sub_name, train_sub_subway))\ntrain_name = list(copy.deepcopy(train['小区名']))\ntrain_subway = list(copy.deepcopy(train['地铁线路']))\nnum = len(train_name)\nsubway = []\nfor i in range(num):\n if (train_name[i] in dic_name_subway.keys()) and (train_subway[i]==0):\n subway.append(dic_name_subway[train_name[i]])\n else:\n subway.append(train_subway[i])\ntrain.drop('地铁线路',axis=1, inplace=True)\ntrain['地铁线路'] = subway\ntest_name = list(copy.deepcopy(test['小区名']))\ntest_subway = list(copy.deepcopy(test['地铁线路']))\nnum = len(test_name)\nsubway = []\nfor i in range(num):\n if (test_name[i] in dic_name_subway.keys()) and (test_subway[i]==0):\n subway.append(dic_name_subway[test_name[i]])\n else:\n subway.append(test_subway[i])\ntest.drop('地铁线路',axis=1, inplace=True)\ntest['地铁线路'] = subway\ndel dic_name_subway, i, num, subway, test_name, test_subway, train_name\ndel train_sub_name, train_sub_subway, train_subway\n\ntrain_sub_name = train_sub['小区名']\ntrain_sub_position = train_sub['地铁站点']\ndic_name_position = dict(map(lambda x, y: [x, y], train_sub_name, train_sub_position))\ntrain_name = list(copy.deepcopy(train['小区名']))\ntrain_position = list(copy.deepcopy(train['地铁站点']))\nnum = len(train_name)\nposition = []\nfor i in range(num):\n if (train_name[i] in dic_name_position.keys()) and (train_position[i]==0):\n position.append(dic_name_position[train_name[i]])\n else:\n position.append(train_position[i])\ntrain.drop('地铁站点',axis=1, inplace=True)\ntrain['地铁站点'] = position\ntest_name = list(copy.deepcopy(test['小区名']))\ntest_position = list(copy.deepcopy(test['地铁站点']))\nnum = len(test_name)\nposition = []\nfor i in range(num):\n if (test_name[i] in dic_name_position.keys()) and (test_position[i]==0):\n position.append(dic_name_position[test_name[i]])\n else:\n position.append(test_position[i])\ntest.drop('地铁站点',axis=1, inplace=True)\ntest['地铁站点'] = position\ndel dic_name_position, i, num, position, test_name, test_position, train_name\ndel train_position, train_sub_name, train_sub_position, train_sub\n\ntrain_distance = list(copy.deepcopy(train['距离']))\ndistance = []\nfor i in train_distance:\n if isnan(i):\n distance.append(0)\n else:\n distance.append(i)\ntrain.drop('距离',axis=1, inplace=True)\ntrain['距离'] = distance\ntest_distance = list(copy.deepcopy(test['距离']))\ndistance = []\nfor i in test_distance:\n if isnan(i):\n distance.append(0)\n else:\n distance.append(i)\ntest.drop('距离',axis=1, inplace=True)\ntest['距离'] = distance\ndel distance, i, test_distance, train_distance\n#############################################################\n## 修改日期:2018年11月2日\n## 修改人员:wzy\n#############################################################\ntrain_live = list(copy.deepcopy(train['居住状态']))\nlive = []\nfor i in train_live:\n if isnan(i):\n live.append(0)\n else:\n live.append(i)\ntrain.drop('居住状态',axis=1, inplace=True)\ntrain['居住状态'] = live\ntest_live = list(copy.deepcopy(test['居住状态']))\nlive = []\nfor i in test_live:\n if isnan(i):\n live.append(0)\n else:\n live.append(i)\ntest.drop('居住状态',axis=1, inplace=True)\ntest['居住状态'] = live\ndel i, live, test_live, train_live\n\ntrain_zx = list(copy.deepcopy(train['装修情况']))\nzx = []\nfor i in train_zx:\n if isnan(i):\n zx.append(0)\n else:\n zx.append(i)\ntrain.drop('装修情况',axis=1, inplace=True)\ntrain['装修情况'] = zx\ntest_zx = list(copy.deepcopy(test['装修情况']))\nzx = []\nfor i in test_zx:\n if isnan(i):\n zx.append(0)\n else:\n zx.append(i)\ntest.drop('装修情况',axis=1, inplace=True)\ntest['装修情况'] = zx\ndel i, test_zx, train_zx, zx\n\ntrain_cz = list(copy.deepcopy(train['出租方式']))\ncz = []\nfor i in train_cz:\n if isnan(i):\n cz.append(2)\n else:\n cz.append(i)\ntrain.drop('出租方式',axis=1, inplace=True)\ntrain['出租方式'] = cz\ntest_cz = list(copy.deepcopy(test['出租方式']))\ncz = []\nfor i in test_cz:\n if isnan(i):\n cz.append(2)\n else:\n cz.append(i)\ntest.drop('出租方式',axis=1, inplace=True)\ntest['出租方式'] = cz\ndel cz, i, test_cz, train_cz\n\ntrain = train.drop(train[train['房屋面积'] > 0.146].index)\n\ntrain_ws = list(copy.deepcopy(train['卧室数量']))\ntrain_t = list(copy.deepcopy(train['厅的数量']))\ntrain_w = list(copy.deepcopy(train['卫的数量']))\ntotal = []\nnum = len(train_ws)\nfor i in range(num):\n temp = train_ws[i] + train_t[i] + train_w[i]\n total.append(temp)\ntrain['总房间数'] = total\ntest_ws = list(copy.deepcopy(test['卧室数量']))\ntest_t = list(copy.deepcopy(test['厅的数量']))\ntest_w = list(copy.deepcopy(test['卫的数量']))\ntotal = []\nnum = len(test_ws)\nfor i in range(num):\n temp = test_ws[i] + test_t[i] + test_w[i]\n total.append(temp)\ntest['总房间数'] = total\ndel i, num, temp, test_t, test_w, test_ws, train_t, train_w, train_ws, total\n\ntrain_ws = list(copy.deepcopy(train['卧室数量']))\ntrain_w = list(copy.deepcopy(train['卫的数量']))\ntotal = []\nnum = len(train_ws)\nfor i in range(num):\n temp = train_ws[i] + train_w[i]\n total.append(temp)\ntrain['卧室和卫生间'] = total\ntest_ws = list(copy.deepcopy(test['卧室数量']))\ntest_w = list(copy.deepcopy(test['卫的数量']))\ntotal = []\nnum = len(test_ws)\nfor i in range(num):\n temp = test_ws[i] + test_w[i]\n total.append(temp)\ntest['卧室和卫生间'] = total\ndel i, num, temp, test_w, test_ws, train_w, train_ws, total\n\ntrain_acer = list(copy.deepcopy(train['房屋面积']))\nacer = []\nfor i in train_acer:\n if i == 0:\n acer.append(0.0001)\n else:\n acer.append(i)\ntrain.drop('房屋面积',axis=1, inplace=True)\ntrain['房屋面积'] = acer\ntest_acer = list(copy.deepcopy(test['房屋面积']))\nacer = []\nfor i in test_acer:\n if i == 0:\n acer.append(0.0001)\n else:\n acer.append(i)\ntest.drop('房屋面积',axis=1, inplace=True)\ntest['房屋面积'] = acer\ndel acer, i, test_acer, train_acer\n\n#############################################################\n## 修改日期:2018年11月3日\n## 修改人员:wzy\n#############################################################\n# 这个特征保留\n# 卧室占整个房间的比例\nbed_sub_all = 0.3\ntrain_sq = list(copy.deepcopy(train['房屋面积']))\ntrain_ws = list(copy.deepcopy(train['卧室数量']))\nws_sq = []\nnum = len(train_sq)\nfor i in range(num):\n temp = (train_sq[i] * 10000 * bed_sub_all) / (train_ws[i] + 1)\n ws_sq.append(temp)\ntrain['卧室均面积'] = ws_sq\ntest_sq = list(copy.deepcopy(test['房屋面积']))\ntest_ws = list(copy.deepcopy(test['卧室数量']))\nws_sq = []\nnum = len(test_sq)\nfor i in range(num):\n temp = (test_sq[i] * 10000 * bed_sub_all) / (test_ws[i] + 1)\n ws_sq.append(temp)\ntest['卧室均面积'] = ws_sq\ndel train_sq, train_ws, ws_sq, i, temp, num, test_sq, test_ws, bed_sub_all\n\n# 这个特征保留\ntrain_sq = list(copy.deepcopy(train['房屋面积']))\ntrain_w = list(copy.deepcopy(train['卫的数量']))\nw_sq = []\nnum = len(train_sq)\nfor i in range(num):\n temp = (train_sq[i] * 10000 / 14) / (train_w[i] + 1)\n w_sq.append(temp)\ntrain['卫的均面积'] = w_sq\ntest_sq = list(copy.deepcopy(test['房屋面积']))\ntest_w = list(copy.deepcopy(test['卫的数量']))\nw_sq = []\nnum = len(test_sq)\nfor i in range(num):\n temp = (test_sq[i] * 10000 / 14) / (test_w[i] + 1)\n w_sq.append(temp)\ntest['卫的均面积'] = w_sq\ndel train_sq, train_w, w_sq, temp, i, num, test_sq, test_w\n\ntrain_wss = list(copy.deepcopy(train['卧室均面积']))\ntrain_ws = list(copy.deepcopy(train['卧室数量']))\nws_s = []\nnum = len(train_wss)\nfor i in range(num):\n temp = train_wss[i] * train_ws[i]\n ws_s.append(temp)\ntrain['卧室总面积'] = ws_s\ntest_wss = list(copy.deepcopy(test['卧室均面积']))\ntest_ws = list(copy.deepcopy(test['卧室数量']))\nws_s = []\nnum = len(test_wss)\nfor i in range(num):\n temp = test_wss[i] * test_ws[i]\n ws_s.append(temp)\ntest['卧室总面积'] = ws_s\ndel train_wss, train_ws, ws_s, num, i, temp, test_wss, test_ws\n\n######################################################\n## 1.98130后的特征测试\n######################################################\ntrain_acr_total = list(copy.deepcopy(train['房屋面积']))\ntrain_bedroom_total = list(copy.deepcopy(train['卧室总面积']))\nelse_acer = []\nnum = len(train_acr_total)\nfor i in range(num):\n temp = (train_acr_total[i] * 10000) - train_bedroom_total[i]\n else_acer.append(temp)\ntrain['除卧室外剩余面积'] = else_acer\ntest_acr_total = list(copy.deepcopy(test['房屋面积']))\ntest_bedroom_total = list(copy.deepcopy(test['卧室总面积']))\nelse_acer = []\nnum = len(test_acr_total)\nfor i in range(num):\n temp = (test_acr_total[i] * 10000) - test_bedroom_total[i]\n else_acer.append(temp)\ntest['除卧室外剩余面积'] = else_acer\ndel train_acr_total, train_bedroom_total, else_acer, num, i, temp, test_acr_total, test_bedroom_total\n\ntotal_floor = list(copy.deepcopy(train['总楼层']))\nTotal_floor = []\nfor i in total_floor:\n if i == 0:\n Total_floor.append(0.01)\n else:\n Total_floor.append(i)\ntrain.drop('总楼层',axis=1, inplace=True)\ntrain['总楼层'] = Total_floor\ntotal_floor = list(copy.deepcopy(test['总楼层']))\nTotal_floor = []\nfor i in total_floor:\n if i == 0:\n Total_floor.append(0.01)\n else:\n Total_floor.append(i)\ntest.drop('总楼层',axis=1, inplace=True)\ntest['总楼层'] = Total_floor\ndel Total_floor, i, total_floor\n\ntotal_floor = list(copy.deepcopy(train['总楼层']))\nfloor = list(copy.deepcopy(train['楼层']))\nnum = len(total_floor)\nFloor = []\nfor i in range(num):\n temp = total_floor[i] * 100 * (floor[i] + 1)\n Floor.append(temp)\ntrain['具体楼层'] = Floor\ntotal_floor = list(copy.deepcopy(test['总楼层']))\nfloor = list(copy.deepcopy(test['楼层']))\nnum = len(total_floor)\nFloor = []\nfor i in range(num):\n temp = total_floor[i] * 100 * (floor[i] + 1)\n Floor.append(temp)\ntest['具体楼层'] = Floor\ndel total_floor, floor, Floor, num, i, temp\n\n######################################################\n## 1.94686后的特征测试 前面对房屋朝向做了重新处理\n######################################################\n# 上分区\ntrain.drop('时间',axis=1, inplace=True)\ntest.drop('时间',axis=1, inplace=True)\n\n# 对区按照租金平均数进行重新编码\ntrain_qu = list(copy.deepcopy(train['区']))\ntrain_label = list(copy.deepcopy(train['月租金']))\nnum = len(train_qu)\nclass_num = len(list(set(train_qu)))\nqu_list = []\nqu_money = []\nfor i in range(class_num):\n qu_list = []\n for j in range(num):\n if i == train_qu[j]:\n qu_list.append(train_label[j])\n qu_money.append(qu_list)\nAVG = []\nfor i in qu_money:\n i = np.array(i)\n avg = np.mean(i)\n AVG.append(avg)\navg = list(copy.deepcopy(AVG))\navg = np.array(avg)\navg = np.sort(avg)\ncode = []\nfor i in range(class_num):\n for j in range(class_num):\n if AVG[i] == avg[j]:\n temp = j\n code.append(temp)\nqu_code = []\nfor i in train_qu:\n i = int(i)\n qu_code.append(code[i])\ntrain.drop('区',axis=1, inplace=True)\ntrain['区'] = qu_code\ntest_qu = list(copy.deepcopy(test['区']))\nqu_code = []\nfor i in test_qu:\n i = int(i)\n qu_code.append(code[i])\ntest.drop('区',axis=1, inplace=True)\ntest['区'] = qu_code\ndel train_qu, train_label, num, class_num, qu_list, qu_money, i, j, AVG, avg, code, qu_code, test_qu\n\n\n\ntrain_location = list(copy.deepcopy(train['位置']))\ntrain_label = list(copy.deepcopy(train['月租金']))\n# 修改了前面代码,位置的缺失用76补齐\nnum_loc_class = len(list(set(train_location))) # 153种位置 最小为0, 最大为153 76缺失\nnum_loc_samp = len(train_location)\nloc_list = []\nloc_money = []\nfor i in range(num_loc_class):\n loc_list = []\n for j in range(num_loc_samp):\n if i == train_location[j]:\n loc_list.append(train_label[j])\n loc_money.append(loc_list)\nAVG = []\nfor i in loc_money:\n i = np.array(i)\n avg = np.mean(i)\n AVG.append(avg)\navg = list(copy.deepcopy(AVG))\navg = np.array(avg)\navg = np.sort(avg)\ncode = []\nfor i in range(num_loc_class):\n for j in range(num_loc_class):\n if AVG[i] == avg[j]:\n temp = j\n code.append(temp)\nloc_code = []\nfor i in train_location:\n i = int(i)\n loc_code.append(code[i])\n# train.drop('位置',axis=1, inplace=True)\ntrain['位置rank'] = loc_code\ntest_location = list(copy.deepcopy(test['位置']))\nloc_code = []\nfor i in test_location:\n i = int(i)\n loc_code.append(code[i])\n# test.drop('位置',axis=1, inplace=True)\ntest['位置rank'] = loc_code\ndel train_location, train_label, num_loc_class, num_loc_samp, i, j, AVG, avg\ndel loc_code, code, test_location\n\n\ntrain_location = list(copy.deepcopy(train['地铁线路']))\ntrain_label = list(copy.deepcopy(train['月租金']))\n# 修改了前面代码,位置的缺失用76补齐\nnum_loc_class = len(list(set(train_location))) # 153种位置 最小为0, 最大为153 76缺失\nnum_loc_samp = len(train_location)\nloc_list = []\nloc_money = []\nfor i in range(num_loc_class):\n loc_list = []\n for j in range(num_loc_samp):\n if i == train_location[j]:\n loc_list.append(train_label[j])\n loc_money.append(loc_list)\nAVG = []\nfor i in loc_money:\n i = np.array(i)\n avg = np.mean(i)\n AVG.append(avg)\navg = list(copy.deepcopy(AVG))\navg = np.array(avg)\navg = np.sort(avg)\ncode = []\nfor i in range(num_loc_class):\n for j in range(num_loc_class):\n if AVG[i] == avg[j]:\n temp = j\n code.append(temp)\nloc_code = []\nfor i in train_location:\n i = int(i)\n loc_code.append(code[i])\n# train.drop('地铁线路',axis=1, inplace=True)\ntrain['地铁线路rank'] = loc_code\ntest_location = list(copy.deepcopy(test['地铁线路']))\nloc_code = []\nfor i in test_location:\n i = int(i)\n loc_code.append(code[i])\n# test.drop('地铁线路',axis=1, inplace=True)\ntest['地铁线路rank'] = loc_code\ndel train_location, train_label, num_loc_class, num_loc_samp, i, j, AVG, avg\ndel loc_code, code, test_location\n\n\n######################################################\n## 1.92593后的特征测试\n######################################################\n#地铁站点、小区名称进行rank\ntrain = train.sort_values(by=['地铁站点'], ascending=(True))\ntrain_name = list(copy.deepcopy(train['地铁站点']))\ntrain_name_dic = list(set(train_name))\ndic_num = len(train_name_dic)\ncode = list(np.arange(dic_num))\ndic_enc_train_name = dict(map(lambda x, y: [x, y], train_name_dic, code))\nencode_train_name = []\nfor i in train_name:\n temp = dic_enc_train_name[i]\n encode_train_name.append(temp)\ntest_name = list(copy.deepcopy(test['地铁站点']))\nencode_test_name = []\nfor i in test_name:\n if i not in dic_enc_train_name.keys():\n print(i)\n else:\n temp = dic_enc_train_name[i]\n encode_test_name.append(temp)\ntrain.drop('地铁站点',axis=1, inplace=True)\ntrain['地铁站点'] = encode_train_name\ntest.drop('地铁站点',axis=1, inplace=True)\ntest['地铁站点'] = encode_test_name\ndel code, dic_enc_train_name, dic_num, encode_test_name, encode_train_name\ndel i, loc_list, loc_money, temp, test_name, train_name, train_name_dic\n\ntrain_location = list(copy.deepcopy(train['地铁站点']))\ntrain_label = list(copy.deepcopy(train['月租金']))\n# 修改了前面代码,位置的缺失用76补齐\nnum_loc_class = len(list(set(train_location))) # 153种位置 最小为0, 最大为153 76缺失\nnum_loc_samp = len(train_location)\nloc_list = []\nloc_money = []\nfor i in range(num_loc_class):\n loc_list = []\n for j in range(num_loc_samp):\n if i == train_location[j]:\n loc_list.append(train_label[j])\n loc_money.append(loc_list)\nAVG = []\nfor i in loc_money:\n i = np.array(i)\n avg = np.mean(i)\n AVG.append(avg)\navg = list(copy.deepcopy(AVG))\navg = np.array(avg)\navg = np.sort(avg)\ncode = []\nfor i in range(num_loc_class):\n for j in range(num_loc_class):\n if AVG[i] == avg[j]:\n temp = j\n code.append(temp)\nloc_code = []\nfor i in train_location:\n i = int(i)\n loc_code.append(code[i])\n# train.drop('地铁站点',axis=1, inplace=True)\ntrain['地铁站点rank'] = loc_code\ntest_location = list(copy.deepcopy(test['地铁站点']))\nloc_code = []\nfor i in test_location:\n i = int(i)\n loc_code.append(code[i])\n# test.drop('地铁站点',axis=1, inplace=True)\ntest['地铁站点rank'] = loc_code\ndel train_location, train_label, num_loc_class, num_loc_samp, i, j, AVG, avg\ndel loc_code, code, test_location\n\n######################################################\n## 1.92306后的特征测试\n######################################################\n# 房屋朝向2不可以做rank处理\n# 修改卧室占整个房间的比例为0.3 原来为1/3\ntrain_location = list(copy.deepcopy(train['装修情况']))\ntrain_label = list(copy.deepcopy(train['月租金']))\n# 修改了前面代码,位置的缺失用76补齐\nnum_loc_class = len(list(set(train_location))) # 153种位置 最小为0, 最大为153 76缺失\nnum_loc_samp = len(train_location)\nloc_list = []\nloc_money = []\nfor i in range(num_loc_class):\n loc_list = []\n for j in range(num_loc_samp):\n if i == train_location[j]:\n loc_list.append(train_label[j])\n loc_money.append(loc_list)\nAVG = []\nfor i in loc_money:\n i = np.array(i)\n avg = np.mean(i)\n AVG.append(avg)\navg = list(copy.deepcopy(AVG))\navg = np.array(avg)\navg = np.sort(avg)\ncode = []\nfor i in range(num_loc_class):\n for j in range(num_loc_class):\n if AVG[i] == avg[j]:\n temp = j\n code.append(temp)\nloc_code = []\nfor i in train_location:\n i = int(i)\n loc_code.append(code[i])\ntrain['装修情况rank'] = loc_code\ntest_location = list(copy.deepcopy(test['装修情况']))\nloc_code = []\nfor i in test_location:\n i = int(i)\n loc_code.append(code[i])\ntest['装修情况rank'] = loc_code\ndel train_location, train_label, num_loc_class, num_loc_samp, i, j, AVG, avg\ndel loc_code, code, test_location\n\ntrain_house_floor = list(copy.deepcopy(train['具体楼层']))\ntrain_square = list(copy.deepcopy(train['房屋面积']))\ntotal_square = []\nfor i in range(len(train_house_floor)):\n temp = train_house_floor[i] * train_square[i]\n total_square.append(temp)\ntrain['这层楼的房屋面积'] = total_square\ndel train_house_floor, train_square, i, temp, total_square\ntest_house_floor = list(copy.deepcopy(test['具体楼层']))\ntest_square = list(copy.deepcopy(test['房屋面积']))\ntotal_square = []\nfor i in range(len(test_house_floor)):\n temp = test_house_floor[i] * test_square[i]\n total_square.append(temp)\ntest['这层楼的房屋面积'] = total_square\ndel test_house_floor, test_square, i, temp, total_square\n\n######################################################\n## 1.90010后的特征测试\n######################################################\ntrain_house_floor = list(copy.deepcopy(train['具体楼层']))\ntrain_bedroom_total = list(copy.deepcopy(train['卧室总面积']))\nbedroom_square = []\nfor i in range(len(train_house_floor)):\n temp = train_house_floor[i] * train_bedroom_total[i]\n bedroom_square.append(temp)\ntrain['这层楼的卧室总面积'] = bedroom_square\ndel train_house_floor, train_bedroom_total, bedroom_square, i, temp\ntest_house_floor = list(copy.deepcopy(test['具体楼层']))\ntest_bedroom_total = list(copy.deepcopy(test['卧室总面积']))\nbedroom_square = []\nfor i in range(len(test_house_floor)):\n temp = test_house_floor[i] * test_bedroom_total[i]\n bedroom_square.append(temp)\ntest['这层楼的卧室总面积'] = bedroom_square\ndel test_house_floor, test_bedroom_total, bedroom_square, i, temp\n\n######################################################\n## 1.88556后的特征测试\n######################################################\ntrain_badroom = list(copy.deepcopy(train['厅的数量']))\ntrain_livingroom = list(copy.deepcopy(train['卧室数量']))\nbad_and_living = []\nfor i in range(len(train_badroom)):\n temp = train_badroom[i] + train_livingroom[i]\n bad_and_living.append(temp)\ntrain['卧室和厅'] = bad_and_living\ntest_badroom = list(copy.deepcopy(test['厅的数量']))\ntest_livingroom = list(copy.deepcopy(test['卧室数量']))\nbad_and_living = []\nfor i in range(len(test_badroom)):\n temp = test_badroom[i] + test_livingroom[i]\n bad_and_living.append(temp)\ntest['卧室和厅'] = bad_and_living\ndel train_badroom, train_livingroom, bad_and_living, i, temp, test_badroom, test_livingroom\n\nliving_sub_all = 0.26\ntrain_sq = list(copy.deepcopy(train['房屋面积']))\ntrain_living = list(copy.deepcopy(train['厅的数量']))\nws_sq = []\nnum = len(train_sq)\nfor i in range(num):\n temp = (train_sq[i] * 10000 * living_sub_all) / (train_living[i] + 1)\n ws_sq.append(temp)\ntrain['客厅均面积'] = ws_sq\ntest_sq = list(copy.deepcopy(test['房屋面积']))\ntest_living = list(copy.deepcopy(test['厅的数量']))\nws_sq = []\nnum = len(test_sq)\nfor i in range(num):\n temp = (test_sq[i] * 10000 * living_sub_all) / (test_living[i] + 1)\n ws_sq.append(temp)\ntest['客厅均面积'] = ws_sq\ndel train_sq, train_living, ws_sq, i, temp, num, test_sq, test_living, living_sub_all\n\ntrain_wss = list(copy.deepcopy(train['客厅均面积']))\ntrain_ws = list(copy.deepcopy(train['厅的数量']))\nws_s = []\nnum = len(train_wss)\nfor i in range(num):\n temp = train_wss[i] * train_ws[i]\n ws_s.append(temp)\ntrain['客厅总面积'] = ws_s\ntest_wss = list(copy.deepcopy(test['客厅均面积']))\ntest_ws = list(copy.deepcopy(test['厅的数量']))\nws_s = []\nnum = len(test_wss)\nfor i in range(num):\n temp = test_wss[i] * test_ws[i]\n ws_s.append(temp)\ntest['客厅总面积'] = ws_s\ndel train_wss, train_ws, ws_s, num, i, temp, test_wss, test_ws\n\ntest = test.sort_values(by=['id'], ascending=(True))\ntest_id = list(copy.deepcopy(test['id']))\ntest.drop('id',axis=1, inplace=True)\ntrain_label = list(copy.deepcopy(train['月租金']))\ntrain.drop('月租金',axis=1, inplace=True)\n\ntrain_pool = Pool(train, train_label, cat_features=None)\ntest_pool = Pool(test, cat_features=None)\ncb_model = cb.CatBoostRegressor(depth=11, learning_rate=0.11, iterations=2729, l2_leaf_reg=0.1, model_size_reg=2, loss_function='RMSE')\ncb_model.fit(train_pool, verbose=True)\npreds = cb_model.predict(test_pool)\n\ntest_lgb = pd.DataFrame({'id': test_id, 'price': preds})\ntest_lgb.to_csv('./result/catboost.csv', index=False)\n"
] |
[
[
"pandas.concat",
"pandas.read_csv",
"numpy.arange",
"pandas.DataFrame",
"numpy.sort",
"numpy.mean",
"numpy.array"
]
] |
cmgreivel/spaCy
|
[
"a31506e06060c559abfeda043503935691af2e98"
] |
[
"examples/keras_parikh_entailment/__main__.py"
] |
[
"from __future__ import division, unicode_literals, print_function\nimport spacy\n\nimport plac\nfrom pathlib import Path\nimport ujson as json\nimport numpy\nfrom keras.utils.np_utils import to_categorical\n\nfrom spacy_hook import get_embeddings, get_word_ids\nfrom spacy_hook import create_similarity_pipeline\n\nfrom keras_decomposable_attention import build_model\n\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\n\ndef train(train_loc, dev_loc, shape, settings):\n train_texts1, train_texts2, train_labels = read_snli(train_loc)\n dev_texts1, dev_texts2, dev_labels = read_snli(dev_loc)\n\n print(\"Loading spaCy\")\n nlp = spacy.load('en')\n assert nlp.path is not None\n print(\"Compiling network\")\n model = build_model(get_embeddings(nlp.vocab), shape, settings)\n print(\"Processing texts...\")\n Xs = []\n for texts in (train_texts1, train_texts2, dev_texts1, dev_texts2):\n Xs.append(get_word_ids(list(nlp.pipe(texts, n_threads=20, batch_size=20000)),\n max_length=shape[0],\n rnn_encode=settings['gru_encode'],\n tree_truncate=settings['tree_truncate']))\n train_X1, train_X2, dev_X1, dev_X2 = Xs\n print(settings)\n model.fit(\n [train_X1, train_X2],\n train_labels,\n validation_data=([dev_X1, dev_X2], dev_labels),\n nb_epoch=settings['nr_epoch'],\n batch_size=settings['batch_size'])\n if not (nlp.path / 'similarity').exists():\n (nlp.path / 'similarity').mkdir()\n print(\"Saving to\", nlp.path / 'similarity')\n weights = model.get_weights()\n with (nlp.path / 'similarity' / 'model').open('wb') as file_:\n pickle.dump(weights[1:], file_)\n with (nlp.path / 'similarity' / 'config.json').open('wb') as file_:\n file_.write(model.to_json())\n\n\ndef evaluate(dev_loc):\n dev_texts1, dev_texts2, dev_labels = read_snli(dev_loc)\n nlp = spacy.load('en',\n create_pipeline=create_similarity_pipeline)\n total = 0.\n correct = 0.\n for text1, text2, label in zip(dev_texts1, dev_texts2, dev_labels):\n doc1 = nlp(text1)\n doc2 = nlp(text2)\n sim = doc1.similarity(doc2)\n if sim.argmax() == label.argmax():\n correct += 1\n total += 1\n return correct, total\n\n\ndef demo():\n nlp = spacy.load('en',\n create_pipeline=create_similarity_pipeline)\n doc1 = nlp(u'What were the best crime fiction books in 2016?')\n doc2 = nlp(\n u'What should I read that was published last year? I like crime stories.')\n print(doc1)\n print(doc2)\n print(\"Similarity\", doc1.similarity(doc2))\n\n\nLABELS = {'entailment': 0, 'contradiction': 1, 'neutral': 2}\ndef read_snli(path):\n texts1 = []\n texts2 = []\n labels = []\n with path.open() as file_:\n for line in file_:\n eg = json.loads(line)\n label = eg['gold_label']\n if label == '-':\n continue\n texts1.append(eg['sentence1'])\n texts2.append(eg['sentence2'])\n labels.append(LABELS[label])\n return texts1, texts2, to_categorical(numpy.asarray(labels, dtype='int32'))\n\n\[email protected](\n mode=(\"Mode to execute\", \"positional\", None, str, [\"train\", \"evaluate\", \"demo\"]),\n train_loc=(\"Path to training data\", \"positional\", None, Path),\n dev_loc=(\"Path to development data\", \"positional\", None, Path),\n max_length=(\"Length to truncate sentences\", \"option\", \"L\", int),\n nr_hidden=(\"Number of hidden units\", \"option\", \"H\", int),\n dropout=(\"Dropout level\", \"option\", \"d\", float),\n learn_rate=(\"Learning rate\", \"option\", \"e\", float),\n batch_size=(\"Batch size for neural network training\", \"option\", \"b\", int),\n nr_epoch=(\"Number of training epochs\", \"option\", \"i\", int),\n tree_truncate=(\"Truncate sentences by tree distance\", \"flag\", \"T\", bool),\n gru_encode=(\"Encode sentences with bidirectional GRU\", \"flag\", \"E\", bool),\n)\ndef main(mode, train_loc, dev_loc,\n tree_truncate=False,\n gru_encode=False,\n max_length=100,\n nr_hidden=100,\n dropout=0.2,\n learn_rate=0.001,\n batch_size=100,\n nr_epoch=5):\n shape = (max_length, nr_hidden, 3)\n settings = {\n 'lr': learn_rate,\n 'dropout': dropout,\n 'batch_size': batch_size,\n 'nr_epoch': nr_epoch,\n 'tree_truncate': tree_truncate,\n 'gru_encode': gru_encode\n }\n if mode == 'train':\n train(train_loc, dev_loc, shape, settings)\n elif mode == 'evaluate':\n correct, total = evaluate(dev_loc)\n print(correct, '/', total, correct / total)\n else:\n demo()\n\nif __name__ == '__main__':\n plac.call(main)\n"
] |
[
[
"numpy.asarray"
]
] |
AnveshAeturi/deep-learning-workshop
|
[
"20be7d92f310ca27a176e96e3a0b557f3fee2ec2"
] |
[
"notebooks/work-in-progress/2018-10_ZeroShotRelationships/train_on_onestep.py"
] |
[
"import os, sys\n\nimport argparse\nimport random\n\nimport time, pytz\nfrom datetime import datetime, timezone\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport h5py\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader\n\n#from text_utils import TextEncoder # This is my version\n\nsys.path.append('orig/pytorch-openai-transformer-lm')\nfrom model_pytorch import TransformerModel, load_openai_pretrained_model, DEFAULT_CONFIG\nfrom model_pytorch import Conv1D, Block\nfrom opt import OpenAIAdam\nfrom utils import ResultLogger\n\npretrained_model_path = os.path.join('.', 'orig', 'finetune-transformer-lm', 'model')\n\n# So, let's read in a text file\nrelation_splits_path = os.path.join('.', 'orig', 'omerlevy-bidaf_no_answer-2e9868b224e4', 'relation_splits', )\n\n# 840000 31087632 191519344 orig/omerlevy-bidaf_no_answer-2e9868b224e4/relation_splits/train.1\n# 600 21854 136415 orig/omerlevy-bidaf_no_answer-2e9868b224e4/relation_splits/dev.1\n# 12000 427110 2688895 orig/omerlevy-bidaf_no_answer-2e9868b224e4/relation_splits/test.1\n# 852600 31536596 194344654 total\n\n# TODO : Fn to get list of relationship_types and relationship_templates for each type\n\n\n# Props to : https://github.com/rasbt/deep-learning-book/blob/master/code/model_zoo/pytorch_ipynb/custom-data-loader-csv.ipynb\n\nclass Hdf5Dataset(Dataset):\n \"\"\"Custom Dataset for loading entries from HDF5 databases\"\"\"\n\n def __init__(self, h5_path, vocab_count, valid_indices=None): # transform=None, \n self.h5f = h5py.File(h5_path, 'r')\n features = self.h5f['features']\n \n self.valid_indices=valid_indices \n if valid_indices is None:\n self.num_entries = features.shape[0]\n else:\n self.num_entries = len(valid_indices)\n #self.transform = transform\n \n self.n_ctx = features.shape[1]\n\n self.postitional_encoder = np.arange(vocab_count, vocab_count + self.n_ctx)\n \n def __getitem__(self, index):\n if self.valid_indices is not None: # find on-disk index\n index = self.valid_indices[index]\n \n features = self.h5f['features'][index]\n labels = self.h5f['labels'][index].astype(np.int64)\n deps = self.h5f['deps'][index].astype(np.int64)\n \n # Find the token_clf\n token_clf_pos = np.nonzero( features==token_clf )[-1].sum() # This is zero if it is not found\n if token_clf_pos>=features.shape[0]-1: \n #print(\"token_clf_pos right at end, index=\", index, token_clf_pos, features.shape[0]-1)\n token_clf_pos=features.shape[0]-2 # Need to have this location, and the next one\n \n #if self.transform is not None:\n # features = self.transform(features)\n \n #xmb[:, :, :, 1] = np.arange(n_vocab + n_special, n_vocab + n_special + n_ctx)\n #xmb[:, 1] = np.arange(n_vocab + n_special, n_vocab + n_special + n_ctx) # This is a single row, of batch=1\n\n #features_with_positions = np.stack( [ features, self.postitional_encoder ], axis=1 )\n features_with_positions = np.stack( [ features, self.postitional_encoder.copy() ], axis=1 ) # May be safer when multithreaded?\n #print(features.shape, features_with_positions.shape) # (128,) (128, 2)\n\n unanswerable=False\n if 3 not in list(labels): # There is no answer to this question\n unanswerable=True\n if 4 not in list(labels): # There is no answer to this question\n unanswerable=True\n \n #print(token_clf_pos, unanswerable)\n if unanswerable:\n if False:\n labels[0]=4 # end is before start\n labels[1]=3\n if True:\n labels[token_clf_pos ] = 4 # end is before start\n labels[token_clf_pos+1] = 3\n \n # https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.clip.html\n np.clip(deps, 0, self.n_ctx-1, out=deps)\n \n return features_with_positions, labels, deps\n\n def __len__(self):\n return self.num_entries\n\n def close(self):\n self.h5f.close()\n \n\nclass StepwiseClassifierModel(nn.Module):\n \"\"\" Transformer with stepwise classifier(s) \"\"\"\n def __init__(self, cfg, n_classifier=None, one_hot=True, vocab_count=None, n_ctx=128, extra_block=False): # 40990\n super(StepwiseClassifierModel, self).__init__()\n self.n_embd = cfg.n_embd\n self.n_ctx = n_ctx\n self.n_classifier = n_classifier\n self.extra_block = extra_block\n \n self.transformer = TransformerModel(cfg, vocab=vocab_count+n_ctx, n_ctx=n_ctx)\n \n ## Add the attention pointer idea\n if extra_block: \n # First : Add an additional transformer layer\n self.full_block = Block(n_ctx, cfg, scale=True)\n \n # BBBUUUTTT :: force it into full-attentional mode ::\n #self.full_block.attn.register_buffer('b', torch.tril(torch.ones(n_ctx, n_ctx)).view(1, 1, n_ctx, n_ctx))\n self.full_block.attn.register_buffer('b', (torch.ones(n_ctx, n_ctx)).view(1, 1, n_ctx, n_ctx))\n\n self.stepwise_dropout = nn.Dropout(cfg.clf_pdrop) \n self.stepwise_classifier = Conv1D(n_classifier, 1, self.n_embd)\n\n self.attn_dropout = nn.Dropout(cfg.attn_pdrop) \n self.c_attn = Conv1D(self.n_embd*2, 1, self.n_embd)\n\n def forward(self, x): # x is the input text\n ## NO : x ~ np.zeros((n_batch, 2, n_ctx, 2), dtype=np.int32) # This is for their 0 vs 1 model\n # x ~ np.zeros((n_batch, n_ctx, 2), dtype=np.int32) # This is more normal use-case\n # x[..., -1] is for [input_sequence, positions]\n \n h = self.transformer(x) # These are the transformers embeddings (n_batch, n_ctx, n_embd) \n \n\n if self.extra_block: # This can look forwards too\n h = self.full_block(h)\n\n # for classification step-wise\n h_stepwise_input = self.stepwise_dropout(h)\n task_logits = self.stepwise_classifier( h_stepwise_input ).permute( 0, 2, 1) # CrossEntropy expects classifier to be in second position\n #print(\"task_logits.size()=\", task_logits.size() ) \n # task_logits.size()= torch.Size([8, 5, 128]) (n_batch, n_classifier, n_ctx)\n\n\n # ~ Attention.forward\n h_attn_input = self.stepwise_dropout(h)\n attn = self.c_attn(h_attn_input)\n \n # reshape for query and key\n query, key = attn.split(self.n_embd, dim=2)\n \n # ~ Attention.split_heads(self, x, k=False):\n #new_h_shape = h.size()[:-1] + (1 , h.size(-1)) # Insert an extra dimension\n #query = query.view(*new_h_shape).permute(0, 2, 1, 3) \n #key = key.view( *new_h_shape).permute(0, 2, 3, 1)\n #query = query.view(*new_h_shape).permute(0, 1, 3) \n \n # Above can be simplified, since we don't need to get too fancy...\n key = key.permute(0, 2, 1)\n #print( \"query.size()=\", query.size())\n # query.size()= torch.Size([8, 128, 768]) = batch, time_step, matcher\n #print( \"key.size()=\", key.size())\n # key.size()= torch.Size([8, 768, 128]) = batch, matcher, time_step\n \n # ~ Attention._attn(self, q, k, v):\n w = torch.matmul(query, key)\n if True: # self.scale:\n w = w / np.sqrt(self.n_embd) # simple scaling, since we're adding up a dot product\n \n # Now, we have a weighting matrix (logits) over the different locations\n #w = nn.Softmax(dim=-1)(w) # Don't do this here, since we use pure logits with the loss_fn\n \n #print(\"w.size()=\", w.size())\n # w.size()= torch.Size([8, 128, 128]) ( thinking about it : batch, time_step, position_score )\n\n attn_logits = w.permute(0, 2, 1) # CrossEntropy expects classifier to be in second position ( batch, position_score, time_step )\n \n return task_logits, attn_logits\n\n\ndef run_predictions(test_loader=None, output_file=None):\n print(\"run_predictions() -> %s\" % (output_file, ))\n model_stepwise.eval()\n\n predictions_arr, targets_arr, txts_arr = [], [], []\n for idx, (features, labels, deps) in enumerate(test_loader):\n #features, labels, deps = features.to(device), labels.to(device), deps.to(device)\n features = features.to(device)\n \n out_class_logits, out_deps_logits = model_stepwise(features)\n\n # Ok, so now what...\n # Ignore the deps\n # Just save off the out_class_logits and corresponding labels\n \n predictions_arr.append( out_class_logits.detach().cpu().numpy() )\n targets_arr.append( labels.detach().cpu().numpy() )\n \n #bpes = list( features.detach().cpu().numpy()[0,:,0] )\n ##txt = text_encoder.decode( bpes )\n #txt = text_encoder.decode_as_fragments( bpes )\n #txts_arr.append( txt )\n \n if (idx+1) % 10 == 0:\n print('%.1f%% of predictions' % (idx / float(len(test_loader)) * 100, ), end='\\r')\n #break\n\n np.savez(output_file, predictions=np.array( predictions_arr ), targets=np.array( targets_arr ), )\n \n #with open(output_file+'.txt', 'w') as f:\n # f.write('\\n'.join(txts_arr))\n \n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n \n parser.add_argument(\"--checkpoint\", default=None, type=str, help=\"model checkpoint path to restart training\")\n parser.add_argument('--stub', type=str, default='base', help=\"Description\")\n \n #parser.add_argument('--dataset', type=str)\n parser.add_argument('--log_dir', type=str, default='log/')\n #parser.add_argument('--save_dir', type=str, default='save/')\n #parser.add_argument('--data_dir', type=str, default='data/')\n #parser.add_argument('--submission_dir', type=str, default='submission/')\n #parser.add_argument('--submit', action='store_true')\n #parser.add_argument('--analysis', action='store_true')\n parser.add_argument('--seed', type=int, default=42)\n parser.add_argument('--max_grad_norm', type=int, default=1)\n \n parser.add_argument('--l2', type=float, default=0.01)\n parser.add_argument('--vector_l2', action='store_true')\n parser.add_argument('--opt', type=str, default='adam')\n\n parser.add_argument('--lr', type=float, default=6.25e-5)\n parser.add_argument('--lr_warmup', type=float, default=0.002)\n parser.add_argument('--lr_schedule', type=str, default='warmup_linear')\n parser.add_argument('--b1', type=float, default=0.9)\n parser.add_argument('--b2', type=float, default=0.999)\n parser.add_argument('--e', type=float, default=1e-8)\n\n parser.add_argument('--n_transfer', type=int, default=12)\n parser.add_argument('--lm_coef', type=float, default=0.5)\n #parser.add_argument('--n_valid', type=int, default=374)\n\n # Standard for pre-trained model START\n parser.add_argument('--n_embd', type=int, default=768) # This is the internal feature width\n parser.add_argument('--n_head', type=int, default=12)\n parser.add_argument('--n_layer', type=int, default=12)\n parser.add_argument('--embd_pdrop', type=float, default=0.1)\n parser.add_argument('--attn_pdrop', type=float, default=0.1)\n parser.add_argument('--resid_pdrop', type=float, default=0.1)\n parser.add_argument('--clf_pdrop', type=float, default=0.1)\n parser.add_argument('--afn', type=str, default='gelu')\n # Standard for pre-trained model END\n\n \n parser.add_argument('--encoder_path', type=str, default=pretrained_model_path+'/encoder_bpe_40000.json')\n parser.add_argument('--bpe_path', type=str, default=pretrained_model_path+'/vocab_40000.bpe')\n \n parser.add_argument('--relation_hdf5', type=str, default='dev.1_all.hdf5')\n \n parser.add_argument('--tokens_special', type=int, default=3) # Printed out by relation_split_to_hdf5\n parser.add_argument('--token_clf', type=int, default=40480) # Printed out by relation_split_to_hdf5\n parser.add_argument('--vocab_count', type=int, default=40481) # Printed out by relation_split_to_hdf5\n parser.add_argument('--n_classes', type=int, default=5) # #label classes = len({0, 1,2, 3,4})\n #parser.add_argument('--n_ctx', type=int, default=128) # Max length of input texts in bpes - get this from input hdf5 shapes\n\n parser.add_argument('--batch_size_per_gpu', type=int, default=32) \n parser.add_argument('--n_epoch', type=int, default=3)\n parser.add_argument(\"--tz\", type=str, default='Asia/Singapore', help=\"Timezone for local finish time estimation\")\n \n parser.add_argument('--dep_fac', type=float, default=0.)\n parser.add_argument('--extra_block', action='store_true')\n \n parser.add_argument('--predict', action='store_true')\n\n args = parser.parse_args()\n print(args)\n\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n torch.cuda.manual_seed_all(args.seed)\n\n tz = pytz.timezone(args.tz)\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n n_gpu = torch.cuda.device_count()\n print(\"device\", device, \"n_gpu\", n_gpu)\n\n \n #text_encoder = TextEncoder(args.encoder_path, args.bpe_path)\n #encoder = text_encoder.encoder\n #n_vocab = len(text_encoder.encoder)\n #\n #tokens_regular = n_vocab\n #encoder['_start_'] = len(encoder) # Last number (increments)\n #encoder['_delimiter_'] = len(encoder) # Last number (increments)\n #encoder['_classify_'] = len(encoder) # Last number (increments)\n #token_clf = encoder['_classify_']\n token_clf = args.token_clf\n \n #n_special = tokens_special =3 \n #tokens_special = len(encoder) - tokens_regular # Number of extra tokens\n\n \n relation_hdf5 = os.path.join(relation_splits_path, args.relation_hdf5)\n \n #with h5py.File(relation_hdf5, 'r') as h5f:\n # print(h5f['features'].shape)\n # print(h5f['labels'].shape)\n # print(h5f['deps'].shape)\n\n #n_ctx = args.n_ctx # \n #vocab_max = args.vocab_count + n_ctx\n\n train_dataset = Hdf5Dataset(h5_path=relation_hdf5, vocab_count=args.vocab_count)\n \n train_size = len(train_dataset)\n n_ctx = train_dataset.n_ctx\n \n batch_size = args.batch_size_per_gpu\n n_gpus = torch.cuda.device_count()\n \n if n_gpus > 1: # https://pytorch.org/tutorials/beginner/blitz/data_parallel_tutorial.html\n batch_size *= n_gpus\n\n n_updates_total = (train_size // batch_size) * args.n_epoch\n\n\n model_stepwise = StepwiseClassifierModel(args, n_classifier=args.n_classes, vocab_count=args.vocab_count, extra_block=args.extra_block)\n\n model_opt = OpenAIAdam(model_stepwise.parameters(),\n lr=args.lr, schedule=args.lr_schedule, \n warmup=args.lr_warmup, t_total=n_updates_total,\n b1=args.b1, b2=args.b2, e=args.e,\n l2=args.l2, ector_l2=args.vector_l2,\n max_grad_norm=args.max_grad_norm)\n \n epoch_start, epoch_max, loss_best = -1, args.n_epoch, None\n\n if args.checkpoint is None:\n load_openai_pretrained_model(\n model_stepwise.transformer, \n n_special=args.tokens_special, n_ctx=n_ctx, # n_ctx adjusts embedding size to include positional\n path=pretrained_model_path+'/',\n path_names=os.path.join('.', 'orig', 'pytorch-openai-transformer-lm')+'/',\n )\n\n model_stepwise.to(device)\n\n if torch.cuda.device_count() > 1: # https://pytorch.org/tutorials/beginner/blitz/data_parallel_tutorial.html\n print(\"Let's use\", torch.cuda.device_count(), \"GPUs!\")\n model_stepwise = nn.DataParallel(model_stepwise)\n \n\n os.makedirs('./checkpoints', exist_ok=True)\n \n if args.checkpoint is not None:\n checkpoint = torch.load(args.checkpoint, map_location=lambda storage, loc: storage)\n epoch_start = checkpoint['epoch']\n \n #from collections import OrderedDict\n #def fix_dict(state_dict):\n # new_state_dict = OrderedDict()\n # for k, v in state_dict.items():\n # name = k\n # if name.startswith('module.'):\n # name = k[7:] # remove 'module.' of dataparallel\n # new_state_dict[name]=v\n # return new_state_dict\n #\n #model.load_state_dict(new_state_dict) \n \n model_stepwise.load_state_dict(checkpoint['model'])\n model_opt.load_state_dict(checkpoint['optimizer'])\n \n #lr_scheduler = get_lr_scheduler(optimizer)\n #lr_scheduler.load_state_dict(checkpoint['lr_scheduler'])\n \n print(\"Loaded %s - assuming epoch_now=%d\" % (args.checkpoint, epoch_start,))\n\n \n #zero = torch.zeros(1).to(device)\n\n if args.predict: \n # Predict out results for all the 'relation_hdf5' instead (batch_size=1 not efficient, but 'sure')\n test_loader = DataLoader(dataset=train_dataset, batch_size=1, shuffle=False) # , num_workers=1\n \n # This is now done by the dataset generation script\n #from text_utils import TextEncoder # This is my version\n #text_encoder = TextEncoder(args.encoder_path, args.bpe_path) \n \n run_predictions(test_loader=test_loader, output_file=\"%s_%s.npz\" % (relation_hdf5, args.stub))\n exit(0)\n\n train_loader = DataLoader(dataset=train_dataset, \n batch_size=batch_size, \n shuffle=False) # 2 leads to device side asserts... , num_workers=1\n\n try:\n idx_loss_check, loss_recent_tot = 0, 0.\n for epoch in range(epoch_start+1, epoch_max): # So this refers to the epoch-end value\n time_estimate_last = t_start = time.time()\n\n model_stepwise.train()\n \n for idx, (features, labels, deps) in enumerate(train_loader):\n features, labels, deps = features.to(device), labels.to(device), deps.to(device)\n \n model_opt.zero_grad()\n out_class_logits, out_deps_logits = model_stepwise(features)\n \n #batch_loss = ce_loss(output, target)\n \n # https://pytorch.org/docs/stable/nn.html?highlight=loss#torch.nn.BCEWithLogitsLoss\n class_loss = nn.CrossEntropyLoss(reduction='none')( out_class_logits, labels )\n #print(\"class_loss.size()=\", class_loss.size())\n # class_loss.size()= torch.Size([8, 128])\n class_loss_tot = class_loss.sum()\n \n # The dep loss should be ignored for those deps which == 0\n dep_loss = nn.CrossEntropyLoss(reduction='none')( out_deps_logits, deps )\n #print(\"dep_loss.size()=\", dep_loss.size())\n # dep_loss.size()= torch.Size([8, 128])\n\n #dep_loss_masked = torch.where(deps>0, dep_loss, zero) # This zeros out all positions where deps == 0\n #dep_loss_tot = dep_loss_masked.sum() / batch_size\n dep_loss_tot = dep_loss.masked_fill_( deps==0, 0. ).sum()\n \n factor_hints=\"Factor hints (class_loss=%8.4f, deps_loss=%10.4f, fac=%.8f)\" % ( \n class_loss_tot.item()/batch_size*100., \n dep_loss_tot.item()/batch_size*100., \n class_loss_tot.item()/dep_loss_tot.item(), )\n \n #factor hints : (231.14927673339844, 225.23297119140625, 1.0262674932124587)\n\n batch_loss = class_loss_tot + args.dep_fac * dep_loss_tot\n \n batch_loss.backward()\n \n model_opt.step()\n \n loss_this = batch_loss.item()\n loss_recent_tot += loss_this\n \n if idx % 10 == 0:\n print('%.1f%% of epoch %d' % (idx / float(len(train_loader)) * 100, epoch,), end='\\r') # Python 3 FTW!\n\n if idx % 100 == 0:\n print(epoch, idx, factor_hints)\n\n sentences_since_last_check = (idx-idx_loss_check)*batch_size\n #if sentences_since_last_check > 50000: # Potentially save every 50000 sentences (~30mins on TitanX)\n if sentences_since_last_check > 200000: # Potentially save every 200000 sentences (~2hrs on TitanX)\n loss_recent = loss_recent_tot / float(sentences_since_last_check) # loss per sentence\n \n if loss_best is None or loss_recent<loss_best: # Save model if loss has decreased\n fname = './checkpoints/model-stepwise_%s_%04d-%06d.pth' % (args.stub, epoch, idx*batch_size,)\n print(\"Saving Checkpoint : '%s', loss_recent=%.4f\" % (fname, loss_recent/batch_size*100., ))\n torch.save(dict(\n epoch=epoch,\n model=model_stepwise.state_dict(), \n optimizer=model_opt.state_dict(), \n #lr_scheduler=lr_scheduler.state_dict(), \n ), fname)\n loss_best=loss_recent\n idx_loss_check, loss_recent_tot = idx, 0. # Restart running tallies\n \n t_now = time.time()\n if t_now - time_estimate_last>5*60.: # Update every 5 minutes\n calc_duration = t_now-t_start\n calc_fraction = (idx*batch_size)/len(train_dataset)\n epoch_duration = calc_duration/calc_fraction\n epoch_max_secs = (epoch_max-(epoch+calc_fraction))*epoch_duration \n epoch_max_end = epoch_max_secs + time.time() # This is since the epoch in seconds\n print(\"Time used for %.2f of epoch %d: %.1f seconds\" % (calc_fraction, epoch, calc_duration, ))\n print(\" Time per 1000 lines : %.3f seconds\" % (epoch_duration/len(train_dataset)*1000., ))\n print(\" Expected finish in : %.2f hours\" % ( epoch_max_secs/60/60, ))\n #print(\" Expected finish time : %s (server)\" % ( datetime.fromtimestamp(epoch_max_end).strftime(\"%A, %B %d, %Y %H:%M:%S %Z%z\"), ))\n print(\" Expected finish time : %s (%s)\" % ( \n datetime.fromtimestamp(epoch_max_end, timezone.utc).astimezone(tz=tz).strftime(\"%A, %B %d, %Y %H:%M:%S %Z%z\"), args.tz, ))\n \n #print(\" Expected finish time : %s (local)\" % ( tz.localize(datetime.fromtimestamp(epoch_max_end)).strftime(\"%A, %B %d, %Y %H:%M:%S %Z%z\"), ))\n \n time_estimate_last = time.time() # Keep track of estimate times\n \n # https://stackoverflow.com/questions/1398674/display-the-time-in-a-different-time-zone\n \n # import time, pytz\n # from datetime import datetime, timezone\n # datetime.fromtimestamp(1247634536).strftime(\"%A, %B %d, %Y %H:%M:%S %Z%z\")\n # datetime.fromtimestamp(time.time()).strftime(\"%A, %B %d, %Y %H:%M:%S %Z%z\") # GCP appears to report in UTC\n # datetime.fromtimestamp(time.time(), timezone.utc).strftime(\"%A, %B %d, %Y %I:%M:%S %Z%z\") \n # tz = pytz.timezone('Asia/Singapore')\n # datetime.fromtimestamp(time.time(), timezone.utc).astimezone(tz=tz).strftime(\"%A, %B %d, %Y %H:%M:%S %Z%z\")\n\n \n idx_loss_check -= len(train_dataset)/batch_size # Keep track of reset idxs\n \n #epoch_duration = time.time()-start\n #epoch_max_end = (epoch_max-epoch)*epoch_duration + time.time()\n #print(\"Time used in epoch %d: %.1f seconds\" % (epoch, epoch_duration, ))\n #print(\" Expected finish time : %s (server)\" % ( datetime.fromtimestamp(epoch_max_end).strftime(\"%A, %B %d, %Y %H:%M:%S %Z%z\"), ))\n #print(\" Expected finish time : %s (local)\" % ( datetime.fromtimestamp(epoch_max_end).astimezone(tz).strftime(\"%A, %B %d, %Y %H:%M:%S %Z%z\"), ))\n\n # End-of-epoch saving\n fname = './checkpoints/model-stepwise_%s_%04d-%06d_end-epoch.pth' % (args.stub, epoch, idx*batch_size,)\n print(\"Saving End-epoch checkpoint : '%s'\" % (fname, ))\n torch.save(dict(\n epoch=epoch,\n model=model_stepwise.state_dict(), \n optimizer=model_opt.state_dict(), \n ), fname)\n \n except KeyboardInterrupt:\n print(\"Interrupted. Releasing resources...\")\n \n finally:\n train_dataset.close()\n\n exit(0) \n"
] |
[
[
"torch.nn.Dropout",
"torch.nn.CrossEntropyLoss",
"torch.ones",
"numpy.sqrt",
"numpy.random.seed",
"numpy.clip",
"torch.load",
"torch.manual_seed",
"numpy.arange",
"numpy.nonzero",
"torch.utils.data.DataLoader",
"torch.matmul",
"torch.nn.DataParallel",
"torch.cuda.manual_seed_all",
"torch.cuda.is_available",
"torch.cuda.device_count",
"numpy.array"
]
] |
shhong/pycabnn
|
[
"e346b5436d3bf265b527669708eb611a8cf12abc"
] |
[
"notebooks/fig_POPGEN/plot_cell_position_figures.py"
] |
[
"# %%\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport pds_plots as ppl\n\n# %%\nfname = \"../../test_data/generated_positions/coords_20190626_1_6.npz\"\nf = np.load(fname)\n\nbbox = [[0, 700], [0-20, 700], [0, 200]]\n\n\ndef limit_to_box(x, box):\n mf = x.copy()\n for i, t in enumerate(box):\n mf = mf[mf[:,i]>=t[0], :]\n mf = mf[mf[:,i]<=t[1], :]\n return mf\n\n\ndef fix_coors(x):\n y = x-np.ones(x.shape[1])*25\n box = [bbox[0], [bbox[1][0]+20, bbox[1][1]], bbox[2]]\n return limit_to_box(y, box[:x.shape[1]])\n\n\nmf = f['mf']\nmf = fix_coors(mf)\n\n\n# %%\nbbox = [[0, 1500], [0-20, 700], [0, 200]]\n\nmf = f['mf']\nmf = fix_coors(mf)\n\nbbox = [[0, 700*8/5], [0-10, 700], [0, 200]]\nbbox2 = bbox[:2]\n\nplt.style.use('dark_background')\nax = ppl.plot_mf_1(mf, bbox2, 8/2, save=False)\nax.plot([bbox2[0][1]-100, bbox2[0][1]], [bbox2[1][0]+2.5, bbox2[1][0]+2.5], 'w', linewidth=10)\n# ppl.plot_mf_2(mf, [1500, 700], save=True)\nplt.tight_layout()\nplt.savefig('mf.png', dpi=600)\n\n\n# %%\nbbox = [[0, 200*8/5], [0-20, 200], [0, 200]]\n\ngoc = f['goc']\ngoc = fix_coors(goc)\n\nplt.style.use('dark_background')\n\nax = ppl.plot_goc(goc, bbox, 100, 13.5)\nax.plot([bbox[0][1]-100, bbox[0][1]], [bbox[1][0], bbox[1][0]], 'w', linewidth=15)\nplt.savefig('goc_topview.png', dpi=600)\n\n# %%\nglo = f['glo']\nglo = fix_coors(glo)\n\nax = ppl.plot_goc_glo((goc, 13.5), (glo, 7.6 / 2), bbox, 100)\nax.plot([bbox[0][1]-100, bbox[0][1]], [bbox[1][0], bbox[1][0]], 'w', linewidth=15)\nplt.savefig('goc+glo_topview.png', dpi=600)\n# plt.savefig('goc+glo.png', dpi=300\n\n# %%\ngrc0 = f['grc_nop']\ngrx = grc0 + np.random.randn(*grc0.shape)*0.2\ngrc = fix_coors(grx)\n\nax = ppl.plot_all_pop(\n (goc, 13.5),\n (glo, 7.6 / 2),\n (grc, 3),\n bbox, 100)\nax.plot([bbox[0][1]-100, bbox[0][1]], [bbox[1][0], bbox[1][0]], 'w', linewidth=15)\nplt.savefig('all_topview.png', dpi=300)\n\n# %%\nfname = \"../../test_data/generated_positions/coords_20190626_1_6.npz\"\n\nf = np.load(fname)\n\n\nbbox = [[0, 1500], [0-10, 700], [0, 200]]\n\n\nmf = f['mf']\nmf = fix_coors(mf)\n\ngoc = f['goc']\ngoc = fix_coors(goc)\n\nglo = f['glo']\nglo = fix_coors(glo)\n\ngrc0 = f['grc_nop']\ngrx = grc0 + np.random.randn(*grc0.shape)*0.2\ngrc = fix_coors(grx)\n\n\n\ndef to_saggit(x):\n y = x.copy()\n y[:,0] = x[:,1]\n y[:,1] = x[:,2]\n y[:,2] = x[:,0] \n return y\n\ndef to_medlat(x):\n y = x.copy()\n y[:,0] = x[:,0]\n y[:,1] = x[:,2]\n y[:,2] = x[:,1]\n return y\n\n\ngoc1 = to_saggit(goc)\nglo1 = to_saggit(glo)\ngrc1 = to_saggit(grc)\n\n\n\nbbox = [[200, 200+200*8/5], [0-10, 200], [0, 500]]\n\n\nax = ppl.plot_goc(goc1, bbox, 100, 13.5)\nax.plot([bbox[0][1]-100, bbox[0][1]], [bbox[1][0], bbox[1][0]], 'w', linewidth=15)\nplt.savefig('goc_sag.png', dpi=600)\n\n# %%\nbbox = [[200, 200+200*8/5], [0-10, 200], [0, 500]]\n\nax = ppl.plot_goc_glo((goc1, 13.5), (glo1, 7.6 / 2), bbox, 100)\nax.plot([bbox[0][1]-100, bbox[0][1]], [bbox[1][0], bbox[1][0]], 'w', linewidth=15)\nplt.savefig('goc+glo_sag.png', dpi=600)\n\n# %%\nbbox = [[200, 200+200*8/5], [0-10, 200], [0, 500]]\n\nax = ppl.plot_all_pop(\n (goc1, 13.5),\n (glo1, 7.6/2),\n (grc1, 6.15/2),\n bbox, 100)\nax.plot([bbox[0][1]-100, bbox[0][1]], [bbox[1][0], bbox[1][0]], 'w', linewidth=15)\nplt.savefig('all_sag.png', dpi=600)\n\n"
] |
[
[
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.savefig",
"numpy.ones",
"numpy.random.randn",
"numpy.load",
"matplotlib.pyplot.style.use"
]
] |
davidmpinho/public-vs-priv-schools
|
[
"ad02a289410bdceecf5be749f102b6136857b773"
] |
[
"src/school_rank/pipelines.py"
] |
[
"from itemadapter import ItemAdapter\nimport pandas as pd\nfrom sqlalchemy import create_engine\n\n\nclass CsvPipeline:\n def process_item(self, item, spider):\n print('Processing item ' + item['name_file'])\n d_item = ItemAdapter(item).asdict()\n\n # TODO: add the html file names to the files \n # TODO: change the names of repeated columns (those are mentioned in the shell scripts)\n def df_dict(d):\n return pd.DataFrame.from_dict(d)\n df_dict(d_item['table_main']\n ).to_csv('./data/output/grades.csv')\n df_dict(d_item['table_aux']['grade_averages']['exam']\n ).to_csv('./data/output/grade_averages_exam.csv')\n df_dict(d_item['table_aux']['grade_averages']['internal']\n ).to_csv('./data/output/grade_averages_internal.csv')\n df_dict(d_item['table_aux']['retention_rate']['school_average']\n ).to_csv('./data/output/ret_rate_school.csv')\n df_dict(d_item['table_aux']['indicators']['school_average']\n ).to_csv('./data/output/indicator_school.csv')\n df_dict(d_item['table_aux']['parents_education']\n ).to_csv('./data/output/parental_edu.csv')\n\n # TODO: this return statement is causing the dict to be in the logs.\n # But without it nothing works; I think yield gave the same issue\n return item\n\n\nclass SqlitePipeline:\n def process_item(self, item, spider):\n d_item = ItemAdapter(item).asdict()\n print('Processing item ' + item['name_file'])\n\n def df_dict(d):\n return pd.DataFrame.from_dict(d)\n engine = create_engine('sqlite://' + spider.path_db\n + item['name_file'] + '.sqlite')\n\n # TODO: add if_exists='replace' to .to_sql\n df_dict(d_item['table_main']\n ).to_sql('grades', con=engine)\n df_dict(d_item['table_aux']['grade_averages']['exam']\n ).to_sql('grade_averages_exam', con=engine)\n df_dict(d_item['table_aux']['grade_averages']['internal']\n ).to_sql('grade_averages_internal', con=engine)\n df_dict(d_item['table_aux']['retention_rate']['school_average']\n ).to_sql('ret_rate_school', con=engine)\n df_dict(d_item['table_aux']['indicators']['school_average']\n ).to_sql('indicator_school', con=engine)\n df_dict(d_item['table_aux']['parents_education']\n ).to_sql('parental_edu', con=engine)\n # TODO: close connection\n return item\n\n"
] |
[
[
"pandas.DataFrame.from_dict"
]
] |
yalechang/adversarial-robustness-toolbox
|
[
"df4efc86c3ed963c82687b3ab8cd5cdbd5fe5c57"
] |
[
"art/attacks/fast_gradient_unittest.py"
] |
[
"# MIT License\n#\n# Copyright (C) IBM Corporation 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport unittest\n\nimport keras.backend as k\nimport tensorflow as tf\n\nfrom art.attacks.fast_gradient import FastGradientMethod\nfrom art.classifiers.cnn import CNN\nfrom art.utils import load_mnist, get_labels_np_array\n\n\nclass TestFastGradientMethod(unittest.TestCase):\n def test_mnist(self):\n session = tf.Session()\n k.set_session(session)\n\n comp_params = {\"loss\": 'categorical_crossentropy',\n \"optimizer\": 'adam',\n \"metrics\": ['accuracy']}\n\n # get MNIST\n batch_size, nb_train, nb_test = 100, 1000, 100\n (X_train, Y_train), (X_test, Y_test), _, _ = load_mnist()\n X_train, Y_train = X_train[:nb_train], Y_train[:nb_train]\n X_test, Y_test = X_test[:nb_test], Y_test[:nb_test]\n im_shape = X_train[0].shape\n\n # get classifier\n classifier = CNN(im_shape, act=\"relu\")\n classifier.compile(comp_params)\n classifier.fit(X_train, Y_train, epochs=1, batch_size=batch_size, verbose=0)\n scores = classifier.evaluate(X_train, Y_train)\n print(\"\\naccuracy on training set: %.2f%%\" % (scores[1] * 100))\n scores = classifier.evaluate(X_test, Y_test)\n print(\"\\naccuracy on test set: %.2f%%\" % (scores[1] * 100))\n\n attack_params = {\"verbose\": 0,\n \"clip_min\": 0.,\n \"clip_max\": 1.,\n \"eps\": 1.}\n\n attack = FastGradientMethod(classifier, session)\n X_train_adv = attack.generate(X_train, **attack_params)\n X_test_adv = attack.generate(X_test, **attack_params)\n\n self.assertFalse((X_train == X_train_adv).all())\n self.assertFalse((X_test == X_test_adv).all())\n\n train_y_pred = get_labels_np_array(classifier.predict(X_train_adv))\n test_y_pred = get_labels_np_array(classifier.predict(X_test_adv))\n\n self.assertFalse((Y_train == train_y_pred).all())\n self.assertFalse((Y_test == test_y_pred).all())\n\n scores = classifier.evaluate(X_train_adv, Y_train)\n print('\\naccuracy on adversarial train examples: %.2f%%' % (scores[1] * 100))\n\n scores = classifier.evaluate(X_test_adv, Y_test)\n print('\\naccuracy on adversarial test examples: %.2f%%' % (scores[1] * 100))\n\n # test minimal perturbations\n attack_params = {\"verbose\": 0,\n \"clip_min\": 0.,\n \"clip_max\": 1.,\n \"minimal\": True,\n \"eps_step\": .1,\n \"eps_max\": 1.}\n\n X_train_adv_min = attack.generate(X_train, **attack_params)\n X_test_adv_min = attack.generate(X_test, **attack_params)\n\n self.assertFalse((X_train_adv_min == X_train_adv).all())\n self.assertFalse((X_test_adv_min == X_test_adv).all())\n\n self.assertFalse((X_train == X_train_adv_min).all())\n self.assertFalse((X_test == X_test_adv_min).all())\n\n train_y_pred = get_labels_np_array(classifier.predict(X_train_adv_min))\n test_y_pred = get_labels_np_array(classifier.predict(X_test_adv_min))\n\n self.assertFalse((Y_train == train_y_pred).all())\n self.assertFalse((Y_test == test_y_pred).all())\n\n scores = classifier.evaluate(X_train_adv_min, Y_train)\n print('\\naccuracy on adversarial train examples with minimal perturbation: %.2f%%' % (scores[1] * 100))\n\n scores = classifier.evaluate(X_test_adv_min, Y_test)\n print('\\naccuracy on adversarial test examples with minimal perturbation: %.2f%%' % (scores[1] * 100))\n\n def test_with_preprocessing(self):\n\n session = tf.Session()\n k.set_session(session)\n\n comp_params = {\"loss\": 'categorical_crossentropy',\n \"optimizer\": 'adam',\n \"metrics\": ['accuracy']}\n\n # get MNIST\n batch_size, nb_train, nb_test = 100, 1000, 100\n (X_train, Y_train), (X_test, Y_test), _, _ = load_mnist()\n X_train, Y_train = X_train[:nb_train], Y_train[:nb_train]\n X_test, Y_test = X_test[:nb_test], Y_test[:nb_test]\n im_shape = X_train[0].shape\n\n # get classifier\n classifier = CNN(im_shape, act=\"relu\", defences=[\"featsqueeze1\"])\n classifier.compile(comp_params)\n classifier.fit(X_train, Y_train, epochs=1, batch_size=batch_size, verbose=0)\n scores = classifier.evaluate(X_train, Y_train)\n print(\"\\naccuracy on training set: %.2f%%\" % (scores[1] * 100))\n scores = classifier.evaluate(X_test, Y_test)\n print(\"\\naccuracy on test set: %.2f%%\" % (scores[1] * 100))\n\n attack_params = {\"verbose\": 0,\n \"clip_min\": 0.,\n \"clip_max\": 1.,\n \"eps\": 1.}\n\n attack = FastGradientMethod(classifier, session)\n X_train_adv = attack.generate(X_train, **attack_params)\n X_test_adv = attack.generate(X_test, **attack_params)\n\n self.assertFalse((X_train == X_train_adv).all())\n self.assertFalse((X_test == X_test_adv).all())\n\n train_y_pred = get_labels_np_array(classifier.predict(X_train_adv))\n test_y_pred = get_labels_np_array(classifier.predict(X_test_adv))\n\n self.assertFalse((Y_train == train_y_pred).all())\n self.assertFalse((Y_test == test_y_pred).all())\n\n scores = classifier.evaluate(X_train_adv, Y_train)\n print('\\naccuracy on adversarial train examples: %.2f%%' % (scores[1] * 100))\n\n scores = classifier.evaluate(X_test_adv, Y_test)\n print('\\naccuracy on adversarial test examples: %.2f%%' % (scores[1] * 100))\n\nif __name__ == '__main__':\n unittest.main()\n"
] |
[
[
"tensorflow.Session"
]
] |
FyodorLikhachev/Keyworder
|
[
"70c3f1057d382a84bbb0079980b5b7b96fbdbb7d"
] |
[
"metrics.py"
] |
[
"from sklearn import metrics\nfrom torch import device\nfrom constants import DEVICE, TRAIN_KEYWORD_MARKER\n\ndevice = device(DEVICE)\n\ndef showMetrics(model ,dataset, title):\n y_pred = []\n y_true = []\n\n for x, y, c in dataset:\n x = x.to(device)\n y = y.to(device)\n c = c\n pred = get_pred(model, x)\n\n y_pred.append(pred)\n y_true.append(c)\n \n pos_correct = [y_true == y_pred for y_true, y_pred in zip(y_true, y_pred) if y_true == 1]\n neg_correct = [y_true == y_pred for y_true, y_pred in zip(y_true, y_pred) if y_true == 0]\n \n accuracy = metrics.accuracy_score(y_true, y_pred)\n precision = metrics.precision_score(y_true, y_pred)\n recall = metrics.recall_score(y_true, y_pred)\n \n print(title)\n print(\"Accuracy: {0} Precision: {1} Recall: {2}\".format(round(accuracy, 2), round(precision, 2), round(recall, 2)))\n print(\"{0} из {1} позитивов\".format(sum(pos_correct), len(pos_correct)))\n print(\"{0} из {1} негативов\".format(sum(neg_correct), len(neg_correct)))\n\ndef GetAccuracy(model, dataset):\n correct = 0\n for i, (x, y, c) in enumerate(dataset):\n pred = get_pred(model, x)\n\n if c == pred:\n correct += 1\n\n return correct/len(dataset)\n\ndef get_pred(model, x):\n return 1 if model(x.to(device))[-TRAIN_KEYWORD_MARKER:-1].argmax(dim=1).sum() > 0 else 0\n"
] |
[
[
"sklearn.metrics.precision_score",
"sklearn.metrics.recall_score",
"sklearn.metrics.accuracy_score"
]
] |
yop0/pykeos
|
[
"02c141cfb3a56a221a3a47ab90b8da047bee2daf"
] |
[
"pykeos/systems/Rossler.py"
] |
[
"from ..systems import ContinuousSys\nfrom ..tools import nd_rand_init\n\nimport numpy as np\n\n\nclass Rossler(ContinuousSys):\n def __init__(self, a=0.1, b=0.1, c=14, n_points=2000, t_min=0, t_max=100):\n def ode(X, t):\n x,y,z = X\n return np.asarray([\n - y - z,\n x + a * y,\n b + z * (x - c)\n ])\n\n def rand_init():\n return nd_rand_init([-10,10],[-10,10],[0,25])\n\n super().__init__(dim=3, map_func=ode, init_func=rand_init, n_points=n_points, t_min=t_min, t_max=t_max)\n"
] |
[
[
"numpy.asarray"
]
] |
jmftrindade/miniplaces_challenge
|
[
"9325e814571000633e233433006b4e913194a34e"
] |
[
"model/alexnet_2/preprocessing/no_preprocessing.py"
] |
[
"# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Provides utilities to preprocess images for the Inception networks.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nfrom tensorflow.python.ops import control_flow_ops\n\n\ndef apply_with_random_selector(x, func, num_cases):\n \"\"\"Computes func(x, sel), with sel sampled from [0...num_cases-1].\n\n Args:\n x: input Tensor.\n func: Python function to apply.\n num_cases: Python int32, number of cases to sample sel from.\n\n Returns:\n The result of func(x, sel), where func receives the value of the\n selector as a python integer, but sel is sampled dynamically.\n \"\"\"\n sel = tf.random_uniform([], maxval=num_cases, dtype=tf.int32)\n # Pass the real x only to one of the func calls.\n return control_flow_ops.merge([\n func(control_flow_ops.switch(x, tf.equal(sel, case))[1], case)\n for case in range(num_cases)])[0]\n\n\ndef distort_color(image, color_ordering=0, fast_mode=True, scope=None):\n \"\"\"Distort the color of a Tensor image.\n\n Each color distortion is non-commutative and thus ordering of the color ops\n matters. Ideally we would randomly permute the ordering of the color ops.\n Rather then adding that level of complication, we select a distinct ordering\n of color ops for each preprocessing thread.\n\n Args:\n image: 3-D Tensor containing single image in [0, 1].\n color_ordering: Python int, a type of distortion (valid values: 0-3).\n fast_mode: Avoids slower ops (random_hue and random_contrast)\n scope: Optional scope for name_scope.\n Returns:\n 3-D Tensor color-distorted image on range [0, 1]\n Raises:\n ValueError: if color_ordering not in [0, 3]\n \"\"\"\n with tf.name_scope(scope, 'distort_color', [image]):\n if fast_mode:\n if color_ordering == 0:\n image = tf.image.random_brightness(image, max_delta=32. / 255.)\n image = tf.image.random_saturation(image, lower=0.5, upper=1.5)\n else:\n image = tf.image.random_saturation(image, lower=0.5, upper=1.5)\n image = tf.image.random_brightness(image, max_delta=32. / 255.)\n else:\n if color_ordering == 0:\n image = tf.image.random_brightness(image, max_delta=32. / 255.)\n image = tf.image.random_saturation(image, lower=0.5, upper=1.5)\n image = tf.image.random_hue(image, max_delta=0.2)\n image = tf.image.random_contrast(image, lower=0.5, upper=1.5)\n elif color_ordering == 1:\n image = tf.image.random_saturation(image, lower=0.5, upper=1.5)\n image = tf.image.random_brightness(image, max_delta=32. / 255.)\n image = tf.image.random_contrast(image, lower=0.5, upper=1.5)\n image = tf.image.random_hue(image, max_delta=0.2)\n elif color_ordering == 2:\n image = tf.image.random_contrast(image, lower=0.5, upper=1.5)\n image = tf.image.random_hue(image, max_delta=0.2)\n image = tf.image.random_brightness(image, max_delta=32. / 255.)\n image = tf.image.random_saturation(image, lower=0.5, upper=1.5)\n elif color_ordering == 3:\n image = tf.image.random_hue(image, max_delta=0.2)\n image = tf.image.random_saturation(image, lower=0.5, upper=1.5)\n image = tf.image.random_contrast(image, lower=0.5, upper=1.5)\n image = tf.image.random_brightness(image, max_delta=32. / 255.)\n else:\n raise ValueError('color_ordering must be in [0, 3]')\n\n # The random_* ops do not necessarily clamp.\n return tf.clip_by_value(image, 0.0, 1.0)\n\n\ndef distorted_bounding_box_crop(image,\n bbox,\n min_object_covered=0.1,\n aspect_ratio_range=(0.75, 1.33),\n area_range=(0.05, 1.0),\n max_attempts=100,\n scope=None):\n \"\"\"Generates cropped_image using a one of the bboxes randomly distorted.\n\n See `tf.image.sample_distorted_bounding_box` for more documentation.\n\n Args:\n image: 3-D Tensor of image (it will be converted to floats in [0, 1]).\n bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]\n where each coordinate is [0, 1) and the coordinates are arranged\n as [ymin, xmin, ymax, xmax]. If num_boxes is 0 then it would use the whole\n image.\n min_object_covered: An optional `float`. Defaults to `0.1`. The cropped\n area of the image must contain at least this fraction of any bounding box\n supplied.\n aspect_ratio_range: An optional list of `floats`. The cropped area of the\n image must have an aspect ratio = width / height within this range.\n area_range: An optional list of `floats`. The cropped area of the image\n must contain a fraction of the supplied image within in this range.\n max_attempts: An optional `int`. Number of attempts at generating a cropped\n region of the image of the specified constraints. After `max_attempts`\n failures, return the entire image.\n scope: Optional scope for name_scope.\n Returns:\n A tuple, a 3-D Tensor cropped_image and the distorted bbox\n \"\"\"\n with tf.name_scope(scope, 'distorted_bounding_box_crop', [image, bbox]):\n # Each bounding box has shape [1, num_boxes, box coords] and\n # the coordinates are ordered [ymin, xmin, ymax, xmax].\n\n # A large fraction of image datasets contain a human-annotated bounding\n # box delineating the region of the image containing the object of interest.\n # We choose to create a new bounding box for the object which is a randomly\n # distorted version of the human-annotated bounding box that obeys an\n # allowed range of aspect ratios, sizes and overlap with the human-annotated\n # bounding box. If no box is supplied, then we assume the bounding box is\n # the entire image.\n sample_distorted_bounding_box = tf.image.sample_distorted_bounding_box(\n tf.shape(image),\n bounding_boxes=bbox,\n min_object_covered=min_object_covered,\n aspect_ratio_range=aspect_ratio_range,\n area_range=area_range,\n max_attempts=max_attempts,\n use_image_if_no_bounding_boxes=True)\n bbox_begin, bbox_size, distort_bbox = sample_distorted_bounding_box\n\n # Crop the image to the specified bounding box.\n cropped_image = tf.slice(image, bbox_begin, bbox_size)\n return cropped_image, distort_bbox\n\n\ndef preprocess_for_train(image, height, width, bbox,\n fast_mode=True,\n scope=None):\n return preprocess_for_eval(image, height, width) \n\n\ndef preprocess_for_eval(image, height, width,\n central_fraction=0.875, scope=None):\n \"\"\"Prepare one image for evaluation.\n\n If height and width are specified it would output an image with that size by\n applying resize_bilinear.\n\n If central_fraction is specified it would crop the central fraction of the\n input image.\n\n Args:\n image: 3-D Tensor of image. If dtype is tf.float32 then the range should be\n [0, 1], otherwise it would converted to tf.float32 assuming that the range\n is [0, MAX], where MAX is largest positive representable number for\n int(8/16/32) data type (see `tf.image.convert_image_dtype` for details).\n height: integer\n width: integer\n central_fraction: Optional Float, fraction of the image to crop.\n scope: Optional scope for name_scope.\n Returns:\n 3-D float Tensor of prepared image.\n \"\"\"\n with tf.name_scope(scope, 'eval_image', [image, height, width]):\n if image.dtype != tf.float32:\n image = tf.image.convert_image_dtype(image, dtype=tf.float32)\n # Crop the central region of the image with an area containing 87.5% of\n # the original image.\n\n if height and width:\n # Resize the image to the specified height and width.\n image = tf.expand_dims(image, 0)\n image = tf.image.resize_bilinear(image, [height, width],\n align_corners=False)\n image = tf.squeeze(image, [0])\n image = tf.subtract(image, 0.5)\n image = tf.multiply(image, 2.0)\n return image\n\n\ndef preprocess_image(image, height, width,\n is_training=False,\n bbox=None,\n fast_mode=True):\n \"\"\"Pre-process one image for training or evaluation.\n\n Args:\n image: 3-D Tensor [height, width, channels] with the image. If dtype is\n tf.float32 then the range should be [0, 1], otherwise it would converted\n to tf.float32 assuming that the range is [0, MAX], where MAX is largest\n positive representable number for int(8/16/32) data type (see\n `tf.image.convert_image_dtype` for details).\n height: integer, image expected height.\n width: integer, image expected width.\n is_training: Boolean. If true it would transform an image for train,\n otherwise it would transform it for evaluation.\n bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]\n where each coordinate is [0, 1) and the coordinates are arranged as\n [ymin, xmin, ymax, xmax].\n fast_mode: Optional boolean, if True avoids slower transformations.\n\n Returns:\n 3-D float Tensor containing an appropriately scaled image\n\n Raises:\n ValueError: if user does not provide bounding box\n \"\"\"\n if is_training:\n return preprocess_for_train(image, height, width, bbox, fast_mode)\n else:\n return preprocess_for_eval(image, height, width)\n"
] |
[
[
"tensorflow.clip_by_value",
"tensorflow.image.resize_bilinear",
"tensorflow.multiply",
"tensorflow.image.random_brightness",
"tensorflow.image.random_hue",
"tensorflow.image.random_contrast",
"tensorflow.shape",
"tensorflow.slice",
"tensorflow.equal",
"tensorflow.expand_dims",
"tensorflow.squeeze",
"tensorflow.subtract",
"tensorflow.image.random_saturation",
"tensorflow.name_scope",
"tensorflow.image.convert_image_dtype",
"tensorflow.random_uniform"
]
] |
kowalskaw/Perspective_transformation
|
[
"dcce673469355898399621b92247a40d94c3ff36"
] |
[
"Prescp_transf/venv_lapt/main.py"
] |
[
"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nl: list = []\nimg = None\nimg_cp = None\n\n\ndef draw_circle(event, x, y, flags, param):\n global l\n global img\n global img_cp\n if event == cv2.EVENT_LBUTTONDOWN:\n cv2.circle(img_cp, (x, y), 5, (255, 0, 0), -1)\n l.append([x, y])\n cv2.imshow('image', img_cp)\n\n if len(l) == 4:\n print(l)\n\n pts1 = np.float32(l)\n pts2 = np.float32([[0, 0], [300, 0], [0, 300], [300, 300]])\n\n M = cv2.getPerspectiveTransform(pts1, pts2)\n dst = cv2.warpPerspective(img, M, (300, 300))\n\n cv2.imshow('Original image', img_cp)\n cv2.imshow('Final', dst)\n img_cp = img.copy()\n l.clear()\n\n\ndef road_straight():\n global img\n global img_cp\n img = cv2.imread('road.jpg')\n img = cv2.resize(img, dsize=(1000, 1000))\n img = cv2.resize(img, (0, 0), fx=0.75, fy=0.75, interpolation=cv2.INTER_NEAREST)\n img_cp = img.copy()\n cv2.namedWindow('image')\n cv2.imshow('image', img)\n cv2.setMouseCallback('image', draw_circle)\n\n cv2.waitKey()\n cv2.destroyAllWindows()\n return\n\n\nroad_straight()\n"
] |
[
[
"numpy.float32"
]
] |
codeupada1/san-antonio-datathon-2019
|
[
"766e6530903be2f9fa5c9d4e93bed243d0e23516",
"766e6530903be2f9fa5c9d4e93bed243d0e23516"
] |
[
"prepare_sso.py",
"prepare_sara.py"
] |
[
"#!/usr/bin/env python\n\n\"\"\"\nThis script contains code used by the following jupytr notebooks:\n\n1. master-sso.ipynb\n2.\n3.\n\n\"\"\"\n\n\n\n# ===========\n# ENVIRONMENT\n# ===========\n\n\nimport os\nimport sys\n\nimport pandas as pd\nimport numpy as np\n\n\n\n# ===========\n# PREPARATION\n# ===========\n\n\ndef missing_values_col(df):\n \"\"\"\n This functions returns the total missing values and\n the percent missing values by column.\n \"\"\"\n null_count = df.isnull().sum()\n null_percentage = (null_count / df.shape[0]) * 100\n empty_count = pd.Series(((df == ' ') | (df == '')).sum())\n empty_percentage = (empty_count / df.shape[0]) * 100\n nan_count = pd.Series(((df == 'nan') | (df == 'NaN')).sum())\n nan_percentage = (nan_count / df.shape[0]) * 100\n return pd.DataFrame({'num_missing': null_count, 'missing_percentage': null_percentage,\n 'num_empty': empty_count, 'empty_percentage': empty_percentage,\n 'nan_count': nan_count, 'nan_percentage': nan_percentage})\n\n\ndef missing_values_row(df):\n \"\"\"\n This functions returns the total missing values and\n the percent missing values by row.\n \"\"\"\n null_count = df.isnull().sum(axis=1)\n null_percentage = (null_count / df.shape[1]) * 100\n return pd.DataFrame({'num_missing': null_count, 'percentage': null_percentage})\n\n\ndef handle_missing_threshold(df, prop_required_column = .3, prop_required_row = .9):\n \"\"\"\n This functions removes columns and rows whose\n count of missing values exceeds threshold.\n \"\"\"\n threshold = int(round(prop_required_column*len(df.index),0))\n df.dropna(axis=1, thresh=threshold, inplace=True)\n threshold = int(round(prop_required_row*len(df.columns),0))\n df.dropna(axis=0, thresh=threshold, inplace=True)\n return df\n\n\ndef count_values(df):\n \"\"\"\n This function counts the value of columns in a dataframe.\n \"\"\"\n for col in df.columns:\n n = df[col].unique().shape[0]\n col_bins = min(n, 10)\n print(f\"{col}:\")\n if df[col].dtype in ['int64', 'float64'] and n > 10:\n print(df[col].value_counts(bins=col_bins, sort=False))\n else:\n print(df[col].value_counts())\n print(\"\\n\")\n\ndef remove_columns(df, columns):\n return df.drop(columns=columns)\n\n\ndef fill_with_zeroes(df, *cols):\n \"\"\"\n This functions returns the column names as input and\n return the dataframe with the\n null values in those columns replace by 0.\n \"\"\"\n for col in cols:\n df[col] = df[col].fillna(0)\n return df\n\n\ndef fill_with_median(df, *cols):\n \"\"\"\n This function fills the NaN values with\n respective median values.\n \"\"\"\n for col in cols:\n df[col] = df[col].fillna(df[col].median())\n return df\n\n\ndef fill_with_none(df, *cols):\n \"\"\"\n This function fills the NaN values with\n 'None' string value.\n \"\"\"\n for col in cols:\n df[col] = df[col].fillna('None')\n return df\n\ndef fill_with_unknown(df, *cols):\n \"\"\"\n This functions fills the NaN values with\n 'Unknown' string value.\n \"\"\"\n for col in cols:\n df[col] = df[col].fillna('Unknown')\n return df\n\ndef lowercase_columns(df):\n \"\"\"\n This function returns a lowercase version of the column values.\n \"\"\"\n df.columns = map(str.lower, df.columns)\n return df\n\ndef lowercase_column_values(df, *columns):\n \"\"\"\n This function returns a lowercase version of the column values.\n \"\"\"\n for col in columns:\n df[col] = df[col].str.lower() \n return df\n\ndef titlecase_column_values(df, *columns):\n \"\"\"\n This function returns a titlecase version of the values.\n \"\"\"\n for col in columns:\n df[col] = df[col].str.title() \n return df\n\n\ndef rename_columns_all(df):\n \"\"\"\n takes in selected dataframe and renames columns to intuitive non-capitalized titles\n \"\"\"\n return df.rename(index=str, columns={'inspkey':'inspection_key',\n 'servno':'service_number',\n 'reportdate':'report_date',\n 'spill_st_name':'spill_street_name',\n 'total_gal':'total_gallons',\n 'galsret':'gallons_returned',\n 'gal':'gallons_1',\n 'spill_start':'spill_start_1',\n 'spill_stop':'spill_stop_1',\n 'hrs':'hours_1',\n 'unitid':'unit_id_1',\n 'unitid2':'unit_id_2',\n 'earz_zone':'edwards_zone',\n 'expr1029':'expr_1029',\n 'pipediam':'pipe_diameter',\n 'pipelen':'pipe_length',\n 'pipetype':'pipe_type',\n 'instyear':'installation_year',\n 'dwndpth':'downstream_depth',\n 'upsdpth':'upstream_depth',\n 'rainfall_less3':'rainfall_less_3',\n 'spill address': 'spill_address_full',\n 'sewerassetexp':'sewer_asset_exp',\n 'prevspill_24mos':'previous_spill_24mos',\n 'unittype':'unit_type',\n 'assettype':'asset_type',\n 'lastclnd':'last_cleaned',\n 'responsetime':'response_time',\n 'responsedttm':'response_datetime',\n 'public notice':'public_notice',\n 'timeint':'time_int',\n 'hrs_2':'hours_2',\n 'gal_2':'gallons_2',\n 'hrs_3':'hours_3',\n 'gal_3':'gallons_3'\n })\ndef lowercase_and_rename(df):\n \"\"\"\n This function changes the column names' case to lowercase\n and renames the column.\n \"\"\"\n return rename_columns_all(lowercase_columns(df))\n\ndef ready_df(df):\n \"\"\"\n This function prepares the dataframe for EDA.\n \"\"\"\n df = remove_columns(df, columns=[ 'sso_id',\n 'inspection_key',\n 'service_number',\n 'comments',\n 'ferguson',\n 'expr_1029',\n 'downstream_depth',\n 'upstream_depth',\n 'sewer_asset_exp',\n 'previous_spill_24mos',\n ])\n df['spill_street_address'] = df['spill_address'].map(str)+ ' ' + df['spill_street_name']\n df = df.drop(columns=['spill_address', 'spill_street_name'])\n df['multiple_spills'] = np.where(df['spill_start_2'].isnull(), False, True)\n df = df.drop(columns=['spill_start_2',\n 'spill_stop_2',\n 'hours_2',\n 'gallons_2',\n 'spill_start_3',\n 'spill_stop_3',\n 'hours_3',\n 'gallons_3',\n 'gallons_1',\n 'spill_address_full'\n ])\n df = df.rename(index=str, columns={ \"spill_start_1\": \"spill_start\",\n \"spill_stop_1\": \"spill_stop\",\n \"hours_1\": \"hours\"})\n df = lowercase_column_values( df, 'unit_type',\n 'asset_type',\n 'cause',\n 'actions',\n 'watershed',\n 'discharge_to',\n 'discharge_route',\n 'pipe_type',\n 'root_cause',\n )\n df = titlecase_column_values(df, 'spill_street_address')\n df[['council_district',\n 'edwards_zone',\n 'num_spills_24mos',\n 'time_int'\n ]] = df[['council_district',\n 'edwards_zone',\n 'num_spills_24mos',\n 'time_int'\n ]].fillna(0.0).astype(int)\n df['installation_year'] = df['installation_year'].fillna(9999).astype(int)\n df[['gallons_returned',\n 'hours',\n 'pipe_diameter',\n 'pipe_length',\n 'inches_no',\n 'rainfall_less_3',\n 'response_time',\n ]] = df[['gallons_returned',\n 'hours',\n 'pipe_diameter',\n 'pipe_length',\n 'inches_no',\n 'rainfall_less_3',\n 'response_time'\n ]].fillna(0.0)\n df[['actions',\n 'unit_id_1',\n 'unit_id_2',\n 'discharge_to',\n 'discharge_route',\n 'pipe_type',\n 'spill_street_address',\n 'unit_type',\n 'asset_type',\n 'root_cause',\n 'steps_to_prevent',\n ]] = df[[ 'actions',\n 'unit_id_1',\n 'unit_id_2',\n 'discharge_to',\n 'discharge_route',\n 'pipe_type',\n 'spill_street_address',\n 'unit_type',\n 'asset_type',\n 'root_cause',\n 'steps_to_prevent',\n ]].fillna('na')\n df['report_date'] = pd.to_datetime(df['report_date'])\n df['response_datetime'] = pd.to_datetime(df['response_datetime'])\n df['last_cleaned'] = pd.to_datetime(df['last_cleaned'])\n\n df.to_csv('data/cleaned_sso_df.csv', index=False)\n\n return df\n\n\n\n# ==================================================\n# MAIN\n# ==================================================\n\n\ndef clear():\n os.system(\"cls\" if os.name == \"nt\" else \"clear\")\n\ndef main():\n \"\"\"Main entry point for the script.\"\"\"\n pass\n\n\nif __name__ == '__main__':\n sys.exit(main())\n\n\n\n\n\n\n\n\n\n\n__authors__ = [\"Joseph Burton\", \"Ednalyn C. De Dios\", \"Sandy Graham\"]\n__copyright__ = \"Copyright 2019, Codeup Data Science\"\n__license__ = \"MIT\"\n__version__ = \"1.0.0\"\n__maintainers__ = \"Ednalyn C. De Dios\"\n__email__ = \"[email protected]\"\n__status__ = \"Prototype\"\n\n",
"#!/usr/bin/env python\n\n\"\"\"\nThis script contains code used by the following jupytr notebooks:\n\n1. master-sso.ipynb\n2.\n3.\n\n\"\"\"\n\n\n\n# ===========\n# ENVIRONMENT\n# ===========\n\n\nimport os\nimport sys\n\nimport pandas as pd\nimport numpy as np\n\n\n\n# ===========\n# PREPARATION\n# ===========\n\n\ndef missing_values_col(df):\n \"\"\"\n This functions returns the total missing values and\n the percent missing values by column.\n \"\"\"\n null_count = df.isnull().sum()\n null_percentage = (null_count / df.shape[0]) * 100\n empty_count = pd.Series(((df == ' ') | (df == '')).sum())\n empty_percentage = (empty_count / df.shape[0]) * 100\n nan_count = pd.Series((df == '-').sum())\n nan_percentage = (nan_count / df.shape[0]) * 100\n return pd.DataFrame({'num_missing': null_count, 'missing_percentage': null_percentage,\n 'num_empty': empty_count, 'empty_percentage': empty_percentage,\n 'dash_count': nan_count, 'dash_percentage': nan_percentage})\n\n\ndef missing_values_row(df):\n \"\"\"\n This functions returns the total missing values and\n the percent missing values by row.\n \"\"\"\n null_count = df.isnull().sum(axis=1)\n null_percentage = (null_count / df.shape[1]) * 100\n return pd.DataFrame({'num_missing': null_count, 'percentage': null_percentage})\n\n\ndef handle_missing_threshold(df, prop_required_column = .3, prop_required_row = .9):\n \"\"\"\n This functions removes columns and rows whose\n count of missing values exceeds threshold.\n \"\"\"\n threshold = int(round(prop_required_column*len(df.index),0))\n df.dropna(axis=1, thresh=threshold, inplace=True)\n threshold = int(round(prop_required_row*len(df.columns),0))\n df.dropna(axis=0, thresh=threshold, inplace=True)\n return df\n\n\ndef count_values(df):\n \"\"\"\n This function counts the value of columns in a dataframe.\n \"\"\"\n for col in df.columns:\n n = df[col].unique().shape[0]\n col_bins = min(n, 10)\n print(f\"{col}:\")\n if df[col].dtype in ['int64', 'float64'] and n > 10:\n print(df[col].value_counts(bins=col_bins, sort=False))\n else:\n print(df[col].value_counts())\n print(\"\\n\")\n\ndef remove_columns(df, columns):\n return df.drop(columns=columns)\n\n\ndef fill_with_zeroes(df, *cols):\n \"\"\"\n This functions returns the column names as input and\n return the dataframe with the\n null values in those columns replace by 0.\n \"\"\"\n for col in cols:\n df[col] = df[col].fillna(0)\n return df\n\n\ndef fill_with_median(df, *cols):\n \"\"\"\n This function fills the NaN values with\n respective median values.\n \"\"\"\n for col in cols:\n df[col] = df[col].fillna(df[col].median())\n return df\n\n\ndef fill_with_none(df, *cols):\n \"\"\"\n This function fills the NaN values with\n 'None' string value.\n \"\"\"\n for col in cols:\n df[col] = df[col].fillna('None')\n return df\n\ndef fill_with_unknown(df, *cols):\n \"\"\"\n This functions fills the NaN values with\n 'Unknown' string value.\n \"\"\"\n for col in cols:\n df[col] = df[col].fillna('Unknown')\n return df\n\ndef lowercase_columns(df):\n \"\"\"\n This function returns a lowercase version of the column values.\n \"\"\"\n df.columns = map(str.lower, df.columns)\n return df\n\ndef lowercase_column_values(df, *columns):\n \"\"\"\n This function returns a lowercase version of the column values.\n \"\"\"\n for col in columns:\n df[col] = df[col].str.lower() \n return df\n\ndef titlecase_column_values(df, *columns):\n \"\"\"\n This function returns a titlecase version of the values.\n \"\"\"\n for col in columns:\n df[col] = df[col].str.title() \n return df\n\n\ndef rename_columns_all(df):\n \"\"\"\n takes in selected dataframe and renames columns to intuitive non-capitalized titles\n \"\"\"\n return df.rename(index=str, columns={'station id':'station_id',\n 'end date':'date',\n 'oxygen, dissolved (mg/l) (00300)':'oxygen',\n 'e. coli, colilert, idexx method, mpn/100ml (31699)':'ecoli_idexx',\n 'e coli,na+mug or ea+mug,24hrs, 35 degree (#/100m (31700)':'ecoli_mug',\n 'e coli, sediment, mpn/100g (31702)':'ecoli_sediment',\n 'e.coli, colilert, idexx, holding time (31704)':'ecoili_holding_time',\n 'days since precipitation event (days) (72053)':'days_since_precipitation',\n 'present weather (1=clear,2=ptcldy,3=cldy,4=rain,5=other) (89966)':'present_weather',\n 'water color 1=brwn 2=red 3=grn 4=blck 5=clr 6=ot (89969)':'water_color',\n })\ndef lowercase_and_rename(df):\n \"\"\"\n This function changes the column names' case to lowercase\n and renames the column.\n \"\"\"\n return rename_columns_all(lowercase_columns(df))\n\ndef ready_df1(df):\n \"\"\"\n This function prepares the dataframe for EDA.\n \"\"\"\n df = remove_columns(df, columns=[ 'ecoli_mug',\n 'ecoli_sediment',\n ])\n\n\n df[['council_district',\n 'edwards_zone',\n 'num_spills_24mos',\n 'time_int'\n ]] = df[[ 'council_district',\n 'edwards_zone',\n 'num_spills_24mos',\n 'time_int'\n ]].fillna(0.0).astype(int)\n df['installation_year'] = df['installation_year'].fillna(9999).astype(int)\n df[['gallons_returned',\n 'hours',\n 'pipe_diameter',\n 'pipe_length',\n 'inches_no',\n 'rainfall_less_3',\n 'response_time',\n ]] = df[['gallons_returned',\n 'hours',\n 'pipe_diameter',\n 'pipe_length',\n 'inches_no',\n 'rainfall_less_3',\n 'response_time'\n ]].fillna(0.0)\n df[['actions',\n 'unit_id_1',\n 'unit_id_2',\n 'discharge_to',\n 'discharge_route',\n 'pipe_type',\n 'spill_street_address',\n 'unit_type',\n 'asset_type',\n 'root_cause',\n 'steps_to_prevent',\n ]] = df[[ 'actions',\n 'unit_id_1',\n 'unit_id_2',\n 'discharge_to',\n 'discharge_route',\n 'pipe_type',\n 'spill_street_address',\n 'unit_type',\n 'asset_type',\n 'root_cause',\n 'steps_to_prevent',\n ]].fillna('na')\n df['report_date'] = pd.to_datetime(df['report_date'])\n df['response_datetime'] = pd.to_datetime(df['response_datetime'])\n df['last_cleaned'] = pd.to_datetime(df['last_cleaned'])\n return df\n\n\n\n# ==================================================\n# MAIN\n# ==================================================\n\n\ndef clear():\n os.system(\"cls\" if os.name == \"nt\" else \"clear\")\n\ndef main():\n \"\"\"Main entry point for the script.\"\"\"\n pass\n\n\nif __name__ == '__main__':\n sys.exit(main())\n\n\n\n\n\n\n\n\n\n\n__authors__ = [\"Joseph Burton\", \"Ednalyn C. De Dios\", \"Sandy Graham\"]\n__copyright__ = \"Copyright 2019, Codeup Data Science\"\n__license__ = \"MIT\"\n__version__ = \"1.0.0\"\n__maintainers__ = \"Ednalyn C. De Dios\"\n__email__ = \"[email protected]\"\n__status__ = \"Prototype\"\n\n"
] |
[
[
"pandas.to_datetime",
"pandas.DataFrame"
],
[
"pandas.to_datetime",
"pandas.DataFrame"
]
] |
prcaaf/kornia
|
[
"87a0ead264ce5fc97997071acb9fe2286d6c425c"
] |
[
"kornia/geometry/transform/crop/crop2d.py"
] |
[
"from typing import Tuple, Union\n\nimport torch\n\nfrom kornia.geometry.transform.imgwarp import (\n warp_perspective, get_perspective_transform, warp_affine\n)\n\n__all__ = [\n \"crop_and_resize\",\n \"crop_by_boxes\",\n \"center_crop\",\n \"bbox_to_mask\",\n \"infer_box_shape\",\n \"validate_bboxes\",\n \"bbox_generator\"\n]\n\n\ndef crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int, int],\n interpolation: str = 'bilinear', align_corners: bool = False) -> torch.Tensor:\n r\"\"\"Extract crops from 2D images (4D tensor) and resize them.\n\n Args:\n tensor (torch.Tensor): the 2D image tensor with shape (B, C, H, W).\n boxes (torch.Tensor): a tensor containing the coordinates of the bounding boxes to be extracted.\n The tensor must have the shape of Bx4x2, where each box is defined in the following (clockwise)\n order: top-left, top-right, bottom-right and bottom-left. The coordinates must be in the x, y order.\n The coordinates would compose a rectangle with a shape of (N1, N2).\n size (Tuple[int, int]): a tuple with the height and width that will be\n used to resize the extracted patches.\n interpolation (str): Interpolation flag. Default: 'bilinear'.\n align_corners (bool): mode for grid_generation. Default: False. See\n https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details.\n\n Returns:\n torch.Tensor: tensor containing the patches with shape BxCxN1xN2.\n\n Example:\n >>> input = torch.tensor([[\n [1., 2., 3., 4.],\n [5., 6., 7., 8.],\n [9., 10., 11., 12.],\n [13., 14., 15., 16.],\n ]])\n >>> boxes = torch.tensor([[\n [1., 1.],\n [2., 1.],\n [2., 2.],\n [1., 2.],\n ]]) # 1x4x2\n >>> kornia.crop_and_resize(input, boxes, (2, 2))\n tensor([[[ 6.0000, 7.0000],\n [ 10.0000, 11.0000]]])\n \"\"\"\n if not isinstance(tensor, torch.Tensor):\n raise TypeError(\"Input tensor type is not a torch.Tensor. Got {}\"\n .format(type(tensor)))\n if not isinstance(boxes, torch.Tensor):\n raise TypeError(\"Input boxes type is not a torch.Tensor. Got {}\"\n .format(type(boxes)))\n if not isinstance(size, (tuple, list,)) and len(size) == 2:\n raise ValueError(\"Input size must be a tuple/list of length 2. Got {}\"\n .format(size))\n assert len(tensor.shape) == 4, f\"Only tensor with shape (B, C, H, W) supported. Got {tensor.shape}.\"\n # unpack input data\n dst_h, dst_w = size\n\n # [x, y] origin\n # top-left, top-right, bottom-right, bottom-left\n points_src: torch.Tensor = boxes\n\n # [x, y] destination\n # top-left, top-right, bottom-right, bottom-left\n points_dst: torch.Tensor = torch.tensor([[\n [0, 0],\n [dst_w - 1, 0],\n [dst_w - 1, dst_h - 1],\n [0, dst_h - 1],\n ]], device=tensor.device).expand(points_src.shape[0], -1, -1)\n\n return crop_by_boxes(tensor, points_src, points_dst, interpolation, align_corners)\n\n\ndef center_crop(tensor: torch.Tensor, size: Tuple[int, int],\n interpolation: str = 'bilinear',\n align_corners: bool = True) -> torch.Tensor:\n r\"\"\"Crop the 2D images (4D tensor) at the center.\n\n Args:\n tensor (torch.Tensor): the 2D image tensor with shape (B, C, H, W).\n size (Tuple[int, int]): a tuple with the expected height and width\n of the output patch.\n interpolation (str): Interpolation flag. Default: 'bilinear'.\n align_corners (bool): mode for grid_generation. Default: False. See\n https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details\n Returns:\n torch.Tensor: the output tensor with patches.\n\n Examples:\n >>> input = torch.tensor([[\n [1., 2., 3., 4.],\n [5., 6., 7., 8.],\n [9., 10., 11., 12.],\n [13., 14., 15., 16.],\n ]])\n >>> kornia.center_crop(input, (2, 4))\n tensor([[[ 5.0000, 6.0000, 7.0000, 8.0000],\n [ 9.0000, 10.0000, 11.0000, 12.0000]]])\n \"\"\"\n if not isinstance(tensor, torch.Tensor):\n raise TypeError(\"Input tensor type is not a torch.Tensor. Got {}\"\n .format(type(tensor)))\n if not isinstance(size, (tuple, list,)) and len(size) == 2:\n raise ValueError(\"Input size must be a tuple/list of length 2. Got {}\"\n .format(size))\n assert len(tensor.shape) == 4, f\"Only tensor with shape (B, C, H, W) supported. Got {tensor.shape}.\"\n\n # unpack input sizes\n dst_h, dst_w = size\n src_h, src_w = tensor.shape[-2:]\n\n # compute start/end offsets\n dst_h_half = dst_h / 2\n dst_w_half = dst_w / 2\n src_h_half = src_h / 2\n src_w_half = src_w / 2\n\n start_x = src_w_half - dst_w_half\n start_y = src_h_half - dst_h_half\n\n end_x = start_x + dst_w - 1\n end_y = start_y + dst_h - 1\n # [y, x] origin\n # top-left, top-right, bottom-right, bottom-left\n points_src: torch.Tensor = torch.tensor([[\n [start_x, start_y],\n [end_x, start_y],\n [end_x, end_y],\n [start_x, end_y],\n ]], device=tensor.device)\n\n # [y, x] destination\n # top-left, top-right, bottom-right, bottom-left\n points_dst: torch.Tensor = torch.tensor([[\n [0, 0],\n [dst_w - 1, 0],\n [dst_w - 1, dst_h - 1],\n [0, dst_h - 1],\n ]], device=tensor.device).expand(points_src.shape[0], -1, -1)\n return crop_by_boxes(tensor,\n points_src.to(tensor.dtype),\n points_dst.to(tensor.dtype),\n interpolation,\n align_corners)\n\n\ndef crop_by_boxes(tensor: torch.Tensor, src_box: torch.Tensor, dst_box: torch.Tensor,\n interpolation: str = 'bilinear', align_corners: bool = False) -> torch.Tensor:\n \"\"\"Perform crop transform on 2D images (4D tensor) by bounding boxes.\n\n Given an input tensor, this function selected the interested areas by the provided bounding boxes (src_box).\n Then the selected areas would be fitted into the targeted bounding boxes (dst_box) by a perspective transformation.\n So far, the ragged tensor is not supported by PyTorch right now. This function hereby requires the bounding boxes\n in a batch must be rectangles with same width and height.\n\n Args:\n tensor (torch.Tensor): the 2D image tensor with shape (B, C, H, W).\n src_box (torch.Tensor): a tensor with shape (B, 4, 2) containing the coordinates of the bounding boxes\n to be extracted. The tensor must have the shape of Bx4x2, where each box is defined in the clockwise\n order: top-left, top-right, bottom-right and bottom-left. The coordinates must be in x, y order.\n dst_box (torch.Tensor): a tensor with shape (B, 4, 2) containing the coordinates of the bounding boxes\n to be placed. The tensor must have the shape of Bx4x2, where each box is defined in the clockwise\n order: top-left, top-right, bottom-right and bottom-left. The coordinates must be in x, y order.\n interpolation (str): Interpolation flag. Default: 'bilinear'.\n align_corners (bool): mode for grid_generation. Default: False. See\n https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details\n\n Returns:\n torch.Tensor: the output tensor with patches.\n\n Examples:\n >>> input = torch.arange(16, dtype=torch.float32).reshape((1, 4, 4))\n >>> src_box = torch.tensor([[\n ... [1., 1.],\n ... [2., 1.],\n ... [2., 2.],\n ... [1., 2.],\n ... ]]) # 1x4x2\n >>> dst_box = torch.tensor([[\n ... [0., 0.],\n ... [1., 0.],\n ... [1., 1.],\n ... [0., 1.],\n ... ]]) # 1x4x2\n >>> crop_by_boxes(input, src_box, dst_box, align_corners=True)\n tensor([[[ 5.0000, 6.0000],\n [ 9.0000, 10.0000]]])\n\n Note:\n If the src_box is smaller than dst_box, the following error will be thrown.\n RuntimeError: solve_cpu: For batch 0: U(2,2) is zero, singular U.\n \"\"\"\n validate_bboxes(src_box)\n validate_bboxes(dst_box)\n\n assert len(tensor.shape) == 4, f\"Only tensor with shape (B, C, H, W) supported. Got {tensor.shape}.\"\n\n # compute transformation between points and warp\n # Note: Tensor.dtype must be float. \"solve_cpu\" not implemented for 'Long'\n dst_trans_src: torch.Tensor = get_perspective_transform(src_box.to(tensor.dtype), dst_box.to(tensor.dtype))\n # simulate broadcasting\n dst_trans_src = dst_trans_src.expand(tensor.shape[0], -1, -1).type_as(tensor)\n\n bbox = infer_box_shape(dst_box)\n assert (bbox[0] == bbox[0][0]).all() and (bbox[1] == bbox[1][0]).all(), (\n f\"Cropping height, width and depth must be exact same in a batch. Got height {bbox[0]} and width {bbox[1]}.\")\n patches: torch.Tensor = warp_affine(\n tensor, dst_trans_src[:, :2, :], (int(bbox[0][0].item()), int(bbox[1][0].item())),\n flags=interpolation, align_corners=align_corners)\n\n return patches\n\n\ndef infer_box_shape(boxes: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n r\"\"\"Auto-infer the output sizes for the given 2D bounding boxes.\n\n Args:\n boxes (torch.Tensor): a tensor containing the coordinates of the\n bounding boxes to be extracted. The tensor must have the shape\n of Bx4x2, where each box is defined in the following (clockwise)\n order: top-left, top-right, bottom-right, bottom-left. The\n coordinates must be in the x, y order.\n\n Returns:\n Tuple[torch.Tensor, torch.Tensor]:\n - Bounding box heights, shape of :math:`(B,)`.\n - Boundingbox widths, shape of :math:`(B,)`.\n\n Example:\n >>> boxes = torch.tensor([[\n ... [1., 1.],\n ... [2., 1.],\n ... [2., 2.],\n ... [1., 2.],\n ... ], [\n ... [1., 1.],\n ... [3., 1.],\n ... [3., 2.],\n ... [1., 2.],\n ... ]]) # 2x4x2\n >>> infer_box_shape(boxes)\n (tensor([2., 2.]), tensor([2., 3.]))\n \"\"\"\n validate_bboxes(boxes)\n width: torch.Tensor = (boxes[:, 1, 0] - boxes[:, 0, 0] + 1)\n height: torch.Tensor = (boxes[:, 2, 1] - boxes[:, 0, 1] + 1)\n return (height, width)\n\n\ndef validate_bboxes(boxes: torch.Tensor) -> None:\n \"\"\"Validate if a 2D bounding box usable or not.\n\n This function checks if the boxes are rectangular or not.\n\n Args:\n boxes (torch.Tensor): a tensor containing the coordinates of the\n bounding boxes to be extracted. The tensor must have the shape\n of Bx4x2, where each box is defined in the following (clockwise)\n order: top-left, top-right, bottom-right, bottom-left. The\n coordinates must be in the x, y order.\n \"\"\"\n assert torch.allclose((boxes[:, 1, 0] - boxes[:, 0, 0] + 1), (boxes[:, 2, 0] - boxes[:, 3, 0] + 1)), \\\n \"Boxes must have be rectangular, while get widths %s and %s\" % \\\n (str(boxes[:, 1, 0] - boxes[:, 0, 0] + 1), str(boxes[:, 2, 0] - boxes[:, 3, 0] + 1))\n assert torch.allclose((boxes[:, 2, 1] - boxes[:, 0, 1] + 1), (boxes[:, 3, 1] - boxes[:, 1, 1] + 1)), \\\n \"Boxes must have be rectangular, while get heights %s and %s\" % \\\n (str(boxes[:, 2, 1] - boxes[:, 0, 1] + 1), str(boxes[:, 3, 1] - boxes[:, 1, 1] + 1))\n\n\ndef bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:\n \"\"\"Convert 2D bounding boxes to masks. Covered area is 1. and the remaining is 0.\n\n Args:\n boxes (torch.Tensor): a tensor containing the coordinates of the bounding boxes to be extracted.\n The tensor must have the shape of Bx4x2, where each box is defined in the following (clockwise)\n order: top-left, top-right, bottom-right and bottom-left. The coordinates must be in the x, y order.\n width (int): width of the masked image.\n height (int): height of the masked image.\n\n Returns:\n torch.Tensor: the output mask tensor.\n\n Examples:\n >>> boxes = torch.tensor([[\n ... [1., 1.],\n ... [3., 1.],\n ... [3., 2.],\n ... [1., 2.],\n ... ]]) # 1x4x2\n >>> bbox_to_mask(boxes, 5, 5)\n tensor([[[0., 0., 0., 0., 0.],\n [0., 1., 1., 1., 0.],\n [0., 1., 1., 1., 0.],\n [0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 0.]]])\n \"\"\"\n validate_bboxes(boxes)\n mask = torch.zeros((len(boxes), height, width))\n\n mask_out = []\n # TODO: Looking for a vectorized way\n for m, box in zip(mask, boxes):\n m = m.index_fill(1, torch.arange(box[0, 0].item(), box[1, 0].item() + 1, dtype=torch.long), torch.tensor(1))\n m = m.index_fill(0, torch.arange(box[1, 1].item(), box[2, 1].item() + 1, dtype=torch.long), torch.tensor(1))\n m = m.unsqueeze(dim=0)\n m_out = (m == 1).all(dim=1) * (m == 1).all(dim=2).T\n mask_out.append(m_out)\n\n return torch.stack(mask_out, dim=0).float()\n\n\ndef bbox_generator(\n x_start: torch.Tensor, y_start: torch.Tensor, width: torch.Tensor, height: torch.Tensor\n) -> torch.Tensor:\n \"\"\"Generate 2D bounding boxes according to the provided start coords, width and height.\n\n Args:\n x_start (torch.Tensor): a tensor containing the x coordinates of the bounding boxes to be extracted.\n Shape must be a scalar tensor or :math:`(B,)`.\n y_start (torch.Tensor): a tensor containing the y coordinates of the bounding boxes to be extracted.\n Shape must be a scalar tensor or :math:`(B,)`.\n width (torch.Tensor): widths of the masked image.\n Shape must be a scalar tensor or :math:`(B,)`.\n height (torch.Tensor): heights of the masked image.\n Shape must be a scalar tensor or :math:`(B,)`.\n\n Returns:\n torch.Tensor: the bounding box tensor.\n\n Examples:\n >>> x_start = torch.tensor([0, 1])\n >>> y_start = torch.tensor([1, 0])\n >>> width = torch.tensor([5, 3])\n >>> height = torch.tensor([7, 4])\n >>> bbox_generator(x_start, y_start, width, height)\n tensor([[[0, 1],\n [4, 1],\n [4, 7],\n [0, 7]],\n <BLANKLINE>\n [[1, 0],\n [3, 0],\n [3, 3],\n [1, 3]]])\n \"\"\"\n assert x_start.shape == y_start.shape and x_start.dim() in [0, 1], \\\n f\"`x_start` and `y_start` must be a scalar or (B,). Got {x_start}, {y_start}.\"\n assert width.shape == height.shape and width.dim() in [0, 1], \\\n f\"`width` and `height` must be a scalar or (B,). Got {width}, {height}.\"\n assert x_start.dtype == y_start.dtype == width.dtype == height.dtype, (\n \"All tensors must be in the same dtype. Got \"\n f\"`x_start`({x_start.dtype}), `y_start`({x_start.dtype}), `width`({width.dtype}), `height`({height.dtype}).\"\n )\n assert x_start.device == y_start.device == width.device == height.device, (\n \"All tensors must be in the same device. Got \"\n f\"`x_start`({x_start.device}), `y_start`({x_start.device}), `width`({width.device}), `height`({height.device}).\"\n )\n\n bbox = torch.tensor([[\n [0, 0],\n [0, 0],\n [0, 0],\n [0, 0],\n ]], device=x_start.device, dtype=x_start.dtype).repeat(1 if x_start.dim() == 0 else len(x_start), 1, 1)\n\n bbox[:, :, 0] += x_start.view(-1, 1)\n bbox[:, :, 1] += y_start.view(-1, 1)\n bbox[:, 1, 0] += width\n bbox[:, 2, 0] += width\n bbox[:, 2, 1] += height\n bbox[:, 3, 1] += height\n\n return bbox\n"
] |
[
[
"torch.stack",
"torch.allclose",
"torch.tensor"
]
] |
Drajan/DDxNet
|
[
"c9f9cb09a5c83ae7582255cb2a5aa9c738f7f628"
] |
[
"train.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# Copyright 2019 IBM Corporation and others\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n__author__ = \"Deepta Rajan, Jayaraman J. Thiagarajan\"\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom sklearn.metrics import f1_score, confusion_matrix, accuracy_score\nimport os\nimport argparse\nimport datetime\nfrom utils.data_loader import get_loader\nfrom utils.log import ResultsLog\nfrom model.ddxnet_model import DDxNet, DDx_block\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nprint('Using ', device)\n\ndef main(args):\n args.model_path = os.path.join(args.model_path, str(datetime.date.today()))\n if not os.path.exists(args.model_path):\n os.makedirs(args.model_path)\n\n loss_fn = nn.CrossEntropyLoss()\n softmax = nn.Softmax(dim=1)\n\n # Build DDxNet with 4 DDx blocks of convolutions\n model = DDxNet(args.num_channels, args.num_timesteps, DDx_block, [2,6,8,4],\n args.output_dim, causal=True, use_dilation=True).to(device)\n\n # multi-gpu training if available\n if(torch.cuda.device_count() > 1):\n print(\"Let's use\", torch.cuda.device_count(), \"GPUs!\")\n model = nn.DataParallel(model)\n model = model.to(device)\n\n\n optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate, betas=(0.9, 0.98))\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', patience=2, factor=0.1**0.75, verbose=True)\n\n train_loader = get_loader(args.data_dir, 'train', args.batch_size, args.shuffle)\n test_loader = get_loader(args.data_dir, 'test', args.batch_size, shuffle=False)\n best_val_acc = 0.\n\n if not os.path.exists(os.path.join('./logs', str(datetime.date.today()))):\n os.makedirs(os.path.join('./logs', str(datetime.date.today())))\n\n results_file = os.path.join('./logs', str(datetime.date.today()), args.results_file)\n results = ResultsLog(results_file)\n\n for epoch in range(args.num_epochs):\n avg_loss = 0.\n total_predlabs = []\n total_truelabs = []\n total_probs =[]\n\n for itr, (X, y_true) in enumerate(train_loader):\n model.train()\n X = X.to(device).float()\n y_true = y_true.to(device).long()\n\n y_pred = model(X)\n loss = loss_fn(y_pred, torch.max(y_true,1)[1])\n avg_loss += loss.item()/len(train_loader)\n\n optimizer.zero_grad()\n loss.backward()\n if args.clip_grad > 0:\n torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip_grad)\n optimizer.step()\n\n probs = softmax(y_pred)\n _, predlabs = torch.max(probs.data, 1)\n total_probs.extend(probs.data.cpu().numpy())\n total_predlabs.extend(predlabs.data.cpu().numpy())\n total_truelabs.extend(torch.max(y_true,1)[1].data.cpu().numpy())\n batch_acc = accuracy_score(torch.max(y_true,1)[1].data.cpu().numpy(), predlabs.data.cpu().numpy())\n\n if (itr+1) % 50 == 0:\n print(('Epoch: {} Iter: {}/{} Loss: {} Acc: {}').format(epoch,itr+1,len(train_loader), loss.item(), batch_acc))\n\n if((itr+1) % len(train_loader)) == 0:\n total_truelabs = np.array(total_truelabs)\n total_predlabs = np.array(total_predlabs)\n total_probs = np.array(total_probs)\n total_train_acc = accuracy_score(total_truelabs, total_predlabs)\n\n f1 = f1_score(total_truelabs, total_predlabs, average='macro')\n res = {'epoch': epoch + (itr*1.0+1.0)/len(train_loader),\n 'steps': epoch*len(train_loader) + itr+1,\n 'train_loss': avg_loss,\n 'train_f1': f1,\n 'train_acc': total_train_acc}\n\n model.eval()\n\n with torch.no_grad():\n total_predlabs = []\n total_probs = []\n total_truelabs = []\n total_val_loss = 0.\n\n for i, (dat, labs) in enumerate(test_loader):\n dat = dat.to(device).float()\n labs = labs.to(device).long()\n y_pred = model(dat)\n val_loss = loss_fn(y_pred, torch.max(labs,1)[1])\n\n probs = softmax(y_pred)\n _, predlabs = torch.max(probs.data, 1)\n total_probs.extend(probs.data.cpu().numpy())\n total_predlabs.extend(predlabs.data.cpu().numpy())\n total_truelabs.extend(torch.max(labs,1)[1].data.cpu().numpy())\n total_val_loss += (val_loss.item()/len(test_loader))\n\n total_truelabs = np.array(total_truelabs)\n total_predlabs = np.array(total_predlabs)\n total_probs = np.array(total_probs)\n total_val_acc = accuracy_score(total_truelabs, total_predlabs)\n\n total_val_f1 = f1_score(total_truelabs, total_predlabs, average='macro')\n print(\"At Epoch: {}, Iter: {}, val_loss: {}, val_acc: {}\".format(epoch, itr+1, total_val_loss, total_val_acc))\n print(\"Confusion Matrix: \")\n print(confusion_matrix(total_truelabs, total_predlabs))\n if(total_val_acc > best_val_acc):\n best_val_acc = total_val_acc\n print(\"saving model\")\n torch.save(model.state_dict(), os.path.join(args.model_path, args.results_file+ '_model.pth'))\n np.savetxt(os.path.join(args.model_path, args.results_file+ '_prob.txt'),total_probs,delimiter=',')\n np.savetxt(os.path.join(args.model_path, args.results_file+ '_pred.txt'),total_predlabs,delimiter=',')\n np.savetxt(os.path.join(args.model_path, args.results_file+ '_true.txt'),total_truelabs,delimiter=',')\n\n res['val_loss'] = total_val_loss\n res['val_acc'] = total_val_acc\n res['val_f1'] = total_val_f1\n\n plot_loss = ['train_loss']\n plot_acc = ['train_acc']\n plot_f1 = ['train_f1']\n\n plot_loss += ['val_loss']\n plot_acc += ['val_acc']\n plot_f1 += ['val_f1']\n\n results.add(**res)\n results.plot(x='epoch', y=plot_loss,\n title='Multi-Class Loss', ylabel='CE Loss')\n results.plot(x='epoch', y=plot_acc,\n title='Accuracy', ylabel='Accuracy')\n results.plot(x='epoch', y=plot_f1,\n title='F1-Score (Macro)', ylabel='F1-Score')\n results.save()\n\n scheduler.step(total_val_loss, epoch)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--results_file', type=str, default = 'results_ecg', help = 'Filename for plot results')\n parser.add_argument('--model_path', type=str, default = './ckpts',\n help = 'Path for storing model checkpoints')\n parser.add_argument('--data_dir', type=str, default = './data', help = 'Directory of pre-processed timeseries data and labels')\n parser.add_argument('--batch_size', type=int, default = 128,\n help = 'batch size')\n parser.add_argument('--shuffle', type=bool, default = True,\n help = 'shuffle')\n parser.add_argument('--learning_rate', type=float, default = 1e-4,\n help = 'learning rate')\n parser.add_argument('--clip_grad', type=float, default = -1,\n help = 'gradient clipping (-1 means no clip)')\n parser.add_argument('--num_epochs', type=int, default = 1,#25,\n help = 'number of epochs')\n parser.add_argument('--num_channels', type=int, default = 1,\n help = 'feature dimension')\n parser.add_argument('--num_timesteps', type=int, default = 187,\n help = 'number of timesteps in every sequence sample')\n parser.add_argument('--output_dim', type=int, default = 5,\n help = 'dimension of output')\n\n\n main(parser.parse_args())\n"
] |
[
[
"torch.nn.Softmax",
"torch.nn.CrossEntropyLoss",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"torch.max",
"sklearn.metrics.confusion_matrix",
"torch.nn.DataParallel",
"torch.no_grad",
"torch.cuda.is_available",
"sklearn.metrics.f1_score",
"torch.cuda.device_count",
"numpy.array",
"sklearn.metrics.accuracy_score"
]
] |
princeton-vl/selfstudy
|
[
"d18ab26c11843557ee75aaccf6ccb63de85b397c"
] |
[
"tasks/cmc.py"
] |
[
"\"\"\"CMC backbone definition.\n\nModified from: https://github.com/HobbitLong/CMC\n\"\"\"\n\nimport gin\n\nimport numpy as np\nimport torch\nfrom torch import nn\n\nfrom .classify import ClassifyTask, ce_loss\n\neps = 1e-7\n\n\n# (not used anymore)\nclass NCECriterion(nn.Module):\n \"\"\"Eq. (12): L_{NCE} \"\"\"\n\n def __init__(self, n_data):\n super(NCECriterion, self).__init__()\n self.n_data = n_data\n\n # noise distribution\n self.Pn = 1 / n_data\n\n def forward(self, x):\n batch_size = x.shape[0]\n K = x.size(1) - 1\n Pn = self.Pn\n\n P_pos = x[:, 0]\n P_neg = x[:, 1:]\n\n # loss for positive pair\n log_D1 = torch.log(P_pos) - torch.log(P_pos + K * Pn + eps)\n # loss for K negative pair\n log_D0 = np.log(K * Pn) - torch.log(P_neg + K * Pn + eps)\n\n loss = -(log_D1.sum(0) + log_D0.view(-1, 1).sum(0)) / batch_size\n\n return loss\n\n\[email protected]\nclass CMCTask(ClassifyTask):\n def evaluate(self, sample, model_out):\n # Calculate downstream FC + MLP loss/accuracies\n results = super().evaluate(sample, model_out, multi_out=True)\n\n out_l, out_ab = model_out[1]\n batch_size = out_l.shape[0]\n zeros = torch.zeros([batch_size]).cuda().long()\n\n l_loss = ce_loss(out_l.squeeze(), zeros)\n ab_loss = ce_loss(out_ab.squeeze(), zeros)\n cmc_loss = l_loss + ab_loss\n\n loss = cmc_loss + results['loss_downstream']\n\n results['loss_l'] = l_loss\n results['loss_ab'] = ab_loss\n results['prob_l'] = out_l[:, 0].mean()\n results['prob_ab'] = out_ab[:, 0].mean()\n\n return loss, results\n"
] |
[
[
"numpy.log",
"torch.log",
"torch.zeros"
]
] |
ashikrafi/stellargraph
|
[
"0f6f24d21ec9c016bb370c2d705af4e876495cb4"
] |
[
"stellargraph/mapper/sampled_node_generators.py"
] |
[
"# -*- coding: utf-8 -*-\n#\n# Copyright 2018-2020 Data61, CSIRO\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nMappers to provide input data for the graph models in layers.\n\n\"\"\"\n__all__ = [\n \"GraphSAGENodeGenerator\",\n \"HinSAGENodeGenerator\",\n \"Attri2VecNodeGenerator\",\n \"DirectedGraphSAGENodeGenerator\",\n]\n\nimport warnings\nimport operator\nimport random\nimport abc\nimport warnings\nimport numpy as np\nimport itertools as it\nimport networkx as nx\nimport scipy.sparse as sps\nfrom tensorflow.keras import backend as K\nfrom functools import reduce\nfrom tensorflow.keras.utils import Sequence\n\nfrom ..data import (\n SampledBreadthFirstWalk,\n SampledHeterogeneousBreadthFirstWalk,\n DirectedBreadthFirstNeighbours,\n)\nfrom ..core.graph import StellarGraph, GraphSchema\nfrom ..core.utils import is_real_iterable\nfrom . import NodeSequence\nfrom ..random import SeededPerBatch\n\n\nclass BatchedNodeGenerator(abc.ABC):\n \"\"\"\n Abstract base class for graph data generators.\n\n The supplied graph should be a StellarGraph object that is ready for\n machine learning. Currently the model requires node features for all\n nodes in the graph.\n\n Do not use this base class: use a subclass specific to the method.\n\n Args:\n G (StellarGraph): The machine-learning ready graph.\n batch_size (int): Size of batch to return.\n schema (GraphSchema): [Optional] Schema for the graph, for heterogeneous graphs.\n \"\"\"\n\n def __init__(self, G, batch_size, schema=None):\n if not isinstance(G, StellarGraph):\n raise TypeError(\"Graph must be a StellarGraph or StellarDiGraph object.\")\n\n self.graph = G\n self.batch_size = batch_size\n\n # This is a node generator and requries a model with one root nodes per query\n self.multiplicity = 1\n\n # Check if the graph has features\n G.check_graph_for_ml()\n\n # We need a schema for compatibility with HinSAGE\n if schema is None:\n self.schema = G.create_graph_schema()\n elif isinstance(schema, GraphSchema):\n self.schema = schema\n else:\n raise TypeError(\"Schema must be a GraphSchema object\")\n\n # We will need real node types here\n self.head_node_types = None\n\n # Create sampler for GraphSAGE\n self.sampler = None\n\n @abc.abstractmethod\n def sample_features(self, head_nodes, batch_num):\n pass\n\n def flow(self, node_ids, targets=None, shuffle=False, seed=None):\n \"\"\"\n Creates a generator/sequence object for training or evaluation\n with the supplied node ids and numeric targets.\n\n The node IDs are the nodes to train or inference on: the embeddings\n calculated for these nodes are passed to the downstream task. These\n are a subset of the nodes in the graph.\n\n The targets are an array of numeric targets corresponding to the\n supplied node_ids to be used by the downstream task. They should\n be given in the same order as the list of node IDs.\n If they are not specified (for example, for use in prediction),\n the targets will not be available to the downstream task.\n\n Note that the shuffle argument should be True for training and\n False for prediction.\n\n Args:\n node_ids: an iterable of node IDs\n targets: a 2D array of numeric targets with shape\n `(len(node_ids), target_size)`\n shuffle (bool): If True the node_ids will be shuffled at each\n epoch, if False the node_ids will be processed in order.\n\n Returns:\n A NodeSequence object to use with with StellarGraph models\n in Keras methods ``fit``, ``evaluate``,\n and ``predict``\n\n \"\"\"\n if self.head_node_types is not None:\n expected_node_type = self.head_node_types[0]\n else:\n expected_node_type = None\n\n # Check all IDs are actually in the graph and are of expected type\n for n in node_ids:\n try:\n node_type = self.graph.node_type(n)\n except KeyError:\n raise KeyError(f\"Node ID {n} supplied to generator not found in graph\")\n\n if expected_node_type is not None and (node_type != expected_node_type):\n raise ValueError(\n f\"Node ID {n} not of expected type {expected_node_type}\"\n )\n\n return NodeSequence(\n self.sample_features,\n self.batch_size,\n node_ids,\n targets,\n shuffle=shuffle,\n seed=seed,\n )\n\n def flow_from_dataframe(self, node_targets, shuffle=False):\n \"\"\"\n Creates a generator/sequence object for training or evaluation\n with the supplied node ids and numeric targets.\n\n Args:\n node_targets: a Pandas DataFrame of numeric targets indexed\n by the node ID for that target.\n shuffle (bool): If True the node_ids will be shuffled at each\n epoch, if False the node_ids will be processed in order.\n\n Returns:\n A NodeSequence object to use with with StellarGraph models\n in Keras methods ``fit``, ``evaluate``,\n and ``predict``\n\n \"\"\"\n return self.flow(node_targets.index, node_targets.values, shuffle=shuffle)\n\n\nclass GraphSAGENodeGenerator(BatchedNodeGenerator):\n \"\"\"\n A data generator for node prediction with Homogeneous GraphSAGE models\n\n At minimum, supply the StellarGraph, the batch size, and the number of\n node samples for each layer of the GraphSAGE model.\n\n The supplied graph should be a StellarGraph object that is ready for\n machine learning. Currently the model requires node features for all\n nodes in the graph.\n\n Use the :meth:`flow` method supplying the nodes and (optionally) targets\n to get an object that can be used as a Keras data generator.\n\n Example::\n\n G_generator = GraphSAGENodeGenerator(G, 50, [10,10])\n train_data_gen = G_generator.flow(train_node_ids, train_node_labels)\n test_data_gen = G_generator.flow(test_node_ids)\n\n Args:\n G (StellarGraph): The machine-learning ready graph.\n batch_size (int): Size of batch to return.\n num_samples (list): The number of samples per layer (hop) to take.\n seed (int): [Optional] Random seed for the node sampler.\n \"\"\"\n\n def __init__(self, G, batch_size, num_samples, seed=None, name=None):\n super().__init__(G, batch_size)\n\n self.num_samples = num_samples\n self.head_node_types = self.schema.node_types\n self.name = name\n\n # Check that there is only a single node type for GraphSAGE\n if len(self.head_node_types) > 1:\n warnings.warn(\n \"running homogeneous GraphSAGE on a graph with multiple node types\",\n RuntimeWarning,\n )\n\n # Create sampler for GraphSAGE\n self._samplers = SeededPerBatch(\n lambda s: SampledBreadthFirstWalk(G, graph_schema=self.schema, seed=s),\n seed=seed,\n )\n\n def sample_features(self, head_nodes, batch_num):\n \"\"\"\n Sample neighbours recursively from the head nodes, collect the features of the\n sampled nodes, and return these as a list of feature arrays for the GraphSAGE\n algorithm.\n\n Args:\n head_nodes: An iterable of head nodes to perform sampling on.\n batch_num (int): Batch number\n\n Returns:\n A list of the same length as ``num_samples`` of collected features from\n the sampled nodes of shape:\n ``(len(head_nodes), num_sampled_at_layer, feature_size)``\n where num_sampled_at_layer is the cumulative product of `num_samples`\n for that layer.\n \"\"\"\n node_samples = self._samplers[batch_num].run(\n nodes=head_nodes, n=1, n_size=self.num_samples\n )\n\n # The number of samples for each head node (not including itself)\n num_full_samples = np.sum(np.cumprod(self.num_samples))\n\n # Reshape node samples to sensible format\n def get_levels(loc, lsize, samples_per_hop, walks):\n end_loc = loc + lsize\n walks_at_level = list(it.chain(*[w[loc:end_loc] for w in walks]))\n if len(samples_per_hop) < 1:\n return [walks_at_level]\n return [walks_at_level] + get_levels(\n end_loc, lsize * samples_per_hop[0], samples_per_hop[1:], walks\n )\n\n nodes_per_hop = get_levels(0, 1, self.num_samples, node_samples)\n node_type = self.head_node_types[0]\n\n # Get features for sampled nodes\n batch_feats = [\n self.graph.node_features(layer_nodes, node_type)\n for layer_nodes in nodes_per_hop\n ]\n\n # Resize features to (batch_size, n_neighbours, feature_size)\n batch_feats = [\n np.reshape(a, (len(head_nodes), -1 if np.size(a) > 0 else 0, a.shape[1]))\n for a in batch_feats\n ]\n return batch_feats\n\n\nclass DirectedGraphSAGENodeGenerator(BatchedNodeGenerator):\n \"\"\"\n A data generator for node prediction with homogeneous GraphSAGE models\n on directed graphs.\n\n At minimum, supply the StellarDiGraph, the batch size, and the number of\n node samples (separately for in-nodes and out-nodes)\n for each layer of the GraphSAGE model.\n\n The supplied graph should be a StellarDiGraph object that is ready for\n machine learning. Currently the model requires node features for all\n nodes in the graph.\n\n Use the :meth:`flow` method supplying the nodes and (optionally) targets\n to get an object that can be used as a Keras data generator.\n\n Example::\n\n G_generator = DirectedGraphSAGENodeGenerator(G, 50, [10,5], [5,1])\n train_data_gen = G_generator.flow(train_node_ids, train_node_labels)\n test_data_gen = G_generator.flow(test_node_ids)\n\n Args:\n G (StellarDiGraph): The machine-learning ready graph.\n batch_size (int): Size of batch to return.\n in_samples (list): The number of in-node samples per layer (hop) to take.\n out_samples (list): The number of out-node samples per layer (hop) to take.\n seed (int): [Optional] Random seed for the node sampler.\n \"\"\"\n\n def __init__(self, G, batch_size, in_samples, out_samples, seed=None, name=None):\n super().__init__(G, batch_size)\n\n # TODO Add checks for in- and out-nodes sizes\n self.in_samples = in_samples\n self.out_samples = out_samples\n self.head_node_types = self.schema.node_types\n self.name = name\n\n # Check that there is only a single node type for GraphSAGE\n if len(self.head_node_types) > 1:\n warnings.warn(\n \"running homogeneous GraphSAGE on a graph with multiple node types\",\n RuntimeWarning,\n )\n\n # Create sampler for GraphSAGE\n self.sampler = DirectedBreadthFirstNeighbours(\n G, graph_schema=self.schema, seed=seed\n )\n\n def sample_features(self, head_nodes, batch_num):\n \"\"\"\n Sample neighbours recursively from the head nodes, collect the features of the\n sampled nodes, and return these as a list of feature arrays for the GraphSAGE\n algorithm.\n\n Args:\n head_nodes: An iterable of head nodes to perform sampling on.\n batch_num (int): Batch number\n\n Returns:\n A list of feature tensors from the sampled nodes at each layer, each of shape:\n ``(len(head_nodes), num_sampled_at_layer, feature_size)``\n where num_sampled_at_layer is the total number (cumulative product)\n of nodes sampled at the given number of hops from each head node,\n given the sequence of in/out directions.\n \"\"\"\n node_samples = self.sampler.run(\n nodes=head_nodes, n=1, in_size=self.in_samples, out_size=self.out_samples\n )\n\n # Reshape node samples to sensible format\n # Each 'slot' represents the list of nodes sampled from some neighbourhood, and will have a corresponding\n # NN input layer. Every hop potentially generates both in-nodes and out-nodes, held separately,\n # and thus the slot (or directed hop sequence) structure forms a binary tree.\n\n node_type = self.head_node_types[0]\n\n max_hops = len(self.in_samples)\n max_slots = 2 ** (max_hops + 1) - 1\n features = [None] * max_slots # flattened binary tree\n\n for slot in range(max_slots):\n nodes_in_slot = list(it.chain(*[sample[slot] for sample in node_samples]))\n features_for_slot = self.graph.node_features(nodes_in_slot, node_type)\n resize = -1 if np.size(features_for_slot) > 0 else 0\n features[slot] = np.reshape(\n features_for_slot, (len(head_nodes), resize, features_for_slot.shape[1])\n )\n\n return features\n\n\nclass HinSAGENodeGenerator(BatchedNodeGenerator):\n \"\"\"Keras-compatible data mapper for Heterogeneous GraphSAGE (HinSAGE)\n\n At minimum, supply the StellarGraph, the batch size, and the number of\n node samples for each layer of the HinSAGE model.\n\n The supplied graph should be a StellarGraph object that is ready for\n machine learning. Currently the model requires node features for all\n nodes in the graph.\n\n Use the :meth:`flow` method supplying the nodes and (optionally) targets\n to get an object that can be used as a Keras data generator.\n\n Note that the shuffle argument should be True for training and\n False for prediction.\n\n Args:\n G (StellarGraph): The machine-learning ready graph\n batch_size (int): Size of batch to return\n num_samples (list): The number of samples per layer (hop) to take\n head_node_type (str): The node type that will be given to the generator\n using the `flow` method, the model will expect this node type.\n schema (GraphSchema, optional): Graph schema for G.\n seed (int, optional): Random seed for the node sampler\n\n Example::\n\n G_generator = HinSAGENodeGenerator(G, 50, [10,10])\n train_data_gen = G_generator.flow(train_node_ids, train_node_labels)\n test_data_gen = G_generator.flow(test_node_ids)\n\n \"\"\"\n\n def __init__(\n self,\n G,\n batch_size,\n num_samples,\n head_node_type,\n schema=None,\n seed=None,\n name=None,\n ):\n super().__init__(G, batch_size, schema=schema)\n\n self.num_samples = num_samples\n self.name = name\n\n # The head node type\n if head_node_type not in self.schema.node_types:\n raise KeyError(\"Supplied head node type must exist in the graph\")\n self.head_node_types = [head_node_type]\n\n # Create sampling schema\n self._sampling_schema = self.schema.sampling_layout(\n self.head_node_types, self.num_samples\n )\n self._type_adjacency_list = self.schema.type_adjacency_list(\n self.head_node_types, len(self.num_samples)\n )\n\n # Create sampler for HinSAGE\n self.sampler = SampledHeterogeneousBreadthFirstWalk(\n G, graph_schema=self.schema, seed=seed\n )\n\n def sample_features(self, head_nodes, batch_num):\n \"\"\"\n Sample neighbours recursively from the head nodes, collect the features of the\n sampled nodes, and return these as a list of feature arrays for the GraphSAGE\n algorithm.\n\n Args:\n head_nodes: An iterable of head nodes to perform sampling on.\n batch_num (int): Batch number\n\n Returns:\n A list of the same length as ``num_samples`` of collected features from\n the sampled nodes of shape:\n ``(len(head_nodes), num_sampled_at_layer, feature_size)``\n where num_sampled_at_layer is the cumulative product of `num_samples`\n for that layer.\n \"\"\"\n # Get sampled nodes\n node_samples = self.sampler.run(nodes=head_nodes, n=1, n_size=self.num_samples)\n\n # Reshape node samples to the required format for the HinSAGE model\n # This requires grouping the sampled nodes by edge type and in order\n nodes_by_type = [\n (\n nt,\n reduce(\n operator.concat,\n (samples[ks] for samples in node_samples for ks in indices),\n [],\n ),\n )\n for nt, indices in self._sampling_schema[0]\n ]\n\n # Get features\n batch_feats = [\n self.graph.node_features(layer_nodes, nt)\n for nt, layer_nodes in nodes_by_type\n ]\n\n # Resize features to (batch_size, n_neighbours, feature_size)\n batch_feats = [\n np.reshape(a, (len(head_nodes), -1 if np.size(a) > 0 else 0, a.shape[1]))\n for a in batch_feats\n ]\n\n return batch_feats\n\n\nclass Attri2VecNodeGenerator(BatchedNodeGenerator):\n \"\"\"\n A node feature generator for node representation prediction with the\n attri2vec model.\n\n At minimum, supply the StellarGraph and the batch size.\n\n The supplied graph should be a StellarGraph object that is ready for\n machine learning. Currently the model requires node features for all\n nodes in the graph.\n\n Use the :meth:`flow` method supplying the nodes to get an object\n that can be used as a Keras data generator.\n\n Example::\n\n G_generator = Attri2VecNodeGenerator(G, 50)\n data_gen = G_generator.flow(node_ids)\n\n Args:\n G (StellarGraph): The machine-learning ready graph.\n batch_size (int): Size of batch to return.\n name (str or None): Name of the generator (optional).\n \"\"\"\n\n def __init__(self, G, batch_size, name=None):\n super().__init__(G, batch_size)\n self.name = name\n\n def sample_features(self, head_nodes, batch_num):\n \"\"\"\n Sample content features of the head nodes, and return these as a list of feature\n arrays for the attri2vec algorithm.\n\n Args:\n head_nodes: An iterable of head nodes to perform sampling on.\n batch_num (int): Batch number\n\n Returns:\n A list of feature arrays, with each element being the feature of a\n head node.\n \"\"\"\n\n batch_feats = self.graph.node_features(head_nodes)\n return batch_feats\n\n def flow(self, node_ids):\n \"\"\"\n Creates a generator/sequence object for node representation prediction\n with the supplied node ids.\n\n The node IDs are the nodes to inference on: the embeddings\n calculated for these nodes are passed to the downstream task. These\n are a subset/all of the nodes in the graph.\n\n Args:\n node_ids: an iterable of node IDs.\n\n Returns:\n A NodeSequence object to use with the Attri2Vec model\n in the Keras method ``predict``.\n\n \"\"\"\n return NodeSequence(\n self.sample_features, self.batch_size, node_ids, shuffle=False\n )\n\n def flow_from_dataframe(self, node_ids):\n \"\"\"\n Creates a generator/sequence object for node representation prediction\n with the supplied node ids.\n\n Args:\n node_ids: a Pandas DataFrame of node_ids.\n\n Returns:\n A NodeSequence object to use with the Attri2Vec model\n in the Keras method ``predict``.\n\n \"\"\"\n return NodeSequence(self.sample_features, self.batch_size, node_ids.index)\n"
] |
[
[
"numpy.size",
"numpy.cumprod"
]
] |
ina-foss/inaFaceGender
|
[
"4c2e2588684d5813732648201f70b61fa5b85142"
] |
[
"inaFaceAnalyzer/face_classifier.py"
] |
[
"#!/usr/bin/env python\n# encoding: utf-8\n\n# The MIT License\n\n# Copyright (c) 2021 Ina (David Doukhan & Zohra Rezgui- http://www.ina.fr/)\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport numpy as np\nimport pandas as pd\nimport numbers\nfrom abc import ABC, abstractmethod\nfrom keras_vggface.vggface import VGGFace\nfrom keras_vggface import utils\nimport tensorflow\nfrom tensorflow import keras\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom .svm_utils import svm_load\nfrom .opencv_utils import imread_rgb\nfrom .remote_utils import get_remote\n\n\nclass FaceClassifier(ABC):\n \"\"\"\n Abstract class to be implemented by face classifiers\n \"\"\"\n\n # The 3 properties bellow (input_shape, bbox_scale, bbox2square) are\n # currently common to all implemented face classifiers\n # they provide information on the face preprocessing steps used for\n # training the classification models\n # in future, they may be defined separately for each classifier using\n # abstract properties\n\n # input image dimensions required by the classifier (width, height, depth)\n input_shape = (224, 224, 3)\n\n # implemented classifiers are optimized for a given scale factor to be\n # applied on face bounding boxes to be defined here\n bbox_scale = 1.1\n\n # implemented face classifiers may require a preprocessing step consisting\n # to extend the face bounding box such as the resulting box is the smallest\n # square containing the detected face\n bbox2square = True\n\n\n @abstractmethod\n def list2batch(self, limg): pass\n\n @abstractmethod\n def inference(self, bfeats): pass\n\n @abstractmethod\n def decisionfunction2labels(self, df): pass\n\n @property\n def output_cols(self):\n if not hasattr(self, '_output_cols'):\n fake_input = [np.zeros(self.input_shape)]\n self._output_cols = list(self(fake_input, False).columns)\n return self._output_cols\n\n def average_results(self, df):\n if len(df) == 0:\n for c in self.output_cols:\n df[c] = []\n\n cols = [e for e in df.columns if e.endswith('_decfunc')]\n gbm = df.groupby('face_id')[cols].mean()\n gbm = self.decisionfunction2labels(gbm)\n\n return df.join(gbm, on='face_id', rsuffix='_avg')\n\n # Keras trick for async READ ?\n # bench execution time : time spent in read/exce . CPU vs GPU\n def imgpaths_batch(self, lfiles, return_features, batch_len=32):\n \"\"\"\n images are assumed to be faces already detected, scaled, aligned, croped\n \"\"\"\n assert len(lfiles) > 0\n\n if return_features:\n raise NotImplementedError()\n\n lbatchret = []\n\n for i in range(0, len(lfiles), batch_len):\n xbatch = [imread_rgb(e) for e in lfiles[i:(i+batch_len)]]\n\n lbatchret.append(self(xbatch, False)) # to change when return features will be managed\n\n return pd.concat(lbatchret).reset_index(drop=True)\n\n def __call__(self, limg, return_features):\n \"\"\"\n Classify a list of images\n images are supposed to be preprocessed faces: aligned, cropped\n Parameters\n ----------\n limg : list of images, a single image can also be used\n\n Returns\n -------\n feats :\n face features used as input to the final classifier\n label : str\n f for female, m for male\n decision_value : float\n decision function value (negative for female, positive for male)\n \"\"\"\n\n if isinstance(limg, list):\n islist = True\n else:\n islist = False\n limg = [limg]\n\n assert np.all([e.shape == self.input_shape for e in limg])\n batch_ret_feats, batch_ret_preds = self.inference(self.list2batch(limg))\n batch_ret_preds = self.decisionfunction2labels(batch_ret_preds)\n\n if islist:\n if return_features:\n return batch_ret_feats, batch_ret_preds\n return batch_ret_preds\n\n ret = next(batch_ret_preds.itertuples(index=False, name='FaceClassifierResult'))\n if return_features:\n return batch_ret_feats[0, :], ret\n return ret\n\nclass Resnet50FairFace(FaceClassifier):\n\n def __init__(self):\n m = keras.models.load_model(get_remote('keras_resnet50_fairface.h5'), compile=False)\n self.model = tensorflow.keras.Model(inputs=m.inputs, outputs=m.outputs + [m.layers[-3].output])\n\n def list2batch(self, limg):\n x = np.concatenate([np.expand_dims(img_to_array(e), axis=0) for e in limg])\n return tensorflow.keras.applications.resnet50.preprocess_input(x)\n\n def inference(self, x):\n decisions, feats = self.model.predict(x)\n df = pd.DataFrame(decisions.ravel(), columns=['sex_decfunc'])\n return feats, df\n\n def decisionfunction2labels(self, df):\n df['sex_label'] = df.sex_decfunc.map(lambda x: 'm' if x > 0 else 'f' )\n return df\n\n\ndef _fairface_agedec2age(age_dec):\n ages = np.array([(0,2), (3,9), (10,19), (20,29), (30,39), (40,49), (50,59), (60,69), (70, 79), (80,99)], dtype=np.float32)\n ages_mean = (np.sum(ages, axis=1) + 1) / 2.\n ages_range = ages[:, 1] - ages[:, 0] +1\n\n if isinstance(age_dec, numbers.Number):\n age_dec = np.array([age_dec])\n\n age_dec = np.array(age_dec)\n age_dec[age_dec <= -.5] = -.5 + 10**-8\n age_dec[age_dec >= 9.5] = 9.5 - 10**-8\n idec = np.round(age_dec).astype(np.int32)\n\n age_label = ages_mean[idec] + (age_dec - idec) * ages_range[idec]\n return age_label\n\n\n\n\nclass Resnet50FairFaceGRA(Resnet50FairFace):\n def __init__(self):\n m = keras.models.load_model(get_remote('keras_resnet50_fairface_GRA.h5'), compile=False)\n self.model = tensorflow.keras.Model(inputs=m.inputs, outputs=m.outputs + [m.layers[-5].output])\n\n def inference(self, x):\n gender, _, age, feats = self.model.predict(x)\n df = pd.DataFrame(zip(gender.ravel(), age.ravel()), columns=['sex_decfunc', 'age_decfunc'])\n return feats, df\n\n def decisionfunction2labels(self, df):\n df = super().decisionfunction2labels(df)\n df['age_label'] = _fairface_agedec2age(df.age_decfunc)\n return df\n\nclass OxfordVggFace(FaceClassifier):\n \n def __init__(self, hdf5_svm=None):\n # Face feature extractor from aligned and detected faces\n self.vgg_feature_extractor = VGGFace(include_top = False, input_shape = self.input_shape, pooling ='avg')\n # SVM trained on VGG neural features\n if hdf5_svm is not None:\n self.gender_svm = svm_load(hdf5_svm)\n\n def decisionfunction2labels(self, df):\n df['sex_label'] = [self.gender_svm.classes_[1 if x > 0 else 0] for x in df.sex_decfunc]\n return df\n\n def list2batch(self, limg):\n \"\"\"\n returns VGG16 Features\n limg is a list of preprocessed images supposed to be aligned and cropped and resized to 224*224\n \"\"\"\n limg = [np.expand_dims(img_to_array(e[:, :, ::-1]), axis=0) for e in limg]\n x = utils.preprocess_input(np.concatenate(limg), version=1)\n return self.vgg_feature_extractor(x)\n\n def inference(self, x):\n return np.array(x), pd.DataFrame(self.gender_svm.decision_function(x), columns=['sex_decfunc'])\n\nclass Vggface_LSVM_YTF(OxfordVggFace):\n def __init__(self):\n OxfordVggFace.__init__(self, get_remote('svm_ytf_zrezgui.hdf5'))\n\n\nclass Vggface_LSVM_FairFace(OxfordVggFace):\n def __init__(self):\n OxfordVggFace.__init__(self, get_remote('svm_vgg16_fairface.hdf5'))\n"
] |
[
[
"pandas.concat",
"tensorflow.keras.preprocessing.image.img_to_array",
"tensorflow.keras.applications.resnet50.preprocess_input",
"tensorflow.keras.Model",
"numpy.all",
"numpy.round",
"numpy.concatenate",
"numpy.array",
"numpy.zeros",
"numpy.sum"
]
] |
FatimaAfilala/ExcelProject
|
[
"43602ad569c0ed0649de3777900f444c8a3a6f7c"
] |
[
"cara/tests/test_monte_carlo_full_models.py"
] |
[
"import numpy as np\nimport numpy.testing as npt\nimport pytest\n\nimport cara.monte_carlo as mc\nfrom cara import models,data\nfrom cara.monte_carlo.data import activity_distributions, virus_distributions\n\n# TODO: seed better the random number generators\nnp.random.seed(2000)\nSAMPLE_SIZE = 50000\nTOLERANCE = 0.05\n\n# references values for infection_probability and expected new cases\n# in the following tests, were obtained from the feature/mc branch\n\[email protected]\ndef shared_office_mc():\n \"\"\"\n Corresponds to the 1st line of Table 5 in CERN-OPEN-2021-04, but\n speaking 30% of the time (instead of 1/3)\n \"\"\"\n concentration_mc = mc.ConcentrationModel(\n room=models.Room(volume=50, humidity=0.3),\n ventilation=models.MultipleVentilation(\n (\n models.SlidingWindow(\n active=models.PeriodicInterval(period=120, duration=10),\n inside_temp=models.PiecewiseConstant((0., 24.), (293,)),\n outside_temp=models.PiecewiseConstant((0., 24.), (283,)),\n window_height=1.6, opening_length=0.6,\n ),\n models.AirChange(\n active=models.SpecificInterval(((0., 24.), )),\n air_exch=0.25,\n ),\n ),\n ),\n infected=mc.InfectedPopulation(\n number=1,\n virus=virus_distributions['SARS_CoV_2_B117'],\n presence=mc.SpecificInterval(((0., 2.), (2.1, 4.), (5., 7.), (7.1, 9.))),\n mask=models.Mask(η_inhale=0.3),\n activity=activity_distributions['Seated'],\n expiration=models.MultipleExpiration(\n expirations=(models.Expiration.types['Talking'],\n models.Expiration.types['Breathing']),\n weights=(0.3, 0.7)),\n ),\n )\n return mc.ExposureModel(\n concentration_model=concentration_mc,\n exposed=mc.Population(\n number=3,\n presence=concentration_mc.infected.presence,\n activity=models.Activity.types['Seated'],\n mask=concentration_mc.infected.mask,\n ),\n )\n\n\[email protected]\ndef classroom_mc():\n \"\"\"\n Corresponds to the 2nd line of Table 5 in CERN-OPEN-2021-04\n \"\"\"\n concentration_mc = mc.ConcentrationModel(\n room=models.Room(volume=160, humidity=0.3),\n ventilation=models.MultipleVentilation(\n (\n models.SlidingWindow(\n active=models.PeriodicInterval(period=120, duration=10),\n inside_temp=models.PiecewiseConstant((0., 24.), (293,)),\n outside_temp=models.PiecewiseConstant((0., 24.), (283,)),\n window_height=1.6, opening_length=0.6,\n ),\n models.AirChange(\n active=models.SpecificInterval(((0., 24.),)),\n air_exch=0.25,\n ),\n ),\n ),\n infected=mc.InfectedPopulation(\n number=1,\n virus=virus_distributions['SARS_CoV_2_B117'],\n presence=mc.SpecificInterval(((0., 2.), (2.5, 4.), (5., 7.), (7.5, 9.))),\n mask=models.Mask.types['No mask'],\n activity=activity_distributions['Light activity'],\n expiration=models.Expiration.types['Talking'],\n ),\n )\n return mc.ExposureModel(\n concentration_model=concentration_mc,\n exposed=mc.Population(\n number=19,\n presence=concentration_mc.infected.presence,\n activity=models.Activity.types['Seated'],\n mask=concentration_mc.infected.mask,\n ),\n )\n\n\[email protected]\ndef ski_cabin_mc():\n \"\"\"\n Corresponds to the 3rd line of Table 5 in CERN-OPEN-2021-04\n \"\"\"\n concentration_mc = mc.ConcentrationModel(\n room=models.Room(volume=10, humidity=0.5),\n ventilation=models.AirChange(\n active=models.SpecificInterval(((0., 24.),)),\n air_exch=0,\n ),\n infected=mc.InfectedPopulation(\n number=1,\n virus=virus_distributions['SARS_CoV_2_B117'],\n presence=mc.SpecificInterval(((0., 1/3),)),\n mask=models.Mask(η_inhale=0.3),\n activity=activity_distributions['Moderate activity'],\n expiration=models.Expiration.types['Talking'],\n ),\n )\n return mc.ExposureModel(\n concentration_model=concentration_mc,\n exposed=mc.Population(\n number=3,\n presence=concentration_mc.infected.presence,\n activity=models.Activity.types['Moderate activity'],\n mask=concentration_mc.infected.mask,\n ),\n )\n\n\[email protected]\ndef gym_mc():\n \"\"\"\n Corresponds to the 4th line of Table 5 in CERN-OPEN-2021-04,\n but there the expected number of cases is wrongly reported as 0.56\n while it should be 0.63.\n \"\"\"\n concentration_mc = mc.ConcentrationModel(\n room=models.Room(volume=300, humidity=0.5),\n ventilation=models.AirChange(\n active=models.SpecificInterval(((0., 24.),)),\n air_exch=6,\n ),\n infected=mc.InfectedPopulation(\n number=2,\n virus=virus_distributions['SARS_CoV_2_B117'],\n presence=mc.SpecificInterval(((0., 1.),)),\n mask=models.Mask.types[\"No mask\"],\n activity=activity_distributions['Heavy exercise'],\n expiration=models.Expiration.types['Breathing'],\n ),\n )\n return mc.ExposureModel(\n concentration_model=concentration_mc,\n exposed=mc.Population(\n number=28,\n presence=concentration_mc.infected.presence,\n activity=models.Activity.types['Heavy exercise'],\n mask=concentration_mc.infected.mask,\n ),\n )\n\n\[email protected]\ndef waiting_room_mc():\n \"\"\"\n Corresponds to the 5th line of Table 5 in CERN-OPEN-2021-04, but\n speaking 30% of the time (instead of 20%)\n \"\"\"\n concentration_mc = mc.ConcentrationModel(\n room=models.Room(volume=100, humidity=0.5),\n ventilation=models.AirChange(\n active=models.SpecificInterval(((0., 24.),)),\n air_exch=0.25,\n ),\n infected=mc.InfectedPopulation(\n number=1,\n virus=virus_distributions['SARS_CoV_2_B117'],\n presence=mc.SpecificInterval(((0., 2.),)),\n mask=models.Mask.types[\"No mask\"],\n activity=activity_distributions['Seated'],\n expiration=models.MultipleExpiration(\n expirations=(models.Expiration.types['Talking'],\n models.Expiration.types['Breathing']),\n weights=(0.3, 0.7)),\n ),\n )\n return mc.ExposureModel(\n concentration_model=concentration_mc,\n exposed=mc.Population(\n number=14,\n presence=concentration_mc.infected.presence,\n activity=models.Activity.types['Seated'],\n mask=concentration_mc.infected.mask,\n ),\n )\n\n\[email protected]\ndef skagit_chorale_mc():\n \"\"\"\n Corresponds to the 6th line of Table 5 in CERN-OPEN-2021-04, but\n infection probability should be 29.8% instead of 32%, and number of\n new cases 17.9 instead of 21.\n \"\"\"\n concentration_mc = mc.ConcentrationModel(\n room=models.Room(volume=810, humidity=0.5),\n ventilation=models.AirChange(\n active=models.SpecificInterval(((0,24),)),\n air_exch=0.7,\n ),\n infected=mc.InfectedPopulation(\n number=1,\n virus=virus_distributions['SARS_CoV_2'],\n presence=mc.SpecificInterval(((0., 2.5),)),\n mask=models.Mask.types[\"No mask\"],\n activity=activity_distributions['Light activity'],\n expiration=models.Expiration((5., 5., 5.)),\n ),\n )\n return mc.ExposureModel(\n concentration_model=concentration_mc,\n exposed=mc.Population(\n number=60,\n presence=concentration_mc.infected.presence,\n activity=models.Activity.types['Moderate activity'],\n mask=concentration_mc.infected.mask,\n ),\n )\n\n\[email protected](\n \"mc_model, expected_pi, expected_new_cases, expected_dose, expected_ER\",\n [\n [\"shared_office_mc\", 10.7, 0.32, 57.24, 654],\n [\"classroom_mc\", 36.1, 6.85, 780.0, 28464],\n [\"ski_cabin_mc\", 16.3, 0.49, 35.94, 7404],\n [\"gym_mc\", 2.25, 0.63, 0.7842, 1968],\n [\"waiting_room_mc\", 9.72, 1.36, 34.26, 3534],\n [\"skagit_chorale_mc\",29.9, 17.9, 190.0, 141400],\n ]\n)\ndef test_report_models(mc_model, expected_pi, expected_new_cases,\n expected_dose, expected_ER, request):\n mc_model = request.getfixturevalue(mc_model)\n exposure_model = mc_model.build_model(size=SAMPLE_SIZE)\n npt.assert_allclose(exposure_model.infection_probability().mean(),\n expected_pi, rtol=TOLERANCE)\n npt.assert_allclose(exposure_model.expected_new_cases().mean(),\n expected_new_cases, rtol=TOLERANCE)\n npt.assert_allclose(exposure_model.exposure().mean(),\n expected_dose, rtol=TOLERANCE)\n npt.assert_allclose(\n exposure_model.concentration_model.infected.emission_rate_when_present().mean(),\n expected_ER, rtol=TOLERANCE)\n\n\[email protected](\n \"mask_type, month, expected_pi, expected_dose, expected_ER\",\n [\n [\"No mask\", \"Jul\", 30.0, 405.84, 3894],\n [\"Type I\", \"Jul\", 10.2, 73.38, 702],\n [\"FFP2\", \"Jul\", 4.0, 73.38, 702],\n [\"Type I\", \"Feb\", 4.25, 21.42, 702],\n ],\n)\ndef test_small_shared_office_Geneva(mask_type, month, expected_pi,\n expected_dose, expected_ER):\n concentration_mc = mc.ConcentrationModel(\n room=models.Room(volume=33, humidity=0.5),\n ventilation=models.MultipleVentilation(\n (\n models.SlidingWindow(\n active=models.SpecificInterval(((0., 24.),)),\n inside_temp=models.PiecewiseConstant((0., 24.), (293,)),\n outside_temp=data.GenevaTemperatures[month],\n window_height=1.5, opening_length=0.2,\n ),\n models.AirChange(\n active=models.SpecificInterval(((0., 24.),)),\n air_exch=0.25,\n ),\n ),\n ),\n infected=mc.InfectedPopulation(\n number=1,\n virus=virus_distributions['SARS_CoV_2_B117'],\n presence=mc.SpecificInterval(((9., 10+2/3), (10+5/6, 12.5), (13.5, 15+2/3), (15+5/6, 18.))),\n mask=models.Mask.types[mask_type],\n activity=activity_distributions['Seated'],\n expiration=models.MultipleExpiration(\n expirations=(models.Expiration.types['Talking'],\n models.Expiration.types['Breathing']),\n weights=(0.33, 0.67)),\n ),\n )\n exposure_mc = mc.ExposureModel(\n concentration_model=concentration_mc,\n exposed=mc.Population(\n number=1,\n presence=concentration_mc.infected.presence,\n activity=activity_distributions['Seated'],\n mask=concentration_mc.infected.mask,\n ),\n )\n exposure_model = exposure_mc.build_model(size=SAMPLE_SIZE)\n npt.assert_allclose(exposure_model.infection_probability().mean(),\n expected_pi, rtol=TOLERANCE)\n npt.assert_allclose(exposure_model.exposure().mean(),\n expected_dose, rtol=TOLERANCE)\n npt.assert_allclose(\n exposure_model.concentration_model.infected.emission_rate_when_present().mean(),\n expected_ER, rtol=TOLERANCE)\n"
] |
[
[
"numpy.random.seed"
]
] |
IJSComplexMatter/dtmm
|
[
"08c66ddf55f9276bc713e921eaadbadbb4a28fe2",
"08c66ddf55f9276bc713e921eaadbadbb4a28fe2"
] |
[
"dtmm/jones.py",
"dtmm/denoise.py"
] |
[
"\"\"\"\nJones calculus functions. You can use this module for simple normal incidence\njones calculus.\n\n2x2 matrices\n------------\n\n* :func:`.jonesvec` : jones vector\n* :func:`.mirror` : mirror matrix\n* :func:`.polarizer` : polarizer matrix\n* :func:`.retarder` : retarder matrix\n* :func:`.quarter_waveplate` : quarter-wave plate matrix\n* :func:`.half_waveplate` : half-wave plate matrix\n* :func:`.circular_polarizer` : circular polarizer matrix\n* :func:`.linear_polarizer` : linear polarizer matrix\n\nConversion functions\n--------------------\n\n* :func:`.as4x4` : convert to 4x4 matrix for (...,4) field vector.\n* :func:`.rotated_matrix` : to view the matrix in rotated frame.\n\nExamples\n--------\n\n>>> j_in = jonesvec((1,1)) #input light polarized at 45\n>>> r = retarder(0.2,0.4)\n>>> p = linear_polarizer((1,0)) # x polarization\n>>> c = circular_polarizer(+1) # left handed\n>>> m = multi_dot([r,p,c])\n>>> j_out = dotmv(m,j_in) #output light E field\n>>> i = jones_intensity(j_out) #intensity\n\"\"\"\n\nfrom dtmm.conf import CDTYPE,FDTYPE\nimport numpy as np\nfrom dtmm.rotation import rotation_matrix2\nfrom dtmm.linalg import dotmv, dotmm, multi_dot\n\ndef jones_intensity(jones):\n \"\"\"Computes intensity of the jones vector\n \n Parameters\n ----------\n jones : (...,2) array\n Jones vector.\n \n Returns\n -------\n intensity : (...) float array\n Computed intensity.\n \"\"\"\n return ((jones * np.conj(jones)).sum(-1)).real\n\ndef jonesvec(pol, phi = 0., out = None):\n \"\"\"Returns a normalized jones vector from an input length 2 vector., Additionaly,\n you can use this function to view the jones vector in rotated coordinate frame, \n defined with a rotation angle phi. \n \n Numpy broadcasting rules apply.\n \n Parameters\n ----------\n pol : (...,2) array\n Input jones vector. Does not need to be normalized. \n phi : float or (...,1) array\n If jones vector must be view in the rotated frame, this parameter\n defines the rotation angle.\n out : ndarray\n Output array in which to put the result; if provided, it\n must have a shape that the inputs broadcast to.\n \n Returns\n -------\n vec : ndarray\n Normalized jones vector\n \n Example\n -------\n \n >>> jonesvec((1,1j)) #left-handed circuar polarization\n array([0.70710678+0.j , 0. +0.70710678j])\n \n In rotated frame\n \n >>> j1,j2 = jonesvec((1,1j), (np.pi/2,np.pi/4)) \n >>> np.allclose(j1, (0.70710678j,-0.70710678))\n True\n >>> np.allclose(j2, (0.5+0.5j,-0.5+0.5j))\n True\n \n \"\"\"\n pol = np.asarray(pol, CDTYPE)\n phi = np.asarray(phi)\n if pol.shape[-1] != 2:\n raise ValueError(\"Invalid input shape\")\n norm = (pol[...,0] * pol[...,0].conj() + pol[...,1] * pol[...,1].conj())**0.5\n pol = pol/norm[...,np.newaxis]\n pol = np.asarray(pol, CDTYPE)\n r = rotation_matrix2(-phi)\n return dotmv(r, pol, out)\n\ndef mirror(out = None):\n \"\"\"Returns jones mirror matrix.\n \n Parameters\n ----------\n out : ndarray, optional\n Output array in which to put the result; if provided, it\n must have a shape that the inputs broadcast to.\n \n Returns\n -------\n mat : ndarray\n Output jones matrix. \n \"\"\"\n m = np.array(((1,0),(0,-1)), dtype = CDTYPE)\n if out is not None:\n out[...,:,:] = m\n m = out\n return m\n\ndef retarder(phase, phi = 0., out = None):\n \"\"\"Returns jones matrix of general phase retarder\n \n Numpy broadcasting rules apply.\n \n Parameters\n ----------\n phase : float or array\n Phase difference between the slow and fast axis of the retarder.\n phi : float or array \n Slow axis orientation\n out : ndarray, optional\n Output array in which to put the result; if provided, it\n must have a shape that the inputs broadcast to.\n \n Returns\n -------\n mat : ndarray\n Output jones matrix.\n \"\"\"\n phi = np.asarray(phi)\n phase = np.asarray(phase)\n \n c = np.cos(phi*2)\n s = np.sin(phi*2)\n \n cp = np.cos(phase/2.)\n sp = np.sin(phase/2.)\n \n m00 = (cp + 1j*sp*c) \n m11 = (cp - 1j*sp*c) \n \n m01 = 1j*sp * s \n \n shape = m00.shape + (2,2)\n if out is None:\n out = np.empty(shape = shape, dtype = CDTYPE)\n else:\n assert out.shape == shape \n \n out[...,0,0] = m00\n out[...,0,1] = m01\n out[...,1,0] = m01\n out[...,1,1] = m11\n return out \n\ndef quarter_waveplate(phi = 0., out = None):\n \"\"\"Returns jones quarter-wave plate matrix.\n \n Numpy broadcasting rules apply.\n \n Parameters\n ----------\n phi : float or array \n Slow axis orientation\n out : ndarray, optional\n Output array in which to put the result; if provided, it\n must have a shape that the inputs broadcast to.\n \n Returns\n -------\n mat : ndarray\n Output jones matrix. \n \"\"\"\n return retarder(np.pi/2, phi, out) \n\ndef half_waveplate(phi = 0., out = None):\n \"\"\"Returns jones half-wave plate matrix.\n \n Numpy broadcasting rules apply.\n \n Parameters\n ----------\n phi : float or array \n Slow axis orientation\n out : ndarray, optional\n Output array in which to put the result; if provided, it\n must have a shape that the inputs broadcast to.\n \n Returns\n -------\n mat : ndarray\n Output jones matrix. \n \"\"\"\n return retarder(np.pi, phi, out) \n\ndef full_waveplate(phi = 0., central = 530., wavelengths = None, out = None):\n \"\"\"Returns jones full-wave plate matrix.\n \n Numpy broadcasting rules apply.\n \n Parameters\n ----------\n phi : float or array \n Slow axis orientation\n central : float \n Central wavelength for which to define the lambda plate. Used only if\n wavelengths are set.\n wavelengths : array, optional\n An array of wavelength around the central wavelength for which we\n compute the retarder jones matrix.\n out : ndarray, optional\n Output array in which to put the result; if provided, it\n must have a shape that the inputs broadcast to.\n \n Returns\n -------\n mat : ndarray\n Output jones matrix. \n \"\"\"\n phase = 2*np.pi*central/np.asarray(wavelengths) if wavelengths is not None else 2*np.pi\n return retarder(phase, phi, out) \n\ndef polarizer(jones, out = None):\n \"\"\"Returns jones polarizer matrix.\n \n Numpy broadcasting rules apply.\n \n Parameters\n ----------\n jones : (...,2) array\n Input normalized jones vector. Use :func:`.jonesvec` to generate jones vector\n out : ndarray, optional\n Output array in which to put the result; if provided, it\n must have a shape that the inputs broadcast to.\n \n Returns\n -------\n mat : ndarray\n Output jones matrix.\n \n Examples\n --------\n >>> pmat = polarizer(jonesvec((1,1))) #45 degree linear polarizer\n >>> np.allclose(pmat, linear_polarizer(np.pi/4)+0j )\n True\n >>> pmat = polarizer(jonesvec((1,-1))) #-45 degree linear polarizer\n >>> np.allclose(pmat, linear_polarizer(-np.pi/4)+0j )\n True\n >>> pmat = polarizer(jonesvec((1,1j))) #left handed circular polarizer\n >>> np.allclose(pmat, circular_polarizer(1) )\n True\n \"\"\"\n jones = np.asarray(jones)\n assert jones.shape[-1] == 2\n shape = jones.shape + (2,)\n if out is None:\n out = np.empty(shape = shape, dtype = CDTYPE)\n else:\n assert out.shape == shape \n c,s = jones[...,0], jones[...,1]\n \n out[...,0,0] = c*c.conj()\n out[...,0,1] = c*s.conj()\n out[...,1,0] = s*c.conj()\n out[...,1,1] = s*s.conj()\n return out \n \ndef linear_polarizer(angle, out = None):\n \"\"\"Return jones matrix for a polarizer.\n \n Numpy broadcasting rules apply.\n \n Parameters\n ----------\n angle : float or array\n Orientation of the polarizer.\n out : ndarray, optional\n Output array in which to put the result; if provided, it\n must have a shape that the inputs broadcast to.\n \n Returns\n -------\n mat : ndarray\n Output jones matrix.\n \"\"\"\n angle = np.asarray(angle)\n shape = angle.shape + (2,2)\n if out is None:\n out = np.empty(shape = shape, dtype = FDTYPE)\n else:\n assert out.shape == shape \n c = np.cos(angle)\n s = np.sin(angle)\n cs = c*s\n out[...,0,0] = c*c\n out[...,1,0] = cs\n out[...,0,1] = cs\n out[...,1,1] = s*s\n return out\n\npolarizer_matrix = linear_polarizer\n\ndef circular_polarizer(hand, out = None):\n \"\"\"Returns circular polarizer matrix.\n \n Numpy broadcasting rules apply.\n \n Parameters\n ----------\n hand : int or (...,1) array\n Handedness +1 (left-hand) or -1 (right-hand).\n out : ndarray, optional\n Output array in which to put the result; if provided, it\n must have a shape that the inputs broadcast to.\n \n Returns\n -------\n mat : ndarray\n Output jones matrix.\n \"\"\"\n hand = np.asarray(hand)*0.5\n shape = hand.shape + (2,2)\n if out is None:\n out = np.empty(shape = shape, dtype = CDTYPE)\n else:\n assert out.shape == shape \n out[...,0,0] = 0.5\n out[...,0,1] = -1j*hand\n out[...,1,0] = 1j*hand\n out[...,1,1] = 0.5 \n return out\n\ndef rotated_matrix(jmat, phi):\n \"\"\"jones matrix viewed in the rotated frame, where phi is the rotation angle\n \n Performs (R.T).jmat.R where R is the rotation matrix.\n \n Numpy broadcasting rules apply.\n \n Parameters\n ----------\n jmat : (...,2,2) array\n Jones matrix\n phi : float\n Rotation angle.\n \n Returns\n -------\n out : (...,2,2) array\n Rotated jones matrix.\n \n \"\"\"\n r = np.asarray(rotation_matrix2(phi),CDTYPE)\n jmat = np.asarray(jmat)\n rT = np.swapaxes(r,-1,-2)\n return multi_dot([rT,jmat,r])\n\ndef as4x4(jmat, out = None):\n \"\"\"Converts jones 2x2 matrix to eigenfield 4x4 matrix.\n \n Parameters\n ----------\n jmat : (...,2,2) array\n Jones matrix\n out : ndarray, optional\n Output array in which to put the result; if provided, it\n must have a shape that the inputs broadcast to.\n \n Returns\n -------\n mat : (...,4,4) ndarray\n Output jones matrix.\n \"\"\"\n \n if out is None:\n shape = jmat.shape[:-2] + (4,4)\n out = np.zeros(shape, dtype = jmat.dtype)\n else:\n out[...] = 0.\n out[...,0::2,0::2] = jmat \n #for back propagating waves, jones matrix is conjugate\n out[...,1::2,1::2] = np.conj(jmat)\n\n return out\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()",
"\"\"\"\nField denoising functions.\n\"\"\"\n\nimport numpy as np\nfrom dtmm.conf import FDTYPE\nfrom dtmm.wave import betaphi\nfrom dtmm.fft import fft2,ifft2\n\ndef tukey_notch_filter(x,x0,alpha):\n x = np.asarray(x, FDTYPE)\n out = np.ones(x.shape, FDTYPE)\n alpha = alpha * x0\n mask = (x < x0 + alpha)\n mask = np.logical_and(mask, (x > x0 - alpha))\n if alpha > 0.:\n tmp = 1/2*(1-np.cos(np.pi*(x-x0)/alpha))\n out[mask] = tmp[mask]\n return out \n\ndef exp_notch_filter(x,x0,sigma):\n return np.asarray((1 - 1*np.exp(-np.abs(x-x0).clip(0,x0)/sigma))/(1-1*np.exp(-x0/sigma)),FDTYPE)\n\ndef denoise_field(field, wavenumbers, beta , smooth = 1, filter_func = exp_notch_filter, out = None):\n \"\"\"Denoises field by attenuating modes around the selected beta parameter.\n \"\"\"\n ffield = fft2(field, out = out)\n ffield = denoise_fftfield(ffield, wavenumbers, beta, smooth = smooth, filter_func = filter_func, out = ffield)\n return ifft2(ffield, out = ffield)\n\ndef denoise_fftfield(ffield, wavenumbers, beta, smooth = 1, filter_func = exp_notch_filter, out = None):\n \"\"\"Denoises fourier transformed field by attenuating modes around the selected beta parameter.\n \"\"\"\n shape = ffield.shape[-2:]\n b, p = betaphi(shape,wavenumbers)\n f = filter_func(b, beta, smooth)\n f = f[...,None,:,:]\n ffield = np.multiply(ffield, f, out = out)\n return ffield\n"
] |
[
[
"numpy.swapaxes",
"numpy.conj",
"numpy.asarray",
"numpy.cos",
"numpy.sin",
"numpy.array",
"numpy.zeros",
"numpy.empty"
],
[
"numpy.abs",
"numpy.multiply",
"numpy.asarray",
"numpy.cos",
"numpy.ones",
"numpy.exp",
"numpy.logical_and"
]
] |
NkosenhleDuma/pandas-ta
|
[
"7ae7b1695c1fcc26c5a012cacca7aec8220599e0"
] |
[
"pandas_ta/utils/_math.py"
] |
[
"# -*- coding: utf-8 -*-\nfrom functools import reduce\nfrom math import fabs, floor\nfrom operator import mul\nfrom sys import float_info as sflt\n\nfrom numpy import dot, ones, triu\nfrom numpy import append as npAppend\nfrom numpy import array as npArray\nfrom numpy import corrcoef as npCorrcoef\nfrom numpy import dot\nfrom numpy import ndarray as npNdArray\nfrom numpy import seterr\nfrom numpy import sqrt as npSqrt\nfrom numpy import sum as npSum\n\nfrom pandas import DataFrame, Series\n\nfrom pandas_ta import Imports\nfrom ._core import verify_series\n\n\ndef combination(**kwargs):\n \"\"\"https://stackoverflow.com/questions/4941753/is-there-a-math-ncr-function-in-python\"\"\"\n n = int(fabs(kwargs.pop(\"n\", 1)))\n r = int(fabs(kwargs.pop(\"r\", 0)))\n\n if kwargs.pop(\"repetition\", False) or kwargs.pop(\"multichoose\", False):\n n = n + r - 1\n\n # if r < 0: return None\n r = min(n, n - r)\n if r == 0:\n return 1\n\n numerator = reduce(mul, range(n, n - r, -1), 1)\n denominator = reduce(mul, range(1, r + 1), 1)\n return numerator // denominator\n\n\ndef fibonacci(n:int = 2, **kwargs) -> npNdArray:\n \"\"\"Fibonacci Sequence as a numpy array\"\"\"\n n = int(fabs(n)) if n >= 0 else 2\n\n zero = kwargs.pop(\"zero\", False)\n if zero:\n a, b = 0, 1\n else:\n n -= 1\n a, b = 1, 1\n\n result = npArray([a])\n for i in range(0, n):\n a, b = b, a + b\n result = npAppend(result, a)\n\n weighted = kwargs.pop(\"weighted\", False)\n if weighted:\n fib_sum = npSum(result)\n if fib_sum > 0:\n return result / fib_sum\n else:\n return result\n else:\n return result\n\n\ndef linear_regression(x:Series, y:Series) -> dict:\n \"\"\"Classic Linear Regression in Numpy or Scikit-Learn\"\"\"\n x, y = verify_series(x), verify_series(y)\n m, n = x.size, y.size\n\n if m != n:\n print(\n f\"[X] Linear Regression X and y observations do not match: {m} != {n}\"\n )\n return\n\n if Imports[\"sklearn\"]:\n return _linear_regression_sklearn(x, y)\n else:\n return _linear_regression_np(x, y)\n\n\ndef pascals_triangle(n:int = None, **kwargs) -> npNdArray:\n \"\"\"Pascal's Triangle\n\n Returns a numpy array of the nth row of Pascal's Triangle.\n n=4 => triangle: [1, 4, 6, 4, 1]\n => weighted: [0.0625, 0.25, 0.375, 0.25, 0.0625]\n => inverse weighted: [0.9375, 0.75, 0.625, 0.75, 0.9375]\n \"\"\"\n n = int(fabs(n)) if n is not None else 0\n\n # Calculation\n triangle = npArray([combination(n=n, r=i) for i in range(0, n + 1)])\n triangle_sum = npSum(triangle)\n triangle_weights = triangle / triangle_sum\n inverse_weights = 1 - triangle_weights\n\n weighted = kwargs.pop(\"weighted\", False)\n inverse = kwargs.pop(\"inverse\", False)\n if weighted and inverse:\n return inverse_weights\n if weighted:\n return triangle_weights\n if inverse:\n return None\n\n return triangle\n\n\ndef symmetric_triangle(n:int = None, **kwargs) -> list:\n \"\"\"Symmetric Triangle with n >= 2\n\n Returns a numpy array of the nth row of Symmetric Triangle.\n n=4 => triangle: [1, 2, 2, 1]\n => weighted: [0.16666667 0.33333333 0.33333333 0.16666667]\n \"\"\"\n n = int(fabs(n)) if n is not None else 2\n\n if n == 2:\n triangle = [1, 1]\n\n if n > 2:\n if n % 2 == 0:\n front = [i + 1 for i in range(0, floor(n / 2))]\n triangle = front + front[::-1]\n else:\n front = [i + 1 for i in range(0, floor(0.5 * (n + 1)))]\n triangle = front.copy()\n front.pop()\n triangle += front[::-1]\n\n if kwargs.pop(\"weighted\", False):\n triangle_sum = npSum(triangle)\n triangle_weights = triangle / triangle_sum\n return triangle_weights\n\n return triangle\n\n\ndef weights(w):\n\n def _dot(x):\n return dot(w, x)\n\n return _dot\n\n\ndef zero(x:[int, float]) -> [int, float]:\n \"\"\"If the value is close to zero, then return zero.\n Otherwise return itself.\"\"\"\n return 0 if abs(x) < sflt.epsilon else x\n\n\n# TESTING\n\n\ndef df_error_analysis(dfA: DataFrame, dfB: DataFrame, **kwargs) -> DataFrame:\n \"\"\"DataFrame Correlation Analysis helper\"\"\"\n corr_method = kwargs.pop(\"corr_method\", \"pearson\")\n\n # Find their differences and correlation\n diff = dfA - dfB\n corr = dfA.corr(dfB, method=corr_method)\n\n # For plotting\n if kwargs.pop(\"plot\", False):\n diff.hist()\n if diff[diff > 0].any():\n diff.plot(kind=\"kde\")\n\n if kwargs.pop(\"triangular\", False):\n return corr.where(triu(ones(corr.shape)).astype(bool))\n\n return corr\n\n\n# PRIVATE\ndef _linear_regression_np(x: Series, y: Series) -> dict:\n \"\"\"Simple Linear Regression in Numpy for two 1d arrays for environments\n without the sklearn package.\"\"\"\n m = x.size\n x_sum = x.sum()\n y_sum = y.sum()\n\n # 1st row, 2nd col value corr(x, y)\n r = npCorrcoef(x, y)[0, 1]\n\n r_mixture = m * (x * y).sum() - x_sum * y_sum\n b = r_mixture / (m * (x * x).sum() - x_sum * x_sum)\n a = y.mean() - b * x.mean()\n line = a + b * x\n\n _np_err = seterr()\n seterr(divide=\"ignore\", invalid=\"ignore\")\n result = {\n \"a\": a, \"b\": b, \"r\": r,\n \"t\": r / npSqrt((1 - r * r) / (m - 2)),\n \"line\": line,\n }\n seterr(divide=_np_err[\"divide\"], invalid=_np_err[\"invalid\"])\n return result\n\ndef _linear_regression_sklearn(x: Series, y: Series):\n \"\"\"Simple Linear Regression in Scikit Learn for two 1d arrays for\n environments with the sklearn package.\"\"\"\n from sklearn.linear_model import LinearRegression\n\n X = DataFrame(x)\n lr = LinearRegression().fit(X, y=y)\n r = lr.score(X, y=y)\n a, b = lr.intercept_, lr.coef_[0]\n\n result = {\n \"a\": a, \"b\": b, \"r\": r,\n \"t\": r / npSqrt((1 - r * r) / (x.size - 2)),\n \"line\": a + b * x\n }\n return result\n"
] |
[
[
"numpy.dot",
"numpy.sqrt",
"pandas.DataFrame",
"numpy.ones",
"numpy.seterr",
"numpy.append",
"sklearn.linear_model.LinearRegression",
"numpy.corrcoef",
"numpy.array",
"numpy.sum"
]
] |
mxvscorrupcion/pemex_contrataciones
|
[
"6c5e44aa29bf7f7d1bc17f376fd11eb3d146d55d"
] |
[
"src/pemex_contratos/load_data_proveedores.py"
] |
[
"import pandas as pd\nimport numpy as np\nfrom pathlib import Path\nfrom .utils import homologar_razon_social\n\n\ndef cargar_no_localizados(path: str):\n df = pd.read_csv(path, encoding='latin-1', usecols=['RFC', 'RAZÓN SOCIAL'])\n df = df.rename(columns={'RAZÓN SOCIAL': 'razon_social'})\n rs = df.razon_social.fillna('').astype(str).str.upper()\n rs = homologar_razon_social(rs).replace('', np.nan)\n df = df.assign(razon_social=rs)\n df = df.drop_duplicates()\n return df\n\n\ndef cargar_padron_proveedores(path: str):\n names = {\n 'DENOMINACIÓN O RAZÓN SOCIAL DEL PROVEEDOR O CONTRATISTA': 'razon_social',\n 'RFC DE LA PERSONA FÍSICA O MORAL CON HOMOCLAVE INCLUIDA': 'RFC',\n }\n dfs = [\n pd.read_csv(p, encoding='latin-1', skiprows=3, usecols=names.keys())\n for p in Path(path).glob('*/*/*/*/32*csv')\n ]\n df = pd.concat(dfs, axis=0, ignore_index=True)\n df = df.rename(columns=names)\n rs = df.razon_social.fillna('').astype(str).str.upper()\n rs = homologar_razon_social(rs).replace('', np.nan)\n df = df.assign(razon_social=rs)\n df = df.drop_duplicates()\n return df\n\n\ndef cargar_lista_contribuyentes_69b(path):\n \"\"\"Función que carga y limpia la tabla del Listado completo\n de contribueyentes artículo 69 B.\n http://omawww.sat.gob.mx/cifras_sat/Paginas/datos/vinculo.html?page=ListCompleta69B.html\n Parameters\n ----------\n path: str\n Ruta del archivo descargado de la página\n Returns\n -------\n Tabla con el nombre de la empresa limpia y el RFC\n \"\"\"\n df = pd.read_csv(\n path,\n encoding=\"iso-8859-1\",\n skiprows=2,\n usecols=[\"RFC\", \"Nombre del Contribuyente\", 'Situación del contribuyente'],\n )\n df = df.rename(\n columns={\"Nombre del Contribuyente\": \"razon_social\",\n 'Situación del contribuyente': 'situacion_contribuyente'}\n )\n rs = df.razon_social.fillna('').astype(str).str.upper().str.strip()\n rs = homologar_razon_social(rs).replace('', np.nan)\n df = df.assign(razon_social=rs)\n df = df.dropna().drop_duplicates()\n return df\n\n\ndef cargar_particulares_sancionados(path):\n names = {'nombre_razon_social': 'razon_social', 'rfc': 'RFC'}\n df = pd.read_json(path)\n df = df.rename(columns=names)\n df = df.loc[:, ['razon_social', 'RFC']]\n rs = df.razon_social.fillna('').astype(str).str.upper().str.strip()\n rs = homologar_razon_social(rs).replace('', np.nan)\n df = df.assign(razon_social=rs)\n df = df.drop_duplicates()\n return df\n\n\ndef cargar_proveedores_sancionados(path: str):\n names = {'PROVEEDOR O CONTRATISTA': 'razon_social'}\n df = pd.read_csv(path, encoding='latin-1', usecols=['PROVEEDOR O CONTRATISTA'])\n df = df.rename(columns=names)\n rs = df.razon_social.fillna('').astype(str).str.upper().str.strip()\n rs = homologar_razon_social(rs).replace('', np.nan)\n df = df.assign(razon_social=rs)\n df = df.dropna().drop_duplicates()\n return df\n\n\n# def cargar_listado_proveedores(path: str) -> pd.DataFrame:\n# names = {\n# 'DENOMINACIÓN O RAZÓN SOCIAL DEL PROVEEDOR O CONTRATISTA': 'razon_social',\n# 'RFC DE LA PERSONA FÍSICA O MORAL CON HOMOCLAVE INCLUIDA': 'RFC',\n# }\n# df = pd.read_csv(path, usecols=names.keys())\n# df = df.rename(columns=names)\n# rs = df.razon_social.fillna('').astype(str).str.upper()\n# rs = homologar_razon_social(rs).replace('', np.nan)\n# df = df.assign(razon_social=rs)\n# df = df.drop_duplicates()\n# return df\n"
] |
[
[
"pandas.concat",
"pandas.read_csv",
"pandas.read_json"
]
] |
vatervonacht/dagster
|
[
"595d78c883ef20618052ac1575fe46cde51fd541"
] |
[
"examples/dagster_examples_tests/bay_bikes_tests/test_solids.py"
] |
[
"# pylint: disable=redefined-outer-name, W0613\nimport os\n\nimport pytest\nfrom dagster_examples.bay_bikes.resources import credentials_vault\nfrom dagster_examples.bay_bikes.solids import (\n MultivariateTimeseries,\n Timeseries,\n download_weather_report_from_weather_api,\n)\nfrom numpy import array\nfrom numpy.testing import assert_array_equal\nfrom pandas import DataFrame\nfrom requests import HTTPError\n\nfrom dagster import ModeDefinition, execute_solid\n\nSTART_TIME = 1514793600\nVOLUME_TARGET_DIRECTORY = '/tmp/bar'\n\n\nclass MockResponse:\n def __init__(self, return_status_code, json_data):\n self.status_code = return_status_code\n self.json_data = json_data\n\n def raise_for_status(self):\n if self.status_code != 200:\n raise HTTPError(\"BAD\")\n return self.status_code\n\n def json(self):\n return self.json_data\n\n\[email protected]\ndef mock_response_ok():\n return MockResponse(200, {'daily': {'data': [{'time': START_TIME}]}})\n\n\[email protected]\ndef simple_timeseries():\n return Timeseries([1, 2, 3, 4, 5])\n\n\[email protected](\n 'timeseries, memory_length, expected_snapshot_sequence',\n [\n (Timeseries([1, 2, 3, 4, 5]), 1, [[1, 2], [2, 3], [3, 4], [4, 5]]),\n (Timeseries([1, 2, 3, 4, 5]), 2, [[1, 2, 3], [2, 3, 4], [3, 4, 5]]),\n (Timeseries([1, 2, 3, 4, 5]), 4, [[1, 2, 3, 4, 5]]),\n ],\n)\ndef test_timeseries_conversion_ok(timeseries, memory_length, expected_snapshot_sequence):\n assert timeseries.convert_to_snapshot_sequence(memory_length) == expected_snapshot_sequence\n\n\ndef test_timeseries_conversion_no_sequence():\n with pytest.raises(ValueError):\n empty_timeseries = Timeseries([])\n empty_timeseries.convert_to_snapshot_sequence(3)\n\n\[email protected]('memory_length', [0, -1, 5, 6])\ndef test_timeseries_bad_memory_lengths(simple_timeseries, memory_length):\n with pytest.raises(ValueError):\n simple_timeseries.convert_to_snapshot_sequence(memory_length)\n\n\ndef test_multivariate_timeseries_transformation_ok():\n mv_timeseries = MultivariateTimeseries(\n [[1, 2, 3, 4, 5], [0, 1, 2, 3, 4]], [6, 7, 8, 9, 10], ['foo', 'bar'], 'baz'\n )\n matrix, output = mv_timeseries.convert_to_snapshot_matrix(2)\n assert_array_equal(\n matrix,\n array([[[1, 0], [2, 1], [3, 2]], [[2, 1], [3, 2], [4, 3]], [[3, 2], [4, 3], [5, 4]]]),\n )\n assert_array_equal(output, array([8, 9, 10]))\n\n\ndef test_mutlivariate_timeseries_transformation_from_dataframe_ok():\n mv_timeseries_df = DataFrame({'foo': [1, 2, 3], 'bar': [4, 5, 6], 'baz': [0, 0, 0]})\n mv_timeseries = MultivariateTimeseries.from_dataframe(mv_timeseries_df, ['foo', 'bar'], 'baz')\n assert mv_timeseries\n assert mv_timeseries.input_timeseries_collection[0].sequence == [1, 2, 3]\n assert mv_timeseries.input_timeseries_collection[1].sequence == [4, 5, 6]\n assert mv_timeseries.output_timeseries.sequence == [0, 0, 0]\n\n\[email protected]\ndef setup_dark_sky():\n old_api_key = os.environ.get('DARK_SKY_API_KEY', '')\n yield\n # pytest swallows errors and throws them in the request.node object. This is akin to a finally.\n # https://docs.pytest.org/en/latest/example/simple.html#making-test-result-information-available-in-fixtures\n os.environ['DAKR_SKY_API_KEY'] = old_api_key\n\n\ndef test_download_weather_report_from_weather_api_200(mocker, setup_dark_sky, mock_response_ok):\n mock_get = mocker.patch(\n 'dagster_examples.bay_bikes.solids.requests.get', return_value=mock_response_ok\n )\n # Clobber api key for test so we don't expose creds\n os.environ['DARK_SKY_API_KEY'] = 'uuids-will-never-collide'\n solid_result = execute_solid(\n download_weather_report_from_weather_api,\n ModeDefinition(resource_defs={'credentials_vault': credentials_vault,}),\n environment_dict={\n 'resources': {\n 'credentials_vault': {\n 'config': {'environment_variable_names': ['DARK_SKY_API_KEY']}\n },\n },\n 'solids': {\n 'download_weather_report_from_weather_api': {\n 'inputs': {'epoch_date': {'value': START_TIME}}\n }\n },\n },\n ).output_value()\n mock_get.assert_called_with(\n 'https://api.darksky.net/forecast/uuids-will-never-collide/37.8267,-122.4233,1514793600?exclude=currently,minutely,hourly,alerts,flags'\n )\n assert isinstance(solid_result, DataFrame)\n assert solid_result['time'][0] == START_TIME\n assert 'uuid' in solid_result.columns\n"
] |
[
[
"numpy.array",
"pandas.DataFrame"
]
] |
yas-sim/openvino-wrapper
|
[
"97493b6ac98e3d02cc0cde5b259be4a5a0fc3cf4"
] |
[
"iewrap_object_detection.py"
] |
[
"import iewrap\r\n\r\nimport cv2\r\nimport numpy as np\r\n\r\nlabel = open('voc_labels.txt').readlines()\r\nimg = cv2.imread('car_1.bmp')\r\n\r\nie = iewrap.ieWrapper('public/mobilenet-ssd/FP16/mobilenet-ssd.xml', 'CPU')\r\n\r\noutput = ie.blockInfer(img)[0] # Inference\r\n\r\n# Draw bounding boxes and labels onto the image\r\noutput = output.reshape((100,7))\r\nimg_h, img_w, _ = img.shape\r\nfor obj in output:\r\n imgid, clsid, confidence, x1, y1, x2, y2 = obj\r\n if confidence>0.8: # Draw a bounding box and label when confidence>0.8\r\n x1 = int(x1 * img_w)\r\n y1 = int(y1 * img_h)\r\n x2 = int(x2 * img_w)\r\n y2 = int(y2 * img_h)\r\n cv2.rectangle(img, (x1, y1), (x2, y2), (0,255,255), thickness=4 )\r\n cv2.putText(img, label[int(clsid)][:-1], (x1, y1), cv2.FONT_HERSHEY_PLAIN, fontScale=4, color=(0,255,255), thickness=4)\r\n\r\n# Displaying the result image\r\nimport matplotlib.pyplot as plt\r\nimg=cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\nplt.imshow(img)\r\nplt.show()"
] |
[
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.show"
]
] |
jon--lee/Mask_RCNN
|
[
"10bd4484b5163e160325005d1d3621dd888b3c3e"
] |
[
"samples/shapes/eval_rgbd.py"
] |
[
"import matplotlib\nmatplotlib.use('Agg')\nimport os\nimport sys\nimport random\nimport math\nimport re\nimport time\nimport numpy as np\nimport cv2\nimport skimage\nimport json\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport IPython\nfrom eval_rgb import run_eval\n\n# Root directory of the project\nROOT_DIR = os.path.abspath(\"../../\")\n\n# Import Mask RCNN\nsys.path.append(ROOT_DIR) # To find local version of the library\nfrom mrcnn.config import Config\nfrom mrcnn import utils\nimport mrcnn.model as modellib\nfrom mrcnn import visualize\nfrom mrcnn.model import log\n\n\n# # Directory to save logs and trained model\nmodel_dir = '/nfs/diskstation/jonathan/mask/logs/'\nmodel_path = os.path.join(model_dir, \"grasps_rgbd/mask_rcnn_grasps_0029.h5\")\ndataset_dir = \"/nfs/diskstation/jonathan/mask/dataset/dataset_rgbd\"\ndataset_val_dir = \"/nfs/diskstation/jonathan/mask/dataset/dataset_rgbd_val\"\n\n\nimage_dir = os.path.join(dataset_dir, \"images/\")\nimage_val_dir = os.path.join(dataset_val_dir, \"images/\")\n\nanno_dir = os.path.join(dataset_dir, \"annotations/\")\nanno_val_dir = os.path.join(dataset_val_dir, \"annotations/\")\n\noutput_dir = './output/output_rgbd/'\noutput_results_dir = './output/output_rgbd_results/'\n\n\n\n\nif __name__ == '__main__':\n run_eval(model_dir, model_path, image_dir, image_val_dir, \n output_dir, output_results_dir, anno_dir, anno_val_dir)\n\n\n"
] |
[
[
"matplotlib.use"
]
] |
asl-epfl/asl-eusipco2020
|
[
"60fa42f598c8b39c9d3379df9a085607f8d873c5"
] |
[
"codefig1.py"
] |
[
"\"\"\"\nThis code can be used to generate simulations similar to Fig. 1 in the following paper:\nVirginia Bordignon, Vincenzo Matta, and Ali H. Sayed, \"Adaptation in online social learning,'' Proc. EUSIPCO, pp. 1-5, Amsterdam, The Netherlands, August 2020.\n\nPlease note that the code is not generally perfected for performance, but is rather meant to illustrate certain results from the paper. The code is provided as-is without guarantees.\n\nJuly 2020 (Author: Virginia Bordignon)\n\"\"\"\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport networkx as nx\nimport os\nfrom functions import *\n#%%\ngetcontext().prec = 200\nmpl.style.use('seaborn-deep')\nplt.rcParams.update({'text.usetex': True})\nmpl.rcParams['font.family'] = 'serif'\n#%%\nFIG_PATH = 'figs/'\nif not os.path.isdir(FIG_PATH):\n os.makedirs(FIG_PATH)\n#%%\nN = 10\nM = 3\nnp.random.seed(0)\n# %%\n################################ Build Network Topology ################################\nG = np.random.choice([0.0,1.0], size=(N, N), p = [0.5,0.5])\nG = G + np.eye(N)\nG = (G > 0) * 1.0\nlamb = .5\n\nA = np.zeros((N, N))\nA = G / G.sum(axis = 0)\nA_dec = np.array([[Decimal(x) for x in y] for y in A])\n#%%\n################################ Run Social Learning ################################\nnp.random.seed(20)\nN_ITER = 600\ntheta = np.array([1., 2., 3.]) * .6\nthetadec = decimal_array(theta)\nvar = 1\nvardec = Decimal(var)\nx = np.linspace(-10, 10, 1000)\nx_dec = decimal_array(x)\ndt = (max(x) - min(x)) / len(x)\ndtdec = (max(x_dec) - min(x_dec)) / len(x_dec)\n# %%\nmu_0 = np.random.rand(N, M)\nmu_0 = mu_0 / np.sum(mu_0, axis = 1)[:, None]\nmu_0dec = decimal_array(mu_0)\ndelta = .1\n# %%\ncsi=[]\nfor l in range(0, N):\n csi.append(np.hstack([theta[0] + np.sqrt(var) * np.random.randn(200), theta[2] + np.sqrt(var) * np.random.randn(N_ITER - 200)]))\ncsi = np.array(csi)\ncsidec = decimal_array(csi)\n# %%\nMU_adapt = asl(mu_0, csi, A, N_ITER, theta, var, N, delta)\nMU = sl(mu_0dec, csidec, A_dec, N_ITER, thetadec, vardec, N)\n# %%\ndec_sl = np.argmax(np.array(MU), axis = 2)[:,0]\ndec_asl = np.argmax(np.array(MU_adapt), axis = 2)[:,0]\n# %%\nfig, ax = plt.subplots(2, 2, figsize = (6, 4.5), gridspec_kw = {'height_ratios': [1, 1]})\nplot_agent_dec(MU, N_ITER, 0, ax[0, 0])\nax[0, 0].set_ylabel('Belief \\nof Agent 1', fontsize = 16)\nax[0, 0].set_xlabel('Iteration', fontsize = 16)\nax[0, 0].set_xticks([0, 200, 400, 600])\nax[1, 0].scatter(np.argwhere(dec_sl == 0)[:, 0], np.ones(len(np.argwhere(dec_sl == 0)[:, 0])), s = 20, marker = '.', color = 'C0')\nax[1, 0].scatter(np.argwhere(dec_sl == 1)[:, 0], 2 * np.ones(len(np.argwhere(dec_sl == 1)[:, 0])), s = 20, marker = '.', color = 'C1')\nax[1, 0].scatter(np.argwhere(dec_sl == 2)[:, 0], 3 * np.ones(len(np.argwhere(dec_sl == 2)[:, 0])), s = 20, marker = '.', color = 'C2')\nax[1, 0].set_xlim(0, N_ITER)\nax[1, 0].set_ylabel('Opinion \\nof Agent 1', fontsize = 16)\nax[1, 0].set_xlabel('Iteration', fontsize = 16)\nax[0, 0].set_title('Social Learning', fontsize = 16)\nax[1, 0].set_ylim(0.5, 3.5)\nax[1, 0].yaxis.grid()\nax[1, 0].set_axisbelow(True)\nax[1, 0].tick_params(axis = 'x', which = 'major', labelsize = 16)\nax[1, 0].set_yticks([1,2,3])\nax[1, 0].set_xticks([0, 200, 400, 600])\nax[1, 0].set_yticklabels(['S','C','R'], size = 14)\nplot_agent(MU_adapt, N_ITER, 0, ax[0,1])\nax[0, 1].set_xlabel('Iteration', fontsize = 16)\nax[0, 1].set_xticks([0,200,400,600])\nax[1, 1].scatter(np.argwhere(dec_asl == 0) [:, 0], np.ones(len(np.argwhere(dec_asl == 0)[:, 0])), s = 20, marker = '.', color ='C0')\nax[1, 1].scatter(np.argwhere(dec_asl == 1)[:, 0], 2 * np.ones(len(np.argwhere(dec_asl == 1)[:, 0])), s = 20, marker = '.', color = 'C1')\nax[1, 1].scatter(np.argwhere(dec_asl == 2)[:, 0], 3 * np.ones(len(np.argwhere(dec_asl == 2)[:, 0])), s = 20, marker = '.', color = 'C2')\nax[1, 1].set_xlim(0, N_ITER)\nax[0, 1].set_ylabel('')\nax[1, 1].set_xlabel('Iteration', fontsize = 16)\nax[0, 1].set_title('Adaptive Social Learning', fontsize = 16)\nax[1, 1].set_ylim(0.5, 3.5)\nax[0, 1].set_ylim(0.1, .6)\nax[1, 1].yaxis.grid()\nax[1, 1].set_axisbelow(True)\nax[1, 1].tick_params(axis = 'x', which = 'major', labelsize = 16)\nax[1, 1].set_yticks([1, 2, 3])\nax[1, 1].set_xticks([0, 200, 400, 600])\nax[1, 1].set_yticklabels(['S', 'C', 'R'], size = 14)\nfig.legend([r'Sunny', r'Cloudy', r'Rainy'], ncol = M, loc = 'center', bbox_to_anchor = (0.5, 0.05), fontsize = 16, handlelength = 1)\nfig.tight_layout(rect = (0, 0.05, 1, 1))\nfig.savefig(FIG_PATH + 'fig1.pdf', bbox_inches = 'tight')\n"
] |
[
[
"matplotlib.pyplot.rcParams.update",
"matplotlib.pyplot.subplots",
"matplotlib.style.use"
]
] |
sehovaclj/fruit_classification
|
[
"8a235e3f40c5e8d3033e8f4a4f1aedeb26e799af"
] |
[
"creating_datasets.py"
] |
[
"# Run this code first!\n\n# Author: Ljubisa Sehovac\n# github: sehovaclj\n\n# email: [email protected]\n# feel free to email me with questions, concerns, fixes, etc.\n\n# the datasets were obtained from Kaggle.com. \n# Make sure to download these datasets and store them in your working directory. They will be downloaded as \"Training/\", \"Test/\", and \"test-multiple_fruits\" the specific url is: https://www.kaggle.com/moltean/fruits.\n# At the time of obtaining the dataset, there were only 65k images -- still plenty of images to work with.\n\n# This is part 1 of the entire process, hence manually creating the training and testing sets by converting the images to pixel form (3D matrices -- 3x100x100)\n\n# over 65k total images, 95 different fruits -- see readme file\n\n\n# !!Note!! all scripts were run on personal laptop: ~16 GB of CPU RAM, ~38 GB of swap memory, ~6 GB GPU RAM\n\n\n\n\n# importing\nimport numpy as np\n\nimport torch\n\nfrom PIL import Image\n\nimport glob\nimport os\n\nimport pickle\n\n\n\n############################################################################################\n\n# loop through all files. loop through all images. read images --> get pixels --> store pixels\n# as dict --> append dict to list\n\n# FOR TRIANING\n\nall_fruit_files_train = []\n\nfor fruit_file in glob.glob(\"Training/*\"):\t\t# make sure you are working in the directory where the \"Training/\" folder is located. The same goes for \"Test/\" below.\n\tall_fruit_files_train.append(fruit_file) \t# appending all fruit folders to one list\n\n\n\n# store pixel values as dict\n\nIMAGES_TRAINING = []\n\ncounter = 0\n\nclass_number = np.arange(len(all_fruit_files_train))\n\n\nfor i in all_fruit_files_train:\n\n\timages_files = glob.glob(i + '/*.jpg') \t# read each image file\n\tclss = class_number[counter]\n\tcounter += 1\n\n\tfor j in images_files:\n\t\tim = Image.open(j)\n\t\tw, h = im.size \t# get width and height of image\n\t\tpixels = list(im.getdata()) \t# get pixel data as list\n\t\tpixels = np.array(pixels).reshape(h, w, 3) # convert to array with dimensions h x w x 3, which is 100x100x3\n\t\tdict = { clss : torch.from_numpy(pixels).float().view(3, h, w) } # create dict, convert to float torch tensor, and change the shape to 3x100x100\n\t\tIMAGES_TRAINING.append(dict) # store dict\n\n\n\n# FOR TESTING\n\n\nIMAGES_TESTING = []\n\nall_fruit_files_test = []\n\nfor fruit_file in glob.glob(\"Test/*\"):\n\tall_fruit_files_test.append(fruit_file)\n\n\n\n# making sure that glob does not mess up the classes.\n# Class = 0 should be Strawberry wedge and class = -1 (last class) should be Pomelo Sweetie\na1 = []\na2 = []\n\ns1 = len('Training/')\ns2 = len('Test/')\n\nfor i in all_fruit_files_train:\n\ta1.append(i[s1:])\nfor i in all_fruit_files_test:\n\ta2.append(i[s2:])\n\nif a1 == a2:\n\tprint('\\nclasses are the same for training and testing sets, glob does not mess it up')\n\tprint('can do print(a1) and print(a2) to check\\n')\n\n# defining classes\nclasses = a1\n\ncounter = 0\n\nclass_number = np.arange(len(all_fruit_files_test))\n\n# store pixel values as dict\n\nfor i in all_fruit_files_test:\n\n\timages_files = glob.glob(i + '/*.jpg')\n\tclss = class_number[counter]\n\tcounter += 1\n\n\tfor j in images_files:\n\t\tim = Image.open(j)\n\t\tw, h = im.size\n\t\tpixels = list(im.getdata())\n\t\tpixels = np.array(pixels).reshape(h, w, 3)\n\t\tdict = { clss : torch.from_numpy(pixels).float().view(3, h, w) }\n\t\tIMAGES_TESTING.append(dict)\n\n\n\n\n# to check, you can run these commands:\n#\n# len(IMAGES_TRAINING) \t\t\t# output: total number of training images\n# len(IMAGES_TRAINING[0])\t\t# output: 1 (because this is one dict value, or image)\n# IMAGES_TRAINING[0][0].shape\t# output: (3, 100, 100), here the first [0] is the image, and the second [0] is the class. [737][0] is the last image for Strawberry Wedge, or class 0\n\n\n####################################################################################\n\n# pickling IMAGES_TRAINING and IMAGES_TESTING\n\n\nwith open('images_training.pkl', 'wb') as f:\n\tpickle.dump(IMAGES_TRAINING, f)\nwith open('images_testing.pkl', 'wb') as f:\n\tpickle.dump(IMAGES_TESTING, f)\n\nwith open('classes.pkl', 'wb') as f:\n\tpickle.dump(classes, f)\n\n\n\n\n\n\n\n"
] |
[
[
"numpy.array",
"torch.from_numpy"
]
] |
kim-younghan/CompoundScalingSeg
|
[
"8fad8f03ac02f3613466572a542ae5b0f50ed067"
] |
[
"CompoundScalingSeg/trainer.py"
] |
[
"import abc\nimport os\nimport sys\nimport tqdm\nimport torch\nimport datetime\n\nfrom torch.utils.data import DataLoader\nfrom typing import Callable, Any\nfrom typing import NamedTuple, List\nfrom torchvision.utils import make_grid\n\ndef to_np(x):\n return x.data.cpu().numpy()\n\nclass BatchResult(NamedTuple):\n \"\"\"\n Represents the result of training for a single batch: the loss\n and score of the batch.\n \"\"\"\n loss: float\n score: float\n\n\nclass EpochResult(NamedTuple):\n \"\"\"\n Represents the result of training for a single epoch: the loss per batch\n and accuracy on the dataset (train or test).\n \"\"\"\n losses: List[float]\n score: float\n\n\nclass FitResult(NamedTuple):\n \"\"\"\n Represents the result of fitting a model for multiple epochs given a\n training and test (or validation) set.\n The losses are for each batch and the accuracies are per epoch.\n \"\"\"\n num_epochs: int\n train_loss: List[float]\n train_acc: List[float]\n test_loss: List[float]\n test_acc: List[float]\n best_score: float\n\nclass Trainer:\n \"\"\"\n A class abstracting the various tasks of training models.\n\n Provides methods at multiple levels of granularity:\n - Multiple epochs (fit)\n - Single epoch (train_epoch/test_epoch)\n - Single batch (train_batch/test_batch)\n \"\"\"\n def __init__(self,\n model,\n loss_fn,\n optimizer,\n objective_metric,\n device=\"cuda\",\n tensorboard_logger=None,\n tensorboard_log_images=True,\n experiment_prefix=None):\n \"\"\"\n Initialize the trainer.\n :param model: Instance of the model to train.\n :param loss_fn: The loss function to evaluate with.\n :param optimizer: The optimizer to train with.\n :param device: torch.device to run training on (CPU or GPU).\n :param tensorboard_logger: tensordboard logger.\n \"\"\"\n self.tensorboard_logger = tensorboard_logger\n\n if experiment_prefix is None:\n now = datetime.datetime.now()\n self.experiment_prefix = now.strftime(r\"%Y-%m-%d\\%H:%M:%S\")\n else:\n self.experiment_prefix = experiment_prefix\n self.tensorboard_log_images = tensorboard_log_images\n self.model = model\n self.loss_fn = loss_fn\n self.optimizer = optimizer\n self.objective_metric = objective_metric\n self.device = device\n\n if self.device:\n model.to(self.device)\n\n def fit(self, dl_train: DataLoader, dl_test: DataLoader,\n num_epochs, checkpoints: str = None,\n early_stopping: int = None,\n print_every=1, **kw) -> FitResult:\n \"\"\"\n Trains the model for multiple epochs with a given training set,\n and calculates validation loss over a given validation set.\n :param dl_train: Dataloader for the training set.\n :param dl_test: Dataloader for the test set.\n :param num_epochs: Number of epochs to train for.\n :param checkpoints: Whether to save model to file every time the\n test set accuracy improves. Should be a string containing a\n filename without extension.\n :param early_stopping: Whether to stop training early if there is no\n test loss improvement for this number of epochs.\n :param print_every: Print progress every this number of epochs.\n :return: A FitResult object containing train and test losses per epoch.\n \"\"\"\n actual_num_epochs = 0\n train_loss, train_acc, test_loss, test_acc = [], [], [], []\n\n best_score = None\n epochs_without_improvement = 0\n\n for epoch in range(num_epochs):\n verbose = False # pass this to train/test_epoch.\n if epoch % print_every == 0 or epoch == num_epochs-1:\n verbose = True\n self._print(f'--- EPOCH {epoch+1}/{num_epochs} ---', verbose)\n\n epoch_train_res = self.train_epoch(dl_train, verbose=verbose, **kw)\n train_loss.extend([float(x.item()) for x in epoch_train_res.losses])\n train_acc.append(float(epoch_train_res.score))\n\n epoch_test_res = self.test_epoch(dl_test, verbose=verbose, **kw)\n test_loss.extend([float(x.item()) for x in epoch_test_res.losses])\n test_acc.append(float(epoch_test_res.score))\n\n if best_score is None:\n best_score = epoch_test_res.score\n elif epoch_test_res.score > best_score:\n best_score = epoch_test_res.score\n if checkpoints is not None:\n #torch.save(self.model, checkpoints)\n print(\"**** Checkpoint saved ****\")\n epochs_without_improvement = 0\n else:\n if early_stopping is not None and epochs_without_improvement >= early_stopping:\n print(\"Early stopping after %s with out improvement\" % epochs_without_improvement)\n break\n epochs_without_improvement += 1\n\n torch.save(self.model, f'./epoch_save_model/{self.model.__class__.__name__}_ckpt_'+str(epoch)+'.pt')\n\n # ========================\n\n return FitResult(actual_num_epochs,\n train_loss, train_acc, test_loss, test_acc, best_score)\n\n def train_epoch(self, dl_train: DataLoader, **kw) -> EpochResult:\n \"\"\"\n Train once over a training set (single epoch).\n :param dl_train: DataLoader for the training set.\n :param kw: Keyword args supported by _foreach_batch.\n :return: An EpochResult for the epoch.\n \"\"\"\n self.model.train() # set train mode\n return self._foreach_batch(dl_train, self.train_batch, **kw)\n\n def test_epoch(self, dl_test: DataLoader, **kw) -> EpochResult:\n \"\"\"\n Evaluate model once over a test set (single epoch).\n :param dl_test: DataLoader for the test set.\n :param kw: Keyword args supported by _foreach_batch.\n :return: An EpochResult for the epoch.\n \"\"\"\n self.model.eval() # set evaluation (test) mode\n return self._foreach_batch(dl_test, self.test_batch, **kw)\n\n def train_batch(self, index, batch_data) -> BatchResult:\n \"\"\"\n Runs a single batch forward through the model, calculates loss,\n preforms back-propagation and uses the optimizer to update weights.\n :param batch: A single batch of data from a data loader (might\n be a tuple of data and labels or anything else depending on\n the underlying dataset.\n :return: A BatchResult containing the value of the loss function and\n the number of correctly classified samples in the batch.\n \"\"\"\n\n X, y = batch_data\n if self.tensorboard_logger and self.tensorboard_log_images:\n B = torch.zeros_like(X.squeeze())\n C = torch.stack([B, X.squeeze(), X.squeeze()])\n C = C.unsqueeze(dim=0)\n images = C\n grid = make_grid(images, normalize=True, scale_each=True)\n self.tensorboard_logger.add_image(\"exp-%s/batch/test/images\" % self.experiment_prefix, grid, index)\n if isinstance(X, tuple) or isinstance(X, list):\n X = [x.to(self.device) for x in X]\n else:\n X = X.to(self.device)\n y = y.to(self.device)\n pred = self.model(X)\n loss = self.loss_fn(pred, y)\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n score = self.objective_metric(pred, y)\n if self.tensorboard_logger:\n self.tensorboard_logger.add_scalar('exp-%s/batch/train/loss' % self.experiment_prefix, loss, index)\n self.tensorboard_logger.add_scalar('exp-%s/batch/train/score' % self.experiment_prefix, score, index)\n if index % 300 == 0:\n for tag, value in self.model.named_parameters():\n tag = tag.replace('.', '/')\n self.tensorboard_logger.add_histogram('exp-%s/batch/train/param/%s' % (self.experiment_prefix, tag), to_np(value), index)\n self.tensorboard_logger.add_histogram('exp-%s/batch/train/param/%s/grad' % (self.experiment_prefix, tag), to_np(value.grad), index)\n\n return BatchResult(loss, score)\n\n def test_batch(self, index, batch_data) -> BatchResult:\n \"\"\"\n Runs a single batch forward through the model and calculates loss.\n :param batch: A single batch of data from a data loader (might\n be a tuple of data and labels or anything else depending on\n the underlying dataset.\n :return: A BatchResult containing the value of the loss function and\n the number of correctly classified samples in the batch.\n \"\"\"\n with torch.no_grad():\n X, y = batch_data\n if isinstance(X, tuple) or isinstance(X, list):\n X = [x.to(self.device) for x in X]\n else:\n X = X.to(self.device)\n y = y.to(self.device)\n pred = self.model(X)\n loss = self.loss_fn(pred, y)\n score = self.objective_metric(pred, y)\n if self.tensorboard_logger:\n self.tensorboard_logger.add_scalar('exp-%s/batch/test/loss' % self.experiment_prefix, loss, index)\n self.tensorboard_logger.add_scalar('exp-%s/batch/test/score' % self.experiment_prefix, score, index)\n return BatchResult(loss, score)\n\n @staticmethod\n def _print(message, verbose=True):\n \"\"\" Simple wrapper around print to make it conditional \"\"\"\n if verbose:\n print(message)\n\n @staticmethod\n def _foreach_batch(dl: DataLoader,\n forward_fn: Callable[[Any], BatchResult],\n verbose=True, max_batches=None) -> EpochResult:\n \"\"\"\n Evaluates the given forward-function on batches from the given\n dataloader, and prints progress along the way.\n \"\"\"\n losses = []\n num_samples = len(dl.sampler)\n num_batches = len(dl.batch_sampler)\n\n if max_batches is not None:\n if max_batches < num_batches:\n num_batches = max_batches\n num_samples = num_batches * dl.batch_size\n\n if verbose:\n pbar_file = sys.stdout\n else:\n pbar_file = open(os.devnull, 'w')\n\n pbar_name = forward_fn.__name__\n with tqdm.tqdm(desc=pbar_name, total=num_batches,\n file=pbar_file) as pbar:\n dl_iter = iter(dl)\n overall_score = overall_loss = avg_score = avg_loss = counter = 0\n min_loss = min_score = 1\n max_loss = max_score = 0\n for batch_idx in range(num_batches):\n counter += 1\n data = next(dl_iter)\n batch_res = forward_fn(batch_idx, data)\n if batch_res.loss > max_loss:\n max_loss = batch_res.loss\n if batch_res.score > max_score:\n max_score = batch_res.score\n\n if batch_res.loss < min_loss:\n min_loss = batch_res.loss\n if batch_res.score < min_score:\n min_score = batch_res.score\n overall_loss += batch_res.loss\n overall_score += batch_res.score\n losses.append(batch_res.loss)\n\n avg_loss = overall_loss / counter\n avg_score = overall_score / counter\n pbar.set_description(f'{pbar_name} (Avg. loss:{avg_loss:.3f}, Avg. score:{avg_score:.3f})')\n pbar.update()\n\n pbar.set_description(f'{pbar_name} '\n f'(Avg. Loss {avg_loss:.3f}, Min {min_loss:.3f}, Max {max_loss:.3f}), '\n f'(Avg. Score {avg_score:.4f}, Min {min_score:.4f}, Max {max_score:.4f})')\n\n return EpochResult(losses=losses, score=avg_score)\n"
] |
[
[
"torch.no_grad"
]
] |
KrishnaswamyLab/scpreprocess
|
[
"926d7be1282d7218a9b61ad555f74489cf3927be"
] |
[
"scprep/run/slingshot.py"
] |
[
"from .. import utils\nfrom . import r_function\n\nimport numpy as np\nimport pandas as pd\nimport warnings\n\n\ndef install(site_repository=None, update=False, version=None, verbose=True):\n \"\"\"Install the required R packages to run Slingshot.\n\n Parameters\n ----------\n site_repository : string, optional (default: None)\n additional repository in which to look for packages to install.\n This repository will be prepended to the default repositories\n update : boolean, optional (default: False)\n When False, don't attempt to update old packages.\n When True, update old packages automatically.\n version : string, optional (default: None)\n Bioconductor version to install, e.g., version = \"3.8\".\n The special symbol version = \"devel\" installs the current 'development' version.\n If None, installs from the current version.\n verbose : boolean, optional (default: True)\n Install script verbosity.\n \"\"\"\n r_function.install_bioconductor(\n \"slingshot\",\n site_repository=site_repository,\n update=update,\n version=version,\n verbose=verbose,\n )\n\n\n_Slingshot = r_function.RFunction(\n setup=\"\"\"\n library(slingshot)\n \"\"\",\n args=\"\"\"\n data, cluster_labels,\n start_cluster = NULL, end_cluster = NULL,\n distance = NULL, omega = NULL, lineages = list(), shrink = TRUE,\n extend = \"y\", reweight = TRUE, reassign = TRUE, thresh = 0.001,\n max_iter = 15, stretch = 2,\n smoother = \"smooth.spline\", shrink_method = \"cosine\",\n allow_breaks = TRUE, seed = NULL, ...\n \"\"\",\n body=\"\"\"\n set.seed(seed)\n data <- as.matrix(data)\n cluster_labels <- as.factor(cluster_labels)\n\n # Run Slingshot\n sling <- slingshot(data, clusterLabels = cluster_labels,\n start.clus = start_cluster, end.clus = end_cluster,\n dist.fun = distance, omega = omega, lineages = lineages,\n shrink = shrink, extend = extend, reweight = reweight,\n reassign = reassign, thresh = thresh,\n maxit = max_iter, stretch = stretch,\n smoother = smoother, shrink.method = shrink_method,\n allow.breaks = allow_breaks, ...)\n list(pseudotime = slingPseudotime(sling),\n curves = lapply(sling@curves, function(curve) curve$s[curve$ord,]))\n \"\"\",\n)\n\n\ndef Slingshot(\n data,\n cluster_labels,\n start_cluster=None,\n end_cluster=None,\n distance=None,\n omega=None,\n shrink=True,\n extend=\"y\",\n reweight=True,\n reassign=True,\n thresh=0.001,\n max_iter=15,\n stretch=2,\n smoother=\"smooth.spline\",\n shrink_method=\"cosine\",\n allow_breaks=True,\n seed=None,\n verbose=1,\n **kwargs,\n):\n \"\"\"Perform lineage inference with Slingshot.\n\n Given a reduced-dimensional data matrix n by p and a vector of cluster labels\n (or matrix of soft cluster assignments, potentially including a -1 label for\n \"unclustered\"), this function performs lineage inference using a cluster-based\n minimum spanning tree and constructing simulatenous principal curves for branching\n paths through the tree.\n\n For more details, read about Slingshot on GitHub_ and Bioconductor_.\n\n .. _GitHub: https://github.com/kstreet13/slingshot\n .. _Bioconductor: https://bioconductor.org/packages/release/bioc/html/slingshot.html\n\n Parameters\n ----------\n data : array-like, shape=[n_samples, n_dimensions]\n matrix of (reduced dimension) coordinates\n to be used for lineage inference.\n cluster_labels : list-like, shape=[n_samples]\n a vector of cluster labels, optionally including -1's for \"unclustered.\"\n start_cluster : string, optional (default: None)\n indicates the cluster(s) of origin.\n Lineages will be represented by paths coming out of this cluster.\n end_cluster : string, optional (default: None)\n indicates the cluster(s) which will be forced leaf nodes.\n This introduces a constraint on the MST algorithm.\n distance : callable, optional (default: None)\n method for calculating distances between clusters.\n Must take two matrices as input, corresponding to subsets of reduced_dim.\n If the minimum cluster size is larger than the number dimensions,\n the default is to use the joint covariance matrix to find squared distance\n between cluster centers. If not, the default is to use the diagonal of the\n joint covariance matrix. Not currently implemented\n omega : float, optional (default: None)\n this granularity parameter determines the distance between every\n real cluster and the artificial cluster.\n It is parameterized such that this distance is omega / 2,\n making omega the maximum distance between two connected clusters.\n By default, omega = Inf.\n shrink : boolean or float, optional (default: True)\n boolean or numeric between 0 and 1, determines whether and how much to shrink\n branching lineages toward their average prior to the split.\n extend : {'y', 'n', 'pc1'}, optional (default: \"y\")\n how to handle root and leaf clusters of lineages when\n constructing the initial, piece-wise linear curve.\n reweight : boolean, optional (default: True)\n whether to allow cells shared between lineages to be reweighted during\n curve-fitting. If True, cells shared between lineages will be iteratively\n reweighted based on the quantiles of their projection distances to each curve.\n reassign : boolean, optional (default: True)\n whether to reassign cells to lineages at each iteration.\n If True, cells will be added to a lineage when their\n projection distance to the curve is less than the median\n distance for all cells currently assigned to the lineage.\n Additionally, shared cells will be removed from a lineage if\n their projection distance to the curve is above the 90th\n percentile and their weight along the curve is less than 0.1.\n thresh : float, optional (default: 0.001)\n determines the convergence criterion. Percent change in the\n total distance from cells to their projections along curves\n must be less than thresh.\n max_iter : int, optional (default: 15)\n maximum number of iterations\n stretch : int, optional (default: 2)\n factor between 0 and 2 by which curves can be extrapolated beyond endpoints\n smoother : {\"smooth.spline\", \"lowess\", \"periodic_lowess\"},\n optional (default: \"smooth.spline\")\n choice of smoother. \"periodic_lowess\" allows one to fit closed\n curves. Beware, you may want to use iter = 0 with \"lowess\".\n shrink_method : string, optional (default: \"cosine\")\n how to determine the appropriate amount of shrinkage for a\n branching lineage. Accepted values: \"gaussian\", \"rectangular\",\n \"triangular\", \"epanechnikov\", \"biweight\", \"triweight\",\n \"cosine\", \"optcosine\", \"density\".\n allow_breaks : boolean, optional (default: True)\n determines whether curves that branch very close to the origin\n should be allowed to have different starting points.\n seed : int or None, optional (default: None)\n Seed to use for generating random numbers.\n verbose : int, optional (default: 1)\n Logging verbosity between 0 and 2.\n\n Returns\n -------\n slingshot : dict\n Contains the following keys:\n pseudotime : array-like, shape=[n_samples, n_curves]\n Pseudotime projection of each cell onto each principal curve.\n Value is `np.nan` if the cell does not lie on the curve\n branch : list-like, shape=[n_samples]\n Branch assignment for each cell\n curves : array_like, shape=[n_curves, n_samples, n_dimensions]\n Coordinates of each principle curve in the reduced dimension\n\n Examples\n --------\n >>> import scprep\n >>> import phate\n >>> data, clusters = phate.tree.gen_dla(n_branch=4, n_dim=200, branch_length=200)\n >>> phate_op = phate.PHATE()\n >>> data_phate = phate_op.fit_transform(data)\n >>> slingshot = scprep.run.Slingshot(data_phate, clusters)\n >>> ax = scprep.plot.scatter2d(\n ... data_phate,\n ... c=slingshot['pseudotime'][:,0],\n ... cmap='magma',\n ... legend_title='Branch 1'\n ... )\n >>> scprep.plot.scatter2d(\n ... data_phate,\n ... c=slingshot['pseudotime'][:,1],\n ... cmap='viridis',\n ... ax=ax,\n ... ticks=False,\n ... label_prefix='PHATE',\n ... legend_title='Branch 2'\n ... )\n >>> for curve in slingshot['curves']:\n ... ax.plot(curve[:,0], curve[:,1], c='black')\n >>> ax = scprep.plot.scatter2d(data_phate, c=slingshot['branch'],\n ... legend_title='Branch', ticks=False, label_prefix='PHATE')\n >>> for curve in slingshot['curves']:\n ... ax.plot(curve[:,0], curve[:,1], c='black')\n \"\"\"\n if seed is None:\n seed = np.random.randint(2**16 - 1)\n if distance is not None:\n raise NotImplementedError(\"distance argument not currently implemented\")\n np.random.seed(seed)\n\n index = data.index if isinstance(data, pd.DataFrame) else None\n\n data = utils.toarray(data)\n if data.shape[1] > 3:\n warnings.warn(\n \"Expected data to be low-dimensional. \"\n \"Got data.shape[1] = {}\".format(data.shape[1]),\n UserWarning,\n )\n cluster_labels = utils.toarray(cluster_labels).flatten()\n if not cluster_labels.shape[0] == data.shape[0]:\n raise ValueError(\n \"Expected len(cluster_labels) ({}) to equal \"\n \"data.shape[0] ({})\".format(cluster_labels.shape[0], data.shape[0])\n )\n\n if start_cluster is not None:\n kwargs[\"start_cluster\"] = start_cluster\n if end_cluster is not None:\n kwargs[\"end_cluster\"] = end_cluster\n if omega is not None:\n kwargs[\"omega\"] = omega\n\n slingshot = _Slingshot(\n data=data,\n cluster_labels=cluster_labels,\n shrink=shrink,\n extend=extend,\n reweight=reweight,\n reassign=reassign,\n thresh=thresh,\n max_iter=max_iter,\n stretch=stretch,\n smoother=smoother,\n shrink_method=shrink_method,\n allow_breaks=allow_breaks,\n **kwargs,\n seed=seed,\n rpy_verbose=verbose,\n )\n slingshot[\"curves\"] = np.array(list(slingshot[\"curves\"].values()))\n\n membership = (~np.isnan(slingshot[\"pseudotime\"])).astype(int)\n branch = np.sum(membership * (2 ** np.arange(membership.shape[1])), axis=1)\n # reorder based on pseudotime\n branch_ids = np.unique(branch)\n branch_means = [\n np.nanmean(slingshot[\"pseudotime\"][branch == id])\n if not np.all(np.isnan(slingshot[\"pseudotime\"][branch == id]))\n else np.nan\n for id in branch_ids\n ]\n branch_order = np.argsort(branch_means)\n branch_old = branch.copy()\n for i in range(len(branch_order)):\n j = branch_order[i]\n if np.isnan(branch_means[j]):\n branch[branch_old == branch_ids[j]] = -1\n else:\n branch[branch_old == branch_ids[j]] = i\n slingshot[\"branch\"] = branch\n\n if index is not None:\n slingshot[\"pseudotime\"] = pd.DataFrame(slingshot[\"pseudotime\"], index=index)\n slingshot[\"branch\"] = pd.Series(slingshot[\"branch\"], name=\"branch\", index=index)\n return slingshot\n"
] |
[
[
"pandas.Series",
"numpy.random.seed",
"numpy.unique",
"numpy.isnan",
"numpy.arange",
"pandas.DataFrame",
"numpy.nanmean",
"numpy.argsort",
"numpy.random.randint"
]
] |
Tanishadel/Mastering-Machine-Learning-for-Penetration-Testing
|
[
"5aecc2603faaa97dafc1fa4c86f4e5f530bb4877"
] |
[
"Chapter09/mnist_loader.py"
] |
[
"\"\"\"\nmnist_loader\n~~~~~~~~~~~~\n\nA library to load the MNIST image data. For details of the data\nstructures that are returned, see the doc strings for ``load_data``\nand ``load_data_wrapper``. In practice, ``load_data_wrapper`` is the\nfunction usually called by our neural network code.\n\"\"\"\n\n#### Libraries\n# Standard library\nimport cPickle\nimport gzip\n\n# Third-party libraries\nimport numpy as np\n\ndef load_data():\n \"\"\"Return the MNIST data as a tuple containing the training data,\n the validation data, and the test data.\n\n The ``training_data`` is returned as a tuple with two entries.\n The first entry contains the actual training images. This is a\n numpy ndarray with 50,000 entries. Each entry is, in turn, a\n numpy ndarray with 784 values, representing the 28 * 28 = 784\n pixels in a single MNIST image.\n\n The second entry in the ``training_data`` tuple is a numpy ndarray\n containing 50,000 entries. Those entries are just the digit\n values (0...9) for the corresponding images contained in the first\n entry of the tuple.\n\n The ``validation_data`` and ``test_data`` are similar, except\n each contains only 10,000 images.\n\n This is a nice data format, but for use in neural networks it's\n helpful to modify the format of the ``training_data`` a little.\n That's done in the wrapper function ``load_data_wrapper()``, see\n below.\n \"\"\"\n f = gzip.open('data/mnist.pkl.gz', 'rb')\n training_data, validation_data, test_data = cPickle.load(f)\n f.close()\n return (training_data, validation_data, test_data)\n\ndef load_data_wrapper():\n \"\"\"Return a tuple containing ``(training_data, validation_data,\n test_data)``. Based on ``load_data``, but the format is more\n convenient for use in our implementation of neural networks.\n\n In particular, ``training_data`` is a list containing 50,000\n 2-tuples ``(x, y)``. ``x`` is a 784-dimensional numpy.ndarray\n containing the input image. ``y`` is a 10-dimensional\n numpy.ndarray representing the unit vector corresponding to the\n correct digit for ``x``.\n\n ``validation_data`` and ``test_data`` are lists containing 10,000\n 2-tuples ``(x, y)``. In each case, ``x`` is a 784-dimensional\n numpy.ndarry containing the input image, and ``y`` is the\n corresponding classification, i.e., the digit values (integers)\n corresponding to ``x``.\n\n Obviously, this means we're using slightly different formats for\n the training data and the validation / test data. These formats\n turn out to be the most convenient for use in our neural network\n code.\"\"\"\n tr_d, va_d, te_d = load_data()\n training_inputs = [np.reshape(x, (784, 1)) for x in tr_d[0]]\n training_results = [vectorized_result(y) for y in tr_d[1]]\n training_data = zip(training_inputs, training_results)\n validation_inputs = [np.reshape(x, (784, 1)) for x in va_d[0]]\n validation_data = zip(validation_inputs, va_d[1])\n test_inputs = [np.reshape(x, (784, 1)) for x in te_d[0]]\n test_data = zip(test_inputs, te_d[1])\n return (training_data, validation_data, test_data)\n\ndef vectorized_result(j):\n \"\"\"Return a 10-dimensional unit vector with a 1.0 in the jth\n position and zeroes elsewhere. This is used to convert a digit\n (0...9) into a corresponding desired output from the neural\n network.\"\"\"\n e = np.zeros((10, 1))\n e[j] = 1.0\n return e\n"
] |
[
[
"numpy.reshape",
"numpy.zeros"
]
] |
glasslucas00/Meter-google-project
|
[
"862e90747b7762e8c3ad107ad8d8c657829390aa"
] |
[
"nets/yolo4.py"
] |
[
"from functools import wraps\r\n\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom keras import backend as K\r\nfrom keras.layers import Conv2D, Add, ZeroPadding2D, UpSampling2D, Concatenate, MaxPooling2D\r\nfrom keras.layers.advanced_activations import LeakyReLU\r\nfrom keras.layers.normalization import BatchNormalization\r\nfrom keras.models import Model\r\nfrom keras.regularizers import l2\r\nfrom nets.CSPdarknet53 import darknet_body\r\nfrom utils.utils import compose\r\n\r\n\r\n#--------------------------------------------------#\r\n# 单次卷积\r\n#--------------------------------------------------#\r\n@wraps(Conv2D)\r\ndef DarknetConv2D(*args, **kwargs):\r\n darknet_conv_kwargs = {'kernel_regularizer': l2(5e-4)}\r\n darknet_conv_kwargs['padding'] = 'valid' if kwargs.get('strides')==(2,2) else 'same'\r\n darknet_conv_kwargs.update(kwargs)\r\n return Conv2D(*args, **darknet_conv_kwargs)\r\n\r\n#---------------------------------------------------#\r\n# 卷积块\r\n# DarknetConv2D + BatchNormalization + LeakyReLU\r\n#---------------------------------------------------#\r\ndef DarknetConv2D_BN_Leaky(*args, **kwargs):\r\n no_bias_kwargs = {'use_bias': False}\r\n no_bias_kwargs.update(kwargs)\r\n return compose(\r\n DarknetConv2D(*args, **no_bias_kwargs),\r\n BatchNormalization(),\r\n LeakyReLU(alpha=0.1))\r\n\r\n#---------------------------------------------------#\r\n# 特征层->最后的输出\r\n#---------------------------------------------------#\r\ndef make_five_convs(x, num_filters):\r\n # 五次卷积\r\n x = DarknetConv2D_BN_Leaky(num_filters, (1,1))(x)\r\n x = DarknetConv2D_BN_Leaky(num_filters*2, (3,3))(x)\r\n x = DarknetConv2D_BN_Leaky(num_filters, (1,1))(x)\r\n x = DarknetConv2D_BN_Leaky(num_filters*2, (3,3))(x)\r\n x = DarknetConv2D_BN_Leaky(num_filters, (1,1))(x)\r\n return x\r\n\r\n#---------------------------------------------------#\r\n# 特征层->最后的输出\r\n#---------------------------------------------------#\r\ndef yolo_body(inputs, num_anchors, num_classes):\r\n # 生成darknet53的主干模型\r\n feat1,feat2,feat3 = darknet_body(inputs)\r\n\r\n # 第一个特征层\r\n # y1=(batch_size,13,13,3,85)\r\n P5 = DarknetConv2D_BN_Leaky(512, (1,1))(feat3)\r\n P5 = DarknetConv2D_BN_Leaky(1024, (3,3))(P5)\r\n P5 = DarknetConv2D_BN_Leaky(512, (1,1))(P5)\r\n # 使用了SPP结构,即不同尺度的最大池化后堆叠。\r\n maxpool1 = MaxPooling2D(pool_size=(13,13), strides=(1,1), padding='same')(P5)\r\n maxpool2 = MaxPooling2D(pool_size=(9,9), strides=(1,1), padding='same')(P5)\r\n maxpool3 = MaxPooling2D(pool_size=(5,5), strides=(1,1), padding='same')(P5)\r\n P5 = Concatenate()([maxpool1, maxpool2, maxpool3, P5])\r\n P5 = DarknetConv2D_BN_Leaky(512, (1,1))(P5)\r\n P5 = DarknetConv2D_BN_Leaky(1024, (3,3))(P5)\r\n P5 = DarknetConv2D_BN_Leaky(512, (1,1))(P5)\r\n\r\n P5_upsample = compose(DarknetConv2D_BN_Leaky(256, (1,1)), UpSampling2D(2))(P5)\r\n\r\n P4 = DarknetConv2D_BN_Leaky(256, (1,1))(feat2)\r\n P4 = Concatenate()([P4, P5_upsample])\r\n P4 = make_five_convs(P4,256)\r\n\r\n P4_upsample = compose(DarknetConv2D_BN_Leaky(128, (1,1)), UpSampling2D(2))(P4)\r\n\r\n P3 = DarknetConv2D_BN_Leaky(128, (1,1))(feat1)\r\n P3 = Concatenate()([P3, P4_upsample])\r\n P3 = make_five_convs(P3,128)\r\n\r\n P3_output = DarknetConv2D_BN_Leaky(256, (3,3))(P3)\r\n P3_output = DarknetConv2D(num_anchors*(num_classes+5), (1,1))(P3_output)\r\n\r\n #26,26 output\r\n P3_downsample = ZeroPadding2D(((1,0),(1,0)))(P3)\r\n P3_downsample = DarknetConv2D_BN_Leaky(256, (3,3), strides=(2,2))(P3_downsample)\r\n P4 = Concatenate()([P3_downsample, P4])\r\n P4 = make_five_convs(P4,256)\r\n\r\n P4_output = DarknetConv2D_BN_Leaky(512, (3,3))(P4)\r\n P4_output = DarknetConv2D(num_anchors*(num_classes+5), (1,1))(P4_output)\r\n\r\n\r\n #13,13 output\r\n P4_downsample = ZeroPadding2D(((1,0),(1,0)))(P4)\r\n P4_downsample = DarknetConv2D_BN_Leaky(512, (3,3), strides=(2,2))(P4_downsample)\r\n P5 = Concatenate()([P4_downsample, P5])\r\n P5 = make_five_convs(P5,512)\r\n\r\n\r\n P5_output = DarknetConv2D_BN_Leaky(1024, (3,3))(P5)\r\n P5_output = DarknetConv2D(num_anchors*(num_classes+5), (1,1))(P5_output)\r\n\r\n return Model(inputs, [P5_output, P4_output, P3_output])\r\n\r\n#---------------------------------------------------#\r\n# 将预测值的每个特征层调成真实值\r\n#---------------------------------------------------#\r\ndef yolo_head(feats, anchors, num_classes, input_shape, calc_loss=False):\r\n num_anchors = len(anchors)\r\n # [1, 1, 1, num_anchors, 2]\r\n anchors_tensor = K.reshape(K.constant(anchors), [1, 1, 1, num_anchors, 2])\r\n\r\n # 获得x,y的网格\r\n # (13,13, 1, 2)\r\n grid_shape = K.shape(feats)[1:3] # height, width\r\n grid_y = K.tile(K.reshape(K.arange(0, stop=grid_shape[0]), [-1, 1, 1, 1]),\r\n [1, grid_shape[1], 1, 1])\r\n grid_x = K.tile(K.reshape(K.arange(0, stop=grid_shape[1]), [1, -1, 1, 1]),\r\n [grid_shape[0], 1, 1, 1])\r\n grid = K.concatenate([grid_x, grid_y])\r\n grid = K.cast(grid, K.dtype(feats))\r\n\r\n # (batch_size,13,13,3,85)\r\n feats = K.reshape(feats, [-1, grid_shape[0], grid_shape[1], num_anchors, num_classes + 5])\r\n\r\n # 将预测值调成真实值\r\n # box_xy对应框的中心点\r\n # box_wh对应框的宽和高\r\n box_xy = (K.sigmoid(feats[..., :2]) + grid) / K.cast(grid_shape[::-1], K.dtype(feats))\r\n box_wh = K.exp(feats[..., 2:4]) * anchors_tensor / K.cast(input_shape[::-1], K.dtype(feats))\r\n box_confidence = K.sigmoid(feats[..., 4:5])\r\n box_class_probs = K.sigmoid(feats[..., 5:])\r\n\r\n # 在计算loss的时候返回如下参数\r\n if calc_loss == True:\r\n return grid, feats, box_xy, box_wh\r\n return box_xy, box_wh, box_confidence, box_class_probs\r\n\r\n#---------------------------------------------------#\r\n# 对box进行调整,使其符合真实图片的样子\r\n#---------------------------------------------------#\r\ndef yolo_correct_boxes(box_xy, box_wh, input_shape, image_shape):\r\n box_yx = box_xy[..., ::-1]\r\n box_hw = box_wh[..., ::-1]\r\n\r\n input_shape = K.cast(input_shape, K.dtype(box_yx))\r\n image_shape = K.cast(image_shape, K.dtype(box_yx))\r\n\r\n new_shape = K.round(image_shape * K.min(input_shape/image_shape))\r\n offset = (input_shape-new_shape)/2./input_shape\r\n scale = input_shape/new_shape\r\n\r\n box_yx = (box_yx - offset) * scale\r\n box_hw *= scale\r\n\r\n box_mins = box_yx - (box_hw / 2.)\r\n box_maxes = box_yx + (box_hw / 2.)\r\n boxes = K.concatenate([\r\n box_mins[..., 0:1], # y_min\r\n box_mins[..., 1:2], # x_min\r\n box_maxes[..., 0:1], # y_max\r\n box_maxes[..., 1:2] # x_max\r\n ])\r\n\r\n boxes *= K.concatenate([image_shape, image_shape])\r\n return boxes\r\n\r\n#---------------------------------------------------#\r\n# 获取每个box和它的得分\r\n#---------------------------------------------------#\r\ndef yolo_boxes_and_scores(feats, anchors, num_classes, input_shape, image_shape):\r\n # 将预测值调成真实值\r\n # box_xy对应框的中心点\r\n # box_wh对应框的宽和高\r\n # -1,13,13,3,2; -1,13,13,3,2; -1,13,13,3,1; -1,13,13,3,80\r\n box_xy, box_wh, box_confidence, box_class_probs = yolo_head(feats, anchors, num_classes, input_shape)\r\n # 将box_xy、和box_wh调节成y_min,y_max,xmin,xmax\r\n boxes = yolo_correct_boxes(box_xy, box_wh, input_shape, image_shape)\r\n # 获得得分和box\r\n boxes = K.reshape(boxes, [-1, 4])\r\n box_scores = box_confidence * box_class_probs\r\n box_scores = K.reshape(box_scores, [-1, num_classes])\r\n return boxes, box_scores\r\n\r\n#---------------------------------------------------#\r\n# 图片预测\r\n#---------------------------------------------------#\r\ndef yolo_eval(yolo_outputs,\r\n anchors,\r\n num_classes,\r\n image_shape,\r\n max_boxes=20,\r\n score_threshold=.6,\r\n iou_threshold=.5):\r\n # 获得特征层的数量\r\n num_layers = len(yolo_outputs)\r\n # 特征层1对应的anchor是678\r\n # 特征层2对应的anchor是345\r\n # 特征层3对应的anchor是012\r\n anchor_mask = [[6,7,8], [3,4,5], [0,1,2]]\r\n\r\n input_shape = K.shape(yolo_outputs[0])[1:3] * 32\r\n boxes = []\r\n box_scores = []\r\n # 对每个特征层进行处理\r\n for l in range(num_layers):\r\n _boxes, _box_scores = yolo_boxes_and_scores(yolo_outputs[l], anchors[anchor_mask[l]], num_classes, input_shape, image_shape)\r\n boxes.append(_boxes)\r\n box_scores.append(_box_scores)\r\n # 将每个特征层的结果进行堆叠\r\n boxes = K.concatenate(boxes, axis=0)\r\n box_scores = K.concatenate(box_scores, axis=0)\r\n\r\n mask = box_scores >= score_threshold\r\n max_boxes_tensor = K.constant(max_boxes, dtype='int32')\r\n boxes_ = []\r\n scores_ = []\r\n classes_ = []\r\n for c in range(num_classes):\r\n # 取出所有box_scores >= score_threshold的框,和成绩\r\n class_boxes = tf.boolean_mask(boxes, mask[:, c])\r\n class_box_scores = tf.boolean_mask(box_scores[:, c], mask[:, c])\r\n\r\n # 非极大抑制,去掉box重合程度高的那一些\r\n nms_index = tf.image.non_max_suppression(\r\n class_boxes, class_box_scores, max_boxes_tensor, iou_threshold=iou_threshold)\r\n\r\n # 获取非极大抑制后的结果\r\n # 下列三个分别是\r\n # 框的位置,得分与种类\r\n class_boxes = K.gather(class_boxes, nms_index)\r\n class_box_scores = K.gather(class_box_scores, nms_index)\r\n classes = K.ones_like(class_box_scores, 'int32') * c\r\n boxes_.append(class_boxes)\r\n scores_.append(class_box_scores)\r\n classes_.append(classes)\r\n boxes_ = K.concatenate(boxes_, axis=0)\r\n scores_ = K.concatenate(scores_, axis=0)\r\n classes_ = K.concatenate(classes_, axis=0)\r\n\r\n return boxes_, scores_, classes_\r\n\r\n\r\n"
] |
[
[
"tensorflow.boolean_mask",
"tensorflow.image.non_max_suppression"
]
] |
yanqiangmiffy/Text-Classification-Application
|
[
"c9608f5857991ae4701c7d82bcac537b7961691f"
] |
[
"train_model_english_.py"
] |
[
"from keras.layers import Input,Dense,Embedding,Conv2D,MaxPool2D\nfrom keras.layers import Reshape,Flatten,Dropout,Concatenate\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.optimizers import Adam\nfrom keras.models import Model\nfrom sklearn.model_selection import train_test_split\nfrom data_helpers_english import load_data\n\nprint(\"正在加载数据....\")\nx,y,vocabulary,vocabulary_inv=load_data()\n\n# x.shape -> (10662, 56)\n# y.shape -> (10662, 2)\n# len(vocabulary) -> 12766\n# len(vocabulary_inv) -> 12766\n\n# 划分数据集\nX_train,X_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=42)\n\n# X_train.shape -> (8529, 56)\n# y_train.shape -> (8529, 2)\n# X_test.shape -> (2133, 56)\n# y_test.shape -> (2133, 2)\n\n\nsequence_length=X_train.shape[1]\nvocabulary_size=len(vocabulary_inv)\nembedding_dim=256\nfilter_sizes=[3,4,5]\nnum_filters=512\ndrop=0.5\n\nepochs=100\nbatch_size=30\n\n# 创建tensor\nprint(\"正在创建模型...\")\ninputs=Input(shape=(sequence_length,),dtype='int32')\nembedding=Embedding(input_dim=vocabulary_size,output_dim=embedding_dim,input_length=sequence_length)(inputs)\nreshape=Reshape((sequence_length,embedding_dim,1))(embedding)\n\n# cnn\nconv_0=Conv2D(num_filters,kernel_size=(filter_sizes[0],embedding_dim),padding='valid',kernel_initializer='normal',activation='relu')(reshape)\nconv_1=Conv2D(num_filters,kernel_size=(filter_sizes[1],embedding_dim),padding='valid',kernel_initializer='normal',activation='relu')(reshape)\nconv_2=Conv2D(num_filters,kernel_size=(filter_sizes[2],embedding_dim),padding='valid',kernel_initializer='normal',activation='relu')(reshape)\n\nmaxpool_0=MaxPool2D(pool_size=(sequence_length-filter_sizes[0]+1,1),strides=(1,1),padding='valid')(conv_0)\nmaxpool_1=MaxPool2D(pool_size=(sequence_length-filter_sizes[1]+1,1),strides=(1,1),padding='valid')(conv_1)\nmaxpool_2=MaxPool2D(pool_size=(sequence_length-filter_sizes[2]+1,1),strides=(1,1),padding='valid')(conv_2)\n\n\nconcatenated_tensor = Concatenate(axis=1)([maxpool_0, maxpool_1, maxpool_2])\nflatten = Flatten()(concatenated_tensor)\ndropout = Dropout(drop)(flatten)\noutput = Dense(units=2, activation='softmax')(dropout)\nmodel=Model(inputs=inputs,outputs=output)\n\n\ncheckpoint = ModelCheckpoint('results/english.weights.{epoch:03d}-{val_acc:.4f}.hdf5', monitor='val_acc', verbose=1, save_best_only=True, mode='auto')\nadam = Adam(lr=1e-4, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\n\nmodel.compile(optimizer=adam, loss='binary_crossentropy', metrics=['accuracy'])\nprint(\"Traning Model...\")\nmodel.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, callbacks=[checkpoint], validation_data=(X_test, y_test)) # starts training\n\n"
] |
[
[
"sklearn.model_selection.train_test_split"
]
] |
jinga-lala/stupidNMT
|
[
"2a41c072c2bc622c7edd8556f552f38556d70dae"
] |
[
"models/new_encoder.py"
] |
[
"'''\nA module which implements the new Encoder\n'''\nimport uuid\nimport threading\nimport pdb\nimport torch\nfrom torch import nn\n\nfrom models.new_attention import NewAttention\nfrom models.attention import MultiHeadedAttention\nfrom models.embeddings import PositionEmbedding, TokenEmbedding\nfrom models.utils import LabelSmoothingLoss, Translator\nfrom utils import left_shift, right_shift, triu\n\n\nclass TransformerSublayer(nn.Module):\n '''\n Implements a sub layer of the transformer model, which consists of:\n 1) A sub layer module\n 2) Followed by dropout\n 3) Plus a residual connection\n 4) With layer normalization\n '''\n def __init__(self, sublayer, sublayer_shape, dropout_p=0.1):\n ''' Initialize the transformer sublayer '''\n super(TransformerSublayer, self).__init__()\n\n self.sublayer = sublayer\n self.norm = nn.LayerNorm(sublayer_shape)\n self.dropout = nn.Dropout(dropout_p, inplace=True)\n self.reset_parameters()\n\n def reset_parameters(self):\n ''' Reset parameters using xavier initialiation '''\n self.norm.reset_parameters()\n\n def forward(self, inputs, *sublayer_args, **sublayer_kwargs): # pylint:disable=arguments-differ\n ''' The forward pass of the sublayer '''\n return self.norm(inputs + self.dropout(self.sublayer(*sublayer_args, **sublayer_kwargs)))\n\n\nclass TransformerFFN(nn.Module):\n ''' Implements the Transformer feed-forward network '''\n def __init__(self, embedding_size, hidden_dim):\n super(TransformerFFN, self).__init__()\n\n self.relu = nn.ReLU()\n\n self.hidden = nn.Linear(embedding_size, hidden_dim)\n self.output = nn.Linear(hidden_dim, embedding_size)\n self.reset_parameters()\n\n def reset_parameters(self):\n ''' Reset parameters using xavier initialiation '''\n gain = nn.init.calculate_gain('relu')\n nn.init.xavier_uniform_(self.hidden.weight, gain)\n nn.init.constant_(self.hidden.bias, 0.)\n\n gain = nn.init.calculate_gain('linear')\n nn.init.xavier_uniform_(self.output.weight, gain)\n nn.init.constant_(self.output.bias, 0.)\n\n def forward(self, inputs): # pylint:disable=arguments-differ\n ''' The forward pass of the feed-forward network '''\n return self.output(self.relu(self.hidden(inputs)))\n\n\nclass TransformerEncoderLayer(nn.Module):\n ''' Implements a single encoder layer in a transformer encoder stack '''\n def __init__(self, attn_config, num_heads, dim, hidden_dim, layer_i, dropout_p=0.1):\n ''' Initialize the transformer layer '''\n super(TransformerEncoderLayer, self).__init__()\n\n if attn_config['ffn_layer'][layer_i]:\n self.ffn = TransformerSublayer(\n TransformerFFN(dim, hidden_dim),\n dim, dropout_p\n )\n print('enc layer %i has ffn' % layer_i)\n\n self.self_attention = TransformerSublayer(\n NewAttention(attn_config, dim, num_heads),\n dim, dropout_p\n )\n\n def reset_parameters(self):\n ''' Reset the parameters of the module '''\n self.ffn.reset_parameters()\n self.self_attention.reset_parameters()\n\n def forward(self, inputs, layer_i): # pylint:disable=arguments-differ\n ''' The forward pass '''\n mask = inputs['mask']\n state = inputs['state']\n\n # print(\"encoder self attention\")\n\n state = self.self_attention(\n state, # residual\n state, state, state, mask, # passed to multiheaded attention\n layer_i=layer_i\n )\n\n if hasattr(self, 'ffn'):\n state = self.ffn(\n state, # residual\n state # passed to feed-forward network\n )\n\n return {'state': state, 'mask': mask}\n\n\nclass TransformerDecoderLayer(nn.Module):\n ''' Implements a single decoder layer in a transformer decoder stack '''\n def __init__(self, dec_attn_config, enc_dec_attn_config, num_heads, dim, hidden_dim, layer_i, causal=True,\n dropout_p=0.1):\n ''' Initialize the transformer layer '''\n super(TransformerDecoderLayer, self).__init__()\n\n self.causal = causal\n self.uuid = uuid.uuid4()\n\n self.enc_dec_attn_config = enc_dec_attn_config\n\n if dec_attn_config['ffn_layer'][layer_i]:\n self.ffn = TransformerSublayer(\n TransformerFFN(dim, hidden_dim),\n dim, dropout_p\n )\n print('dec layer %i has ffn' % layer_i)\n\n self.self_attention = TransformerSublayer(\n NewAttention(dec_attn_config, dim, num_heads),\n dim, dropout_p\n )\n\n if self.enc_dec_attn_config['enc_dec_attn_layer'] == 1 or \\\n (type(self.enc_dec_attn_config['enc_dec_attn_layer'] is list) and\n self.enc_dec_attn_config['enc_dec_attn_layer'][layer_i] == 1):\n if self.enc_dec_attn_config['enc_dec_attn_num_heads'] == -1:\n src_num_heads = num_heads\n elif type(self.enc_dec_attn_config['enc_dec_attn_num_heads']) is not list:\n src_num_heads = self.enc_dec_attn_config['enc_dec_attn_num_heads']\n else:\n src_num_heads = self.enc_dec_attn_config['enc_dec_attn_num_heads'][layer_i]\n assert src_num_heads != 0\n\n self.source_attention = TransformerSublayer(\n NewAttention(enc_dec_attn_config, dim, src_num_heads),\n dim, dropout_p\n )\n\n print('layer %i num of src heads %i' % (layer_i, src_num_heads))\n\n def reset_parameters(self):\n ''' Reset the parameters of the module '''\n self.ffn.reset_parameters()\n self.self_attention.reset_parameters()\n if hasattr(self, 'source_attention'):\n self.source_attention.reset_parameters()\n\n def forward(self, inputs, sources, layer_i): # pylint:disable=arguments-differ\n ''' The forward pass '''\n mask = inputs['mask']\n state = inputs['state']\n cache = inputs.get('cache')\n\n decoder_position = state.shape[1] - 1\n\n kwargs = {'layer_i': layer_i}\n if self.causal and cache is not None:\n # If caching, only want the last one sequence values. Requires no causal masking.\n residual = state[:, -1:]\n kwargs['decoder_position'] = decoder_position\n else:\n # If not caching, use the full sequence and ensure an appropriate causal mask\n residual = state\n kwargs['key_mask'] = mask\n kwargs['attention_mask'] = self.mask(state)\n\n # print(\"decoder self attention\")\n state = self.self_attention(\n residual, # residual\n state, state, state, **kwargs # passed to multiheaded attention\n )\n\n source = sources['state']\n # print(\"source\", source)\n kwargs = {'key_mask': sources['mask'], 'layer_i': layer_i}\n if self.causal and cache is not None:\n kwargs['decoder_position'] = decoder_position\n\n # print(\"decoder source attention\")\n\n if hasattr(self, 'source_attention'):\n # print(\"in source, state\", state.shape)\n state = self.source_attention(\n state, # residual\n source, source, state, **kwargs # passed to multiheaded attention\n )\n\n if hasattr(self, 'ffn'):\n state = self.ffn(\n state, # residual\n state # passed to feed-forward network\n )\n\n if self.causal and cache is not None:\n cached = cache.get(self.uuid)\n if cached is None:\n cache[self.uuid] = state\n else:\n # print(\"cached\", cached.shape)\n # print(\"state\", state.shape)\n try:\n state = cache[self.uuid] = torch.cat((cached, state), 1)\n except:\n pdb.set_trace()\n\n return {'state': state, 'mask': mask, 'cache': cache}\n\n _masks = threading.local()\n def mask(self, inputs):\n '''\n Get a self-attention mask\n The mask will be of shape [T x T] containing elements from the set {0, -inf}\n Input shape: (B x T x E)\n Output shape: (T x T)\n '''\n if not self.causal:\n return None\n\n dim = inputs.shape[1]\n device = inputs.device\n mask_store = TransformerDecoderLayer._masks.__dict__\n if device not in mask_store:\n mask = inputs.new_full((dim, dim), float('-inf'))\n mask_store[device] = triu(mask, 1, 1, 1)\n\n mask = mask_store[device]\n if mask.shape[0] < dim:\n mask = mask.resize_(dim, dim).fill_(float('-inf'))\n mask_store[device] = triu(mask, 1, 1, 1)\n mask = mask_store[device]\n\n return mask[None, :dim, :dim]\n\n\nclass NewTransformer(nn.Module):\n ''' The New Transformer module '''\n def __init__(self, config, dataset):\n ''' Initialize the Transformer '''\n super(NewTransformer, self).__init__()\n\n self.dataset = dataset\n self.embedding = TokenEmbedding(\n dataset.vocab_size,\n config.embedding_size,\n padding_idx=self.padding_idx\n )\n self.position_embedding = PositionEmbedding(config.embedding_size)\n self.dropout = nn.Dropout(config.dropout_p, inplace=True)\n\n # Uniq attn attributes\n self.attn_ofs_uniq = list(set(\n config.enc_attn_offset + config.dec_attn_offset + config.enc_dec_attn_offset))\n self.attn_std_uniq = list(set(\n config.enc_attn_std + config.dec_attn_std + config.enc_dec_attn_std))\n\n # Allow for overriding the encoders and decoders in dervied classes\n self.encoders = self.create_encoders(config)\n # self.decoders = self.create_decoders(config)\n\n self.label_smoothing = LabelSmoothingLoss(\n config.label_smoothing or 0,\n ignore_index=self.padding_idx,\n reduction='none'\n )\n self.cross_entropy = nn.CrossEntropyLoss(\n ignore_index=self.padding_idx,\n reduction='none'\n )\n\n def create_encoders(self, config):\n ''' Create the transformer encoders '''\n kwargs = {'dropout_p': config.dropout_p}\n\n if config.ffn_layer == -1:\n config.ffn_layer = [1] * config.num_layers\n assert len(config.ffn_layer) == config.num_layers\n\n attn_config = {'attn_type': config.enc_attn_type,\n 'attn_std': config.enc_attn_std,\n 'attn_offset': config.enc_attn_offset,\n 'num_layers': config.num_layers,\n 'num_heads': config.num_heads,\n 'which_attn': 'encoder',\n 'attn_threshold': config.enc_attn_threshold,\n 'attn_window': config.enc_attn_window,\n 'attn_impl': config.enc_attn_impl,\n 'ffn_layer': config.ffn_layer,\n 'attn_ofs_uniq': self.attn_ofs_uniq,\n 'attn_std_uniq': self.attn_std_uniq}\n args = [attn_config, config.num_heads, config.embedding_size, config.hidden_dim]\n encoders = nn.ModuleList([\n TransformerEncoderLayer(*args, layer_i, **kwargs)\n for layer_i in range(config.num_layers)\n ])\n\n return encoders\n\n\n @property\n def sos_idx(self):\n ''' Return the sos index '''\n return self.dataset.sos_idx\n\n @property\n def padding_idx(self):\n ''' Return the padding index '''\n return self.dataset.padding_idx\n\n def translator(self, config):\n ''' Get a translator for this model '''\n return Translator(config, self, self.dataset)\n\n def reset_named_parameters(self, modules):\n ''' Get a translator for this model '''\n if 'encoder' in modules:\n for encoder in self.encoders:\n encoder.reset_parameters()\n if 'decoder' in modules:\n # for decoder in self.decoders:\n # decoder.reset_parameters()\n print(\"Decoder should not be here!!\")\n exit(0)\n if 'embeddings' in modules:\n self.embedding.reset_parameters()\n\n def forward(self, batch): # pylint:disable=arguments-differ\n ''' A batch of inputs and targets '''\n\n logits = self.encode(batch['inputs'])['state']\n print(logits)\n print(logits.shape)\n print(logits.dim())\n dims = list(range(1, logits.dim()))\n targets = (batch['targets'])\n nll = self.cross_entropy(logits, targets).sum(dims[:-1])\n smoothed_nll = self.label_smoothing(logits, targets).sum(dims)\n return smoothed_nll, nll\n\n def encode(self, inputs):\n ''' Encode the inputs '''\n word_embedding = self.embed(inputs, self.embedding)\n encoded = {\n 'state': word_embedding,\n 'mask': inputs.eq(self.padding_idx)\n }\n for i, encoder in enumerate(self.encoders):\n encoded = encoder(encoded, i)\n\n return encoded\n\n def decode(self, encoded, targets, decoders=None, embedding=None, cache=None, mask=None, input_lens=None):\n ''' Decode the encoded sequence to the targets '''\n if decoders is None:\n decoders = self.decoders\n\n if embedding is None:\n embedding = self.embedding\n\n word_embedding = self.embed(targets, embedding)\n\n decoded = {\n 'cache': cache,\n 'state': word_embedding,\n 'mask': targets.eq(self.padding_idx) if mask is None else mask\n }\n for i, decoder in enumerate(decoders):\n # print(\"i\", i)\n decoded = decoder(decoded, encoded, i)\n\n # compute projection to the vocabulary\n state = decoded['state']\n if cache is not None:\n state = state[:, -1:]\n\n return {\n 'cache': decoded.get('cache'),\n 'logits': embedding(state, transpose=True).transpose(2, 1), # transpose to B x C x ...\n }\n\n def embed(self, inputs, token_embedding):\n ''' Embed the given inputs '''\n return self.dropout(token_embedding(inputs) + self.position_embedding(inputs))\n"
] |
[
[
"torch.nn.init.calculate_gain",
"torch.nn.Dropout",
"torch.nn.CrossEntropyLoss",
"torch.cat",
"torch.nn.init.constant_",
"torch.nn.LayerNorm",
"torch.nn.Linear",
"torch.nn.init.xavier_uniform_",
"torch.nn.ReLU"
]
] |
nsriniva/Spotifinder
|
[
"1522290231b73966070975a966f141d28e006583"
] |
[
"app/data_model/find_songs.py"
] |
[
"'''\nContains the implementation of the FindSongs class.\n'''\nfrom re import compile as rcompile\nfrom zipfile import ZipFile\nfrom os.path import dirname\nfrom importlib import import_module\nimport pandas as pd\nfrom joblib import load\n\nload_model = None\nNearestNeighbors = None\n\ndef import_from_sk_tf():\n global load_model, NearestNeighbors\n\n if load_model is None:\n load_model = import_module('tensorflow.keras.models').load_model\n NearestNeighbors = import_module('sklearn.neighbors').NearestNeighbors\n\nDIR = dirname(__file__)\n\nrex = rcompile('[^a-zA-Z 0-9]')\n\ntokenize = lambda x: rex.sub('', x.lower().replace(',', ' ').replace('-', ' '))\n\nMODELS_DIR = DIR + '/../../models/'\nDATA_DIR = DIR + '/../../data/'\n\nENCODER = 'encoder.h5'\nFG_ENCODER = 'fg_encoder.h5'\n\nENCODER_PATH = MODELS_DIR + ENCODER + '.zip'\nENCODED_DTM = MODELS_DIR + 'encoded_dtm.pkl'\nTFIDF = MODELS_DIR + 'tfidf.pkl'\n\nFG_ENCODER_PATH = MODELS_DIR + FG_ENCODER\nFG_ENCODED_DF = MODELS_DIR + 'fg_encoded_df.pkl'\nGENRES_TFIDF = MODELS_DIR + 'genres_tfidf.pkl'\nSCALER = MODELS_DIR + 'scaler.pkl'\n\n\nTRACKS = DATA_DIR + 'tracks_genres_lyrics_en.csv.zip'\n\ndef getBestChoice(sugg_str, df):\n\n # Convert sugg_str to a set of tokens\n sugg_set = set(tokenize(sugg_str).split())\n \n # Get the list of index values for the dataframe\n choice = df.index.tolist()\n \n \n # Given index value of a song entry row, returns a set of\n # tokens from the combined name and artists columns.\n # The array syntax ['name'] is used in place of the dot\n # syntax .name because .name returns the value from the index\n # column\n name_artists = lambda x: set(tokenize(df.loc[x]['name']+' '+\n df.loc[x].artists).split())\n \n # Given a set of tokens, it returns the length of its\n # intersection with the sugg_set\n # This is used as a measure how similar the input is to the\n # sugg_set - the larger the return value, the greater the\n # similarity\n score_func = lambda x: len(sugg_set.intersection(x))\n \n choices = [(y, name_artists(y)) for y in choice]\n best_idx = 0\n best_score = score_func(choices[0][1])\n for idx, nm_art in enumerate(choices[1:]):\n score = score_func(nm_art[1])\n #print(f'{nm_art[1]}/{choices[best_idx][1]}/{sugg_set}::{score}/{best_score}')\n if score > best_score:\n best_score = score\n best_idx = idx+1\n \n choice = choices[best_idx][0]\n #print(choice, best_idx, choices, choices[best_idx])\n return choice\n\n\nclass FindSongEntries():\n\n def __init__(self):\n super().__init__()\n\n import_from_sk_tf()\n # Extract encoder.h5 from encoder.h5.zip\n with ZipFile(ENCODER_PATH, 'r') as zipObj:\n zipObj.extractall()\n \n # Load the model saved in ../../models/encoder.h5\n self.encoder = load_model(ENCODER)\n # Load the TfIDF vectorizer saved in tfidf.pkl\n self.tfidf = load(TFIDF)\n # Load the encoded DTM saved in encoded_dtm.pkl\n encoded_dtm = load(ENCODED_DTM)\n # Fit NearestNeighbors on encoded DTM\n self.nn = NearestNeighbors(n_neighbors=10, algorithm='ball_tree')\n self.nn.fit(encoded_dtm)\n del encoded_dtm\n\n def find_matching_songs(self, sugg_str):\n '''\n Given sugg_str(a string containing part/whole of the\n song's name and/or artist) returns a dataframe of\n song entries that are the closest matches.\n '''\n\n # Vectorize the sugg_str by running it through tfidf\n vec = self.tfidf.transform([tokenize(sugg_str)]).todense()\n # Reduce dimensionality by running through encoder\n encoded_vec = self.encoder.predict(vec)\n del vec\n # Get list of indices of entries that are closest to sugg_str\n entries = self.nn.kneighbors(encoded_vec)[1][0].tolist()\n del encoded_vec\n return entries\n\nclass FindSongRecommendations():\n\n def __init__(self):\n super().__init__()\n\n import_from_sk_tf()\n\n # Numerical features associated with a song entry\n self.features = [\n 'popularity', 'duration_ms', 'explicit', 'danceability',\n 'energy', 'key', 'loudness', 'mode', 'speechiness',\n 'acousticness', 'instrumentalness', 'liveness', 'valence',\n 'tempo', 'time_signature'\n ]\n # Load the model saved in fg_encoder.h5\n self.fg_encoder = load_model(FG_ENCODER_PATH)\n # Load the TfIDF vectorizer for genres data saved in genres_tfidf.pkl\n self.genres_tfidf = load(GENRES_TFIDF)\n # The original DF is DTM generated by genres_tfidf from genres data\n # in the dataset + Numerical features\n # Load the encoded DF from fg_encoded_df.pkl\n fg_encoded_df = load(FG_ENCODED_DF)\n # Load the StandardScaler saved at scaler.pkl\n self.scaler = load(SCALER)\n\n # Fit NearestNeighbors on encoded DF\n self.fg_nn = NearestNeighbors(n_neighbors=10, algorithm='ball_tree')\n self.fg_nn.fit(fg_encoded_df)\n del fg_encoded_df\n\n\n def get_recommended_songs_json(self, xj):\n '''\n Given a song entry x, returns a dataframe of similar songs.\n\n The similarity is determined based on the numerical \n features(detailed in self.features) along with genres feature.\n '''\n x = pd.read_json(xj, typ='Series')\n del xj\n # Convert the genres feature to a vector\n gvec = self.genres_tfidf.transform([tokenize(x.genres)]).todense()\n # Standardize the numerical features\n fvec = self.scaler.transform([x[self.features]])\n del x\n # Combine bot vectors to create a single features vector\n vec = [fvec.tolist()[0] + gvec.tolist()[0]]\n del fvec\n del gvec\n # Perform dimensionality reduction by running through fg_encoder\n encoded_vec = self.fg_encoder.predict(vec)\n del vec[:]\n del vec\n # Get the list of indices of entries that are closest to\n # the input entry\n entries = self.fg_nn.kneighbors(encoded_vec)[1][0].tolist()\n del encoded_vec\n # Return a dataframe containing the sorted list of entries.\n return entries\n\n def get_recommended_songs(self, x):\n '''\n Given a song entry x, returns a dataframe of similar songs.\n\n The similarity is determined based on the numerical \n features(detailed in self.features) along with genres feature.\n '''\n\n xj = x.to_json()\n \n return self.get_recommended_songs_json(xj)\n\nclass FindSongData():\n\n def __init__(self):\n super().__init__()\n # Load tracks_df from zipped csv file tracks_genres_lyrics_en.csv.zip\n self.tracks_df = pd.read_csv(TRACKS)\n\n # Get rid of superfluous columns and rows\n self.tracks_df.drop(columns=['Unnamed: 0'], inplace=True)\n\n \n def get_df_entry(self, idx):\n return self.tracks_df.loc[idx]\n\n def get_song_entries_data(self, entries, sorted=False):\n # Get the list of indices of closest matches sorted in descending\n # order of popularity i.e. the first entry will have the highest\n # popularity value\n if sorted:\n entries = self.tracks_df.iloc[entries].popularity.\\\n sort_values(ascending=False).index.tolist()\n\n # Return a dataframe containing the sorted selection of entries\n return self.tracks_df.loc[entries]\n\n # Return a dataframe containing the selected entries\n return self.tracks_df.iloc[entries]\n\n \n\nclass FindSongs(FindSongData, FindSongEntries, FindSongRecommendations):\n '''\n This class implements 3 methods:\n (1) find_song_entries - Given a song suggestion string containing \n partial/whole song name\n and/or artist, returns a dataframe of possible matches\n (2) find_song_entry - Given a song suggestion string returns either \n a dataframe of possible matches(if the best_choice kw argument is \n False) or a single entry(if the best_choice argumen is True - this \n is the default value)\n (3) get_recommendations - Given a song entry returns a dataframe of \n songs that are similar.\n '''\n def __init__(self):\n super().__init__()\n\n\n\n def find_song_entries(self, sugg_str):\n\n entries = self.find_matching_songs(sugg_str)\n return self.get_song_entries_data(entries, sorted=True)\n \n \n \n \n def find_song_entry(self, sugg_str, df=None, best_choice=True):\n '''\n Given sugg_str(a string containing part/whole of the\n song's name and/or artist) returns either a dataframe of\n song entries that are the closest matches(best_choice=False)\n or a single song entry(best_choice=True)\n '''\n\n\n # Get dataframe of song entries that are closest match\n # to sugg_str which is a string containing part/whole\n # of the song's name and/or artist.\n if df is None:\n df = self.find_song_entries(sugg_str)\n \n if best_choice:\n choice = getBestChoice(sugg_str, df)\n return self.get_df_entry(choice)\n\n return df\n\n def get_recommendations(self, x):\n '''\n Given a song entry x, returns a dataframe of similar songs. \n '''\n \n entries = self.get_recommended_songs(x)\n\n return self.get_song_entries_data(entries)\n \n"
] |
[
[
"pandas.read_csv",
"pandas.read_json"
]
] |
erickRochaIP/SuperNimLearner
|
[
"896acb00b1b30b36cb7aa924852e1a43020c6e48"
] |
[
"play.py"
] |
[
"import nim\nimport sys\nimport numpy as np\n\ndef main():\n\n\t# Check command-line arguments\n\tif len(sys.argv) != 2:\n\t\tsys.exit(\"Usage: python play.py filename.npy\")\n\n\tai = nim.NimAI()\n\tai.q = np.load(sys.argv[1], allow_pickle=\"True\").item()\n\n\tnim.play(ai)\n\nif __name__ == \"__main__\":\n\tmain()\n"
] |
[
[
"numpy.load"
]
] |
CG2016/barkovsky_3
|
[
"784bb3e419736cd11b9bc84b3055b8a4b9ec57e6"
] |
[
"lab3/color_stats.py"
] |
[
"#!/usr/bin/env python\nimport argparse\nimport statistics\nimport tkinter as tk\n\nimport numpy\nimport matplotlib\nmatplotlib.use(\"TkAgg\")\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\nfrom matplotlib.figure import Figure\nimport PIL.ImageTk\nimport PIL.Image\n\n\nIMAGE_SIZE = (600, 400)\n\n\nclass ColorStatsWindow:\n def __init__(self, image_path):\n self.root = tk.Tk()\n\n self.image = PIL.Image.open(image_path).convert('RGB')\n\n self.label_original = tk.Label(self.root)\n self.label_original.grid(row=0, column=0)\n self.set_original_image(self.image)\n\n red_counts, green_counts, blue_counts = self.get_color_stats()\n red_mean = statistics.mean(self.get_values_from_counts(red_counts))\n green_mean = statistics.mean(self.get_values_from_counts(green_counts))\n blue_mean = statistics.mean(self.get_values_from_counts(blue_counts))\n print('red mean: %.2f' % red_mean)\n print('green mean: %.2f' % green_mean)\n print('blue mean: %.2f' % blue_mean)\n\n red_figure = self.draw_figure(red_counts, red_mean, 'r')\n green_figure = self.draw_figure(green_counts, green_mean, 'g')\n blue_figure = self.draw_figure(blue_counts, blue_mean, 'b')\n\n red_canvas = self.get_tk_canvas(red_figure)\n green_canvas = self.get_tk_canvas(green_figure)\n blue_canvas = self.get_tk_canvas(blue_figure)\n\n red_canvas.grid(row=0, column=1)\n green_canvas.grid(row=1, column=0)\n blue_canvas.grid(row=1, column=1)\n\n def set_original_image(self, image):\n scaled_image = image.copy()\n scaled_image.thumbnail(IMAGE_SIZE)\n\n self._scaled_tk_image = PIL.ImageTk.PhotoImage(scaled_image)\n self.label_original.config(image=self._scaled_tk_image)\n\n def get_tk_canvas(self, figure):\n canvas = FigureCanvasTkAgg(figure, self.root)\n canvas.show()\n return canvas.get_tk_widget()\n\n def draw_figure(self, counts, mean, plot_color):\n figure = Figure(figsize=(8, 5.3333333), dpi=75)\n plot = figure.add_subplot(111)\n plot.set_xlim([0, 255])\n plot.plot(range(0, 256), counts, color=plot_color)\n plot.axvline(mean, color='purple')\n return figure\n\n def get_color_stats(self):\n width, height = self.image.width, self.image.height\n\n red_counts = [0] * 256\n green_counts = [0] * 256\n blue_counts = [0] * 256\n\n for i in range(width):\n for j in range(height):\n r, g, b = self.image.getpixel((i, j))\n red_counts[r] += 1\n green_counts[g] += 1\n blue_counts[b] += 1\n\n return red_counts, green_counts, blue_counts\n\n @staticmethod\n def get_values_from_counts(counts):\n values = []\n for v, count in enumerate(counts):\n values.extend([v] * count)\n return values\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('image_path', type=str, help='Path to the image file')\n args = parser.parse_args()\n\n window = ColorStatsWindow(args.image_path)\n window.root.mainloop()\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"matplotlib.use",
"matplotlib.figure.Figure",
"matplotlib.backends.backend_tkagg.FigureCanvasTkAgg"
]
] |
JasonSanchez/machine-learning-for-all
|
[
"e4a7d581ccdc5f2faa71ff14109095f425a55e0b"
] |
[
"flask/app/viz.py"
] |
[
"from __future__ import division\n\nfrom flask import render_template, request, Response, jsonify,redirect,url_for,flash\nfrom werkzeug.utils import secure_filename\n\nfrom app import app\n\nimport json\nimport psycopg2\nimport psycopg2.extras\nimport os\nimport pandas as pd\nimport hashlib\nimport datetime\nfrom datetime import date\nimport numpy as np\nfrom subprocess import Popen\nimport shlex\nimport sys\nimport requests\nimport threading\nfrom json2table import convert\nfrom flask import send_from_directory\n\nmodule_path = os.path.abspath(os.path.join('../'))\nif module_path not in sys.path:\n sys.path.append(module_path)\n\nfrom learn import forall as fa\nfrom learn import utils\n\nTRAINING_DATA={}\nTESTING_DATA={}\n\n\nALLOWED_EXTENSIONS=set(['txt','csv'])\nSECRET_KEY='ml4all'\napp.secret_key='ml4all'\n\np=\"global variable for the vis server\"\n\[email protected]('/index')\ndef index():\n\treturn render_template('home.html')\n\[email protected]('/')\ndef dataset():\n return render_template('home.html')\n\[email protected]('/method')\ndef method():\n\treturn render_template('method.html')\n\n\ndef to_csv(d, fields):\n\td.insert(0, fields)\n\treturn Response('\\n'.join([\",\".join(map(str, e)) for e in d]), mimetype='text/csv')\n\ndef allowed_file(filename):\n\treturn '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\[email protected]('/dataset',methods=['POST'])\ndef upload_file():\n\tglobal p\n\ttrain_file_name = 'train'\n\ttest_file_name ='test'\n\terror=None\n\tif request.method == 'POST':\n\t\ttry:\n\t\t\tp.terminate()\n\t\t\tprint(\"Shiny server killed.\")\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\tprint(\"Did not find a Shiny server to kill...\")\n\n\t\t# check if the post request has the file part\n\t\tif train_file_name not in request.files or test_file_name not in request.files:\n\t\t\t#flash('No file part')\n\t\t\terror='Kindly upload both training and testing files'\n\t\t\t#print(\"helllllo\")\n\t\t\t#print(request.url)\n\t\t\tflash(\"load files\")\n\t\t\t#return redirect(request.url)\n\t\t\treturn render_template('home.html',error=error)\n\n\n\t\tfile = request.files[train_file_name]\n\n\t\t# if user does not select file, browser also\n\t\t# submit a empty part without filename\n\t\tif file.filename == '':\n\n\t\t\tprint(request.url)\n\t\t\terror='Kindly upload both training and testing files'\n\n\t\t\tflash('No selected files')\n\t\t\treturn redirect(request.url)\n\t\t\t#return render_template('home.html',error=error)\n\n\t\tif file and allowed_file(file.filename):\n\t\t\tfilename = secure_filename(file.filename)\n\t\t\tprint(filename)\n\t\t\tprint(os.path.abspath(os.path.join('app/','uploads/')))\n\t\t\t#file.save(os.path.abspath(os.path.join('app/',app.config['UPLOAD_FOLDER'], filename)))\n\t\t\tfile.save(os.path.abspath(os.path.join('app/','uploads/', filename)))\n\t\t\tprint(\"done\")\n\t\t\t## convert file to pandas dataframe\n\t\t\t#df_train=pd.read_csv(os.path.join('app/',app.config['UPLOAD_FOLDER'], filename))\n\t\t\tdf_train=pd.read_csv(os.path.join('app/','uploads/', filename))\n\n\t\t\tprint(\"df_train1\",df_train.head(5))\n\n\t\t\t## hash the pd , change to binary --> get fom Jason\n\t\t\ttemp_hash=pd.util.hash_pandas_object(df_train)\n\t\t\thash_train = hashlib.sha256(str(temp_hash).encode('utf-8','ignore')).hexdigest()\n\n\t\t\t#Save train data in /uploads folder\n\t\t\ttrain_file_name=filename\n\t\t\tos.system(\"mv app/uploads/\" + filename + \" \" + \"app/uploads/\" + hash_train + \".csv\")\n\t\t\t## update dict ---> key:hash ,value: dataframe\n\t\t\t#TRAINING_DATA[hash_train]=df_train\n\n\t\t## For the test file\n\t\tfile = request.files[test_file_name]\n\n\t\t\t# if user does not select file, browser also\n\t\t\t# submit a empty part without filename\n\t\tif file.filename == '':\n\t\t\tprint(request_url)\n\t\t\tflash('No selected files')\n\t\t\treturn redirect(request.url)\n\t\tif file and allowed_file(file.filename):\n\t\t\tfilename = secure_filename(file.filename)\n\t\t\t#file.save(os.path.abspath(os.path.join('app/',app.config['UPLOAD_FOLDER'], filename)))\n\t\t\tfile.save(os.path.abspath(os.path.join('app/','uploads/', filename)))\n\n\t\t\t## convert file to pandas dataframe\n\t\t\t#df_test=pd.read_csv(os.path.join('app/',app.config['UPLOAD_FOLDER'], filename))\n\t\t\tdf_test=pd.read_csv(os.path.join('app/','uploads/', filename))\n\t\t\tprint(\"df_test1\",df_test.head(5))\n\n\t\t\t## hash the pd , change to binary --> get fom Jason\n\t\t\ttemp_hash=pd.util.hash_pandas_object(df_test)\n\t\t\thash_test = hashlib.sha256(str(temp_hash).encode('utf-8','ignore')).hexdigest()\n\n\t\t\t# Save test data in /uploads folder\n\t\t\ttest_file_name=filename\n\t\t\tos.system(\"mv app/uploads/\" + filename + \" \" + \"app/uploads/\" + hash_test + \".csv\")\n\n\t\t# Pass datasets to Shiny app\n\t\tp = Popen(shlex.split(\"Rscript app/shiny/shiny.R \" + hash_train + \".csv \" + hash_test + \".csv \" + train_file_name + \" \" + test_file_name))\n\t\treturn(jsonify({\"hash_train\": hash_train, \"hash_test\": hash_test}))\n\n\[email protected]('/shiny',methods=['GET'])\ndef check_shiny():\n\t# Check if Shiny server is up\n\tresponse_code = 0\n\timport time\n\twhile response_code != 200:\n\t\ttry:\n\t\t\tr = requests.head(\"http://127.0.0.1:2326\")\n\t\t\tresponse_code = r.status_code\n\t\t\tprint(r.status_code)\n\t\texcept requests.ConnectionError:\n\t\t\ttime.sleep(0.1)\n\t\t\tprint(\"Trying to connect to Shiny server.\")\n\t\t\tpass\n\n\treturn(\"Shiny server is up.\")\n\n\[email protected]('/predict/<hash_train>_<hash_test>', methods=['GET'])\ndef run_prediction(hash_train, hash_test):\n\ttrain_file=hash_train + \".csv\"\n\ttest_file=hash_test + \".csv\"\n\n\t# Make predictions\n\tdf_train=pd.read_csv(os.path.join('app/','uploads/', train_file))\n\tdf_test=pd.read_csv(os.path.join('app/','uploads/', test_file))\n\tX, y = utils.X_y_split(X_train=df_train, X_test=df_test)\n\tmodel = fa.All()\n\tmodel.fit(X, y)\n\n\t# Append prediction column to test set at column 1\n\tpredictions = model.predict(df_test)\n\tprediction_name=\"predict_\" + model.target_name\n\tdf_test.insert(0, prediction_name, predictions)\n\n\t# Get current time\n\tfrom datetime import datetime\n\tt_current=datetime.now().strftime('%Y%m%d%H%M%S')\n\n\t# Save output file in /downloads folder\n\tdf_test.to_csv(\"app/downloads/\" + \"Predict\" + \"_\" + model.target_name + \"_\" + t_current + \".csv\", index=False)\n\n\t# Add model.display_score to JSON and round values\n\toutput_dic = {\"Overall score\" : model.display_score,\n\t\t\t\t# model.understandable_metric_name : round(model.understandable_metric_value, 2),\n\t\t\t\t \" \" : model.understandable_metric_description}\n\n\t# Build HTML table\n\tbuild_direction = \"LEFT_TO_RIGHT\"\n\ttable_attributes = {\"style\" : \"width:60%\"}\n\tdisplay_score = convert(output_dic, build_direction=build_direction, table_attributes=table_attributes)\n\n\treturn(jsonify({\"fileid\": \"Predict\" + \"_\" + model.target_name + \"_\" + t_current, \"performance\": display_score}))\n\n\[email protected]('/download/<hashid>',methods=['GET'])\ndef prediction_test(hashid):\n\treturn send_from_directory(directory=os.path.abspath(os.path.join('app/downloads/')), filename=hashid + \".csv\")\n"
] |
[
[
"pandas.util.hash_pandas_object"
]
] |
parthxtripathi/zarr-python
|
[
"c7494a9e21df777f7b6f962ea5c41b803f7f418c"
] |
[
"zarr/tests/test_core.py"
] |
[
"import atexit\nimport os\nimport sys\nimport pickle\nimport shutil\nimport unittest\nfrom itertools import zip_longest\nfrom tempfile import mkdtemp, mktemp\n\nimport numpy as np\nimport pytest\nfrom numcodecs import (BZ2, JSON, LZ4, Blosc, Categorize, Delta,\n FixedScaleOffset, GZip, MsgPack, Pickle, VLenArray,\n VLenBytes, VLenUTF8, Zlib)\nfrom numcodecs.compat import ensure_bytes, ensure_ndarray\nfrom numcodecs.tests.common import greetings\nfrom numpy.testing import assert_array_almost_equal, assert_array_equal\nfrom pkg_resources import parse_version\n\nfrom zarr._storage.store import (\n _prefix_to_array_key,\n _prefix_to_attrs_key,\n _prefix_to_group_key\n)\nfrom zarr.core import Array\nfrom zarr.errors import ArrayNotFoundError, ContainsGroupError\nfrom zarr.meta import json_loads\nfrom zarr.n5 import N5Store, N5FSStore, n5_keywords\nfrom zarr.storage import (\n ABSStore,\n DBMStore,\n DirectoryStore,\n FSStore,\n KVStore,\n LMDBStore,\n LRUStoreCache,\n NestedDirectoryStore,\n SQLiteStore,\n ABSStoreV3,\n DBMStoreV3,\n DirectoryStoreV3,\n FSStoreV3,\n KVStoreV3,\n LMDBStoreV3,\n LRUStoreCacheV3,\n SQLiteStoreV3,\n StoreV3,\n atexit_rmglob,\n atexit_rmtree,\n data_root,\n init_array,\n init_group,\n meta_root,\n)\nfrom zarr.util import buffer_size\nfrom zarr.tests.util import abs_container, skip_test_env_var, have_fsspec\n\n# noinspection PyMethodMayBeStatic\n\n\nclass TestArray(unittest.TestCase):\n\n version = 2\n\n def test_array_init(self):\n\n # normal initialization\n store = KVStore(dict())\n init_array(store, shape=100, chunks=10, dtype=\"<f8\")\n a = Array(store)\n assert isinstance(a, Array)\n assert (100,) == a.shape\n assert (10,) == a.chunks\n assert '' == a.path\n assert a.name is None\n assert a.basename is None\n assert store is a.store\n assert \"8fecb7a17ea1493d9c1430d04437b4f5b0b34985\" == a.hexdigest()\n store.close()\n\n # initialize at path\n store = KVStore(dict())\n init_array(store, shape=100, chunks=10, path='foo/bar', dtype='<f8')\n a = Array(store, path='foo/bar')\n assert isinstance(a, Array)\n assert (100,) == a.shape\n assert (10,) == a.chunks\n assert 'foo/bar' == a.path\n assert '/foo/bar' == a.name\n assert 'bar' == a.basename\n assert store is a.store\n assert \"8fecb7a17ea1493d9c1430d04437b4f5b0b34985\" == a.hexdigest()\n\n # store not initialized\n store = KVStore(dict())\n with pytest.raises(ValueError):\n Array(store)\n\n # group is in the way\n store = KVStore(dict())\n init_group(store, path='baz')\n with pytest.raises(ValueError):\n Array(store, path='baz')\n\n def create_array(self, read_only=False, **kwargs):\n store = KVStore(dict())\n kwargs.setdefault('compressor', Zlib(level=1))\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def test_store_has_text_keys(self):\n # Initialize array\n np.random.seed(42)\n z = self.create_array(shape=(1050,), chunks=100, dtype='f8', compressor=[])\n z[:] = np.random.random(z.shape)\n\n expected_type = str\n\n for k in z.chunk_store.keys():\n if not isinstance(k, expected_type): # pragma: no cover\n pytest.fail(\"Non-text key: %s\" % repr(k))\n\n z.store.close()\n\n def test_store_has_binary_values(self):\n # Initialize array\n np.random.seed(42)\n z = self.create_array(shape=(1050,), chunks=100, dtype='f8', compressor=[])\n z[:] = np.random.random(z.shape)\n\n for v in z.chunk_store.values():\n try:\n ensure_ndarray(v)\n except TypeError: # pragma: no cover\n pytest.fail(\"Non-bytes-like value: %s\" % repr(v))\n\n z.store.close()\n\n def test_store_has_bytes_values(self):\n # Test that many stores do hold bytes values.\n # Though this is not a strict requirement.\n # Should be disabled by any stores that fail this as needed.\n\n # Initialize array\n np.random.seed(42)\n z = self.create_array(shape=(1050,), chunks=100, dtype='f8', compressor=[])\n z[:] = np.random.random(z.shape)\n\n # Check in-memory array only contains `bytes`\n assert all(isinstance(v, bytes) for v in z.chunk_store.values())\n\n z.store.close()\n\n def test_nbytes_stored(self):\n\n # dict as store\n z = self.create_array(shape=1000, chunks=100)\n expect_nbytes_stored = sum(buffer_size(v) for v in z.store.values())\n assert expect_nbytes_stored == z.nbytes_stored\n z[:] = 42\n expect_nbytes_stored = sum(buffer_size(v) for v in z.store.values())\n assert expect_nbytes_stored == z.nbytes_stored\n\n # mess with store\n try:\n z.store[z._key_prefix + 'foo'] = list(range(10))\n assert -1 == z.nbytes_stored\n except TypeError:\n pass\n\n z.store.close()\n\n # noinspection PyStatementEffect\n def test_array_1d(self):\n a = np.arange(1050)\n z = self.create_array(shape=a.shape, chunks=100, dtype=a.dtype)\n\n # check properties\n assert len(a) == len(z)\n assert a.ndim == z.ndim\n assert a.shape == z.shape\n assert a.dtype == z.dtype\n assert (100,) == z.chunks\n assert a.nbytes == z.nbytes\n assert 11 == z.nchunks\n assert 0 == z.nchunks_initialized\n assert (11,) == z.cdata_shape\n\n # check empty\n b = z[:]\n assert isinstance(b, np.ndarray)\n assert a.shape == b.shape\n assert a.dtype == b.dtype\n\n # check attributes\n z.attrs['foo'] = 'bar'\n assert 'bar' == z.attrs['foo']\n\n # set data\n z[:] = a\n\n # check properties\n assert a.nbytes == z.nbytes\n assert 11 == z.nchunks\n assert 11 == z.nchunks_initialized\n\n # check slicing\n assert_array_equal(a, np.array(z))\n assert_array_equal(a, z[:])\n assert_array_equal(a, z[...])\n # noinspection PyTypeChecker\n assert_array_equal(a, z[slice(None)])\n assert_array_equal(a[:10], z[:10])\n assert_array_equal(a[10:20], z[10:20])\n assert_array_equal(a[-10:], z[-10:])\n assert_array_equal(a[:10, ...], z[:10, ...])\n assert_array_equal(a[10:20, ...], z[10:20, ...])\n assert_array_equal(a[-10:, ...], z[-10:, ...])\n assert_array_equal(a[..., :10], z[..., :10])\n assert_array_equal(a[..., 10:20], z[..., 10:20])\n assert_array_equal(a[..., -10:], z[..., -10:])\n # ...across chunk boundaries...\n assert_array_equal(a[:110], z[:110])\n assert_array_equal(a[190:310], z[190:310])\n assert_array_equal(a[-110:], z[-110:])\n # single item\n assert a[0] == z[0]\n assert a[-1] == z[-1]\n # unusual integer items\n assert a[42] == z[np.int64(42)]\n assert a[42] == z[np.int32(42)]\n assert a[42] == z[np.uint64(42)]\n assert a[42] == z[np.uint32(42)]\n # too many indices\n with pytest.raises(IndexError):\n z[:, :]\n with pytest.raises(IndexError):\n z[0, :]\n with pytest.raises(IndexError):\n z[:, 0]\n with pytest.raises(IndexError):\n z[0, 0]\n # only single ellipsis allowed\n with pytest.raises(IndexError):\n z[..., ...]\n\n # check partial assignment\n b = np.arange(1e5, 2e5)\n z[190:310] = b[190:310]\n assert_array_equal(a[:190], z[:190])\n assert_array_equal(b[190:310], z[190:310])\n assert_array_equal(a[310:], z[310:])\n\n z.store.close()\n\n def test_array_1d_fill_value(self):\n for fill_value in -1, 0, 1, 10:\n\n a = np.arange(1050)\n f = np.empty_like(a)\n f.fill(fill_value)\n z = self.create_array(shape=a.shape, chunks=100, dtype=a.dtype,\n fill_value=fill_value)\n z[190:310] = a[190:310]\n\n assert_array_equal(f[:190], z[:190])\n assert_array_equal(a[190:310], z[190:310])\n assert_array_equal(f[310:], z[310:])\n\n z.store.close()\n\n def test_array_1d_set_scalar(self):\n # test setting the contents of an array with a scalar value\n\n # setup\n a = np.zeros(100)\n z = self.create_array(shape=a.shape, chunks=10, dtype=a.dtype)\n z[:] = a\n assert_array_equal(a, z[:])\n\n for value in -1, 0, 1, 10:\n a[15:35] = value\n z[15:35] = value\n assert_array_equal(a, z[:])\n a[:] = value\n z[:] = value\n assert_array_equal(a, z[:])\n\n z.store.close()\n\n def test_array_1d_selections(self):\n # light test here, full tests in test_indexing\n\n # setup\n a = np.arange(1050)\n z = self.create_array(shape=a.shape, chunks=100, dtype=a.dtype)\n z[:] = a\n\n # get\n assert_array_equal(a[50:150], z.get_orthogonal_selection(slice(50, 150)))\n assert_array_equal(a[50:150], z.oindex[50: 150])\n ix = [99, 100, 101]\n bix = np.zeros_like(a, dtype=bool)\n bix[ix] = True\n assert_array_equal(a[ix], z.get_orthogonal_selection(ix))\n assert_array_equal(a[ix], z.oindex[ix])\n assert_array_equal(a[ix], z.get_coordinate_selection(ix))\n assert_array_equal(a[ix], z.vindex[ix])\n assert_array_equal(a[bix], z.get_mask_selection(bix))\n assert_array_equal(a[bix], z.oindex[bix])\n assert_array_equal(a[bix], z.vindex[bix])\n\n # set\n z.set_orthogonal_selection(slice(50, 150), 1)\n assert_array_equal(1, z[50:150])\n z.oindex[50:150] = 2\n assert_array_equal(2, z[50:150])\n z.set_orthogonal_selection(ix, 3)\n assert_array_equal(3, z.get_coordinate_selection(ix))\n z.oindex[ix] = 4\n assert_array_equal(4, z.oindex[ix])\n z.set_coordinate_selection(ix, 5)\n assert_array_equal(5, z.get_coordinate_selection(ix))\n z.vindex[ix] = 6\n assert_array_equal(6, z.vindex[ix])\n z.set_mask_selection(bix, 7)\n assert_array_equal(7, z.get_mask_selection(bix))\n z.vindex[bix] = 8\n assert_array_equal(8, z.vindex[bix])\n z.oindex[bix] = 9\n assert_array_equal(9, z.oindex[bix])\n\n z.store.close()\n\n # noinspection PyStatementEffect\n def test_array_2d(self):\n a = np.arange(10000).reshape((1000, 10))\n z = self.create_array(shape=a.shape, chunks=(100, 2), dtype=a.dtype)\n\n # check properties\n assert len(a) == len(z)\n assert a.ndim == z.ndim\n assert a.shape == z.shape\n assert a.dtype == z.dtype\n assert (100, 2) == z.chunks\n assert 0 == z.nchunks_initialized\n assert (10, 5) == z.cdata_shape\n\n # set data\n z[:] = a\n\n # check properties\n assert a.nbytes == z.nbytes\n assert 50 == z.nchunks_initialized\n\n # check array-like\n assert_array_equal(a, np.array(z))\n\n # check slicing\n\n # total slice\n assert_array_equal(a, z[:])\n assert_array_equal(a, z[...])\n # noinspection PyTypeChecker\n assert_array_equal(a, z[slice(None)])\n\n # slice first dimension\n assert_array_equal(a[:10], z[:10])\n assert_array_equal(a[10:20], z[10:20])\n assert_array_equal(a[-10:], z[-10:])\n assert_array_equal(a[:10, :], z[:10, :])\n assert_array_equal(a[10:20, :], z[10:20, :])\n assert_array_equal(a[-10:, :], z[-10:, :])\n assert_array_equal(a[:10, ...], z[:10, ...])\n assert_array_equal(a[10:20, ...], z[10:20, ...])\n assert_array_equal(a[-10:, ...], z[-10:, ...])\n assert_array_equal(a[:10, :, ...], z[:10, :, ...])\n assert_array_equal(a[10:20, :, ...], z[10:20, :, ...])\n assert_array_equal(a[-10:, :, ...], z[-10:, :, ...])\n\n # slice second dimension\n assert_array_equal(a[:, :2], z[:, :2])\n assert_array_equal(a[:, 2:4], z[:, 2:4])\n assert_array_equal(a[:, -2:], z[:, -2:])\n assert_array_equal(a[..., :2], z[..., :2])\n assert_array_equal(a[..., 2:4], z[..., 2:4])\n assert_array_equal(a[..., -2:], z[..., -2:])\n assert_array_equal(a[:, ..., :2], z[:, ..., :2])\n assert_array_equal(a[:, ..., 2:4], z[:, ..., 2:4])\n assert_array_equal(a[:, ..., -2:], z[:, ..., -2:])\n\n # slice both dimensions\n assert_array_equal(a[:10, :2], z[:10, :2])\n assert_array_equal(a[10:20, 2:4], z[10:20, 2:4])\n assert_array_equal(a[-10:, -2:], z[-10:, -2:])\n\n # slicing across chunk boundaries\n assert_array_equal(a[:110], z[:110])\n assert_array_equal(a[190:310], z[190:310])\n assert_array_equal(a[-110:], z[-110:])\n assert_array_equal(a[:110, :], z[:110, :])\n assert_array_equal(a[190:310, :], z[190:310, :])\n assert_array_equal(a[-110:, :], z[-110:, :])\n assert_array_equal(a[:, :3], z[:, :3])\n assert_array_equal(a[:, 3:7], z[:, 3:7])\n assert_array_equal(a[:, -3:], z[:, -3:])\n assert_array_equal(a[:110, :3], z[:110, :3])\n assert_array_equal(a[190:310, 3:7], z[190:310, 3:7])\n assert_array_equal(a[-110:, -3:], z[-110:, -3:])\n\n # single row/col/item\n assert_array_equal(a[0], z[0])\n assert_array_equal(a[-1], z[-1])\n assert_array_equal(a[:, 0], z[:, 0])\n assert_array_equal(a[:, -1], z[:, -1])\n assert a[0, 0] == z[0, 0]\n assert a[-1, -1] == z[-1, -1]\n\n # too many indices\n with pytest.raises(IndexError):\n z[:, :, :]\n with pytest.raises(IndexError):\n z[0, :, :]\n with pytest.raises(IndexError):\n z[:, 0, :]\n with pytest.raises(IndexError):\n z[:, :, 0]\n with pytest.raises(IndexError):\n z[0, 0, 0]\n # only single ellipsis allowed\n with pytest.raises(IndexError):\n z[..., ...]\n\n # check partial assignment\n b = np.arange(10000, 20000).reshape((1000, 10))\n z[190:310, 3:7] = b[190:310, 3:7]\n assert_array_equal(a[:190], z[:190])\n assert_array_equal(a[:, :3], z[:, :3])\n assert_array_equal(b[190:310, 3:7], z[190:310, 3:7])\n assert_array_equal(a[310:], z[310:])\n assert_array_equal(a[:, 7:], z[:, 7:])\n\n z.store.close()\n\n def test_array_2d_edge_case(self):\n # this fails with filters - chunks extend beyond edge of array, messes with delta\n # filter if no fill value?\n shape = 1000, 10\n chunks = 300, 30\n dtype = 'i8'\n z = self.create_array(shape=shape, dtype=dtype, chunks=chunks)\n z[:] = 0\n expect = np.zeros(shape, dtype=dtype)\n actual = z[:]\n assert_array_equal(expect, actual)\n\n z.store.close()\n\n def test_array_2d_partial(self):\n z = self.create_array(shape=(1000, 10), chunks=(100, 2), dtype='i4',\n fill_value=0)\n\n # check partial assignment, single row\n c = np.arange(z.shape[1])\n z[0, :] = c\n with pytest.raises(ValueError):\n # N.B., NumPy allows this, but we'll be strict for now\n z[2:3] = c\n with pytest.raises(ValueError):\n # N.B., NumPy allows this, but we'll be strict for now\n z[-1:] = c\n z[2:3] = c[None, :]\n z[-1:] = c[None, :]\n assert_array_equal(c, z[0, :])\n assert_array_equal(c, z[2, :])\n assert_array_equal(c, z[-1, :])\n\n # check partial assignment, single column\n d = np.arange(z.shape[0])\n z[:, 0] = d\n with pytest.raises(ValueError):\n z[:, 2:3] = d\n with pytest.raises(ValueError):\n z[:, -1:] = d\n z[:, 2:3] = d[:, None]\n z[:, -1:] = d[:, None]\n assert_array_equal(d, z[:, 0])\n assert_array_equal(d, z[:, 2])\n assert_array_equal(d, z[:, -1])\n\n # check single item assignment\n z[0, 0] = -1\n z[2, 2] = -1\n z[-1, -1] = -1\n assert -1 == z[0, 0]\n assert -1 == z[2, 2]\n assert -1 == z[-1, -1]\n\n z.store.close()\n\n def test_array_order(self):\n\n # 1D\n a = np.arange(1050)\n for order in 'C', 'F':\n z = self.create_array(shape=a.shape, chunks=100, dtype=a.dtype,\n order=order)\n assert order == z.order\n if order == 'F':\n assert z[:].flags.f_contiguous\n else:\n assert z[:].flags.c_contiguous\n z[:] = a\n assert_array_equal(a, z[:])\n\n z.store.close()\n\n # 2D\n a = np.arange(10000).reshape((100, 100))\n for order in 'C', 'F':\n z = self.create_array(shape=a.shape, chunks=(10, 10),\n dtype=a.dtype, order=order)\n assert order == z.order\n if order == 'F':\n assert z[:].flags.f_contiguous\n else:\n assert z[:].flags.c_contiguous\n z[:] = a\n actual = z[:]\n assert_array_equal(a, actual)\n\n z.store.close()\n\n def test_setitem_data_not_shared(self):\n # check that data don't end up being shared with another array\n # https://github.com/alimanfoo/zarr/issues/79\n z = self.create_array(shape=20, chunks=10, dtype='i4')\n a = np.arange(20, dtype='i4')\n z[:] = a\n assert_array_equal(z[:], np.arange(20, dtype='i4'))\n a[:] = 0\n assert_array_equal(z[:], np.arange(20, dtype='i4'))\n z.store.close()\n\n def expected(self):\n # tests for array without path will not be run for v3 stores\n assert self.version == 2\n return [\n \"063b02ff8d9d3bab6da932ad5828b506ef0a6578\",\n \"f97b84dc9ffac807415f750100108764e837bb82\",\n \"c7190ad2bea1e9d2e73eaa2d3ca9187be1ead261\",\n \"14470724dca6c1837edddedc490571b6a7f270bc\",\n \"2a1046dd99b914459b3e86be9dde05027a07d209\",\n ]\n\n def test_hexdigest(self):\n found = []\n\n # Check basic 1-D array\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n found.append(z.hexdigest())\n z.store.close()\n\n # Check basic 1-D array with different type\n z = self.create_array(shape=(1050,), chunks=100, dtype='<f4')\n found.append(z.hexdigest())\n z.store.close()\n\n # Check basic 2-D array\n z = self.create_array(shape=(20, 35,), chunks=10, dtype='<i4')\n found.append(z.hexdigest())\n z.store.close()\n\n # Check basic 1-D array with some data\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z[200:400] = np.arange(200, 400, dtype='i4')\n found.append(z.hexdigest())\n z.store.close()\n\n # Check basic 1-D array with attributes\n z = self.create_array(shape=(1050,), chunks=100, dtype='<i4')\n z.attrs['foo'] = 'bar'\n found.append(z.hexdigest())\n z.store.close()\n\n assert self.expected() == found\n\n def test_resize_1d(self):\n\n z = self.create_array(shape=105, chunks=10, dtype='i4',\n fill_value=0)\n a = np.arange(105, dtype='i4')\n z[:] = a\n assert (105,) == z.shape\n assert (105,) == z[:].shape\n assert np.dtype('i4') == z.dtype\n assert np.dtype('i4') == z[:].dtype\n assert (10,) == z.chunks\n assert_array_equal(a, z[:])\n\n z.resize(205)\n assert (205,) == z.shape\n assert (205,) == z[:].shape\n assert np.dtype('i4') == z.dtype\n assert np.dtype('i4') == z[:].dtype\n assert (10,) == z.chunks\n assert_array_equal(a, z[:105])\n assert_array_equal(np.zeros(100, dtype='i4'), z[105:])\n\n z.resize(55)\n assert (55,) == z.shape\n assert (55,) == z[:].shape\n assert np.dtype('i4') == z.dtype\n assert np.dtype('i4') == z[:].dtype\n assert (10,) == z.chunks\n assert_array_equal(a[:55], z[:])\n\n # via shape setter\n z.shape = (105,)\n assert (105,) == z.shape\n assert (105,) == z[:].shape\n\n z.store.close()\n\n def test_resize_2d(self):\n\n z = self.create_array(shape=(105, 105), chunks=(10, 10), dtype='i4',\n fill_value=0)\n a = np.arange(105*105, dtype='i4').reshape((105, 105))\n z[:] = a\n assert (105, 105) == z.shape\n assert (105, 105) == z[:].shape\n assert np.dtype('i4') == z.dtype\n assert np.dtype('i4') == z[:].dtype\n assert (10, 10) == z.chunks\n assert_array_equal(a, z[:])\n\n z.resize((205, 205))\n assert (205, 205) == z.shape\n assert (205, 205) == z[:].shape\n assert np.dtype('i4') == z.dtype\n assert np.dtype('i4') == z[:].dtype\n assert (10, 10) == z.chunks\n assert_array_equal(a, z[:105, :105])\n assert_array_equal(np.zeros((100, 205), dtype='i4'), z[105:, :])\n assert_array_equal(np.zeros((205, 100), dtype='i4'), z[:, 105:])\n\n z.resize((55, 55))\n assert (55, 55) == z.shape\n assert (55, 55) == z[:].shape\n assert np.dtype('i4') == z.dtype\n assert np.dtype('i4') == z[:].dtype\n assert (10, 10) == z.chunks\n assert_array_equal(a[:55, :55], z[:])\n\n z.resize((55, 1))\n assert (55, 1) == z.shape\n assert (55, 1) == z[:].shape\n assert np.dtype('i4') == z.dtype\n assert np.dtype('i4') == z[:].dtype\n assert (10, 10) == z.chunks\n assert_array_equal(a[:55, :1], z[:])\n\n # via shape setter\n z.shape = (105, 105)\n assert (105, 105) == z.shape\n assert (105, 105) == z[:].shape\n\n z.store.close()\n\n def test_append_1d(self):\n\n a = np.arange(105)\n z = self.create_array(shape=a.shape, chunks=10, dtype=a.dtype)\n z[:] = a\n assert a.shape == z.shape\n assert a.dtype == z.dtype\n assert (10,) == z.chunks\n assert_array_equal(a, z[:])\n\n b = np.arange(105, 205)\n e = np.append(a, b)\n z.append(b)\n assert e.shape == z.shape\n assert e.dtype == z.dtype\n assert (10,) == z.chunks\n assert_array_equal(e, z[:])\n\n # check append handles array-like\n c = [1, 2, 3]\n f = np.append(e, c)\n z.append(c)\n assert f.shape == z.shape\n assert f.dtype == z.dtype\n assert (10,) == z.chunks\n assert_array_equal(f, z[:])\n\n z.store.close()\n\n def test_append_2d(self):\n\n a = np.arange(105*105, dtype='i4').reshape((105, 105))\n z = self.create_array(shape=a.shape, chunks=(10, 10), dtype=a.dtype)\n z[:] = a\n assert a.shape == z.shape\n assert a.dtype == z.dtype\n assert (10, 10) == z.chunks\n actual = z[:]\n assert_array_equal(a, actual)\n\n b = np.arange(105*105, 2*105*105, dtype='i4').reshape((105, 105))\n e = np.append(a, b, axis=0)\n z.append(b)\n assert e.shape == z.shape\n assert e.dtype == z.dtype\n assert (10, 10) == z.chunks\n actual = z[:]\n assert_array_equal(e, actual)\n\n z.store.close()\n\n def test_append_2d_axis(self):\n\n a = np.arange(105*105, dtype='i4').reshape((105, 105))\n z = self.create_array(shape=a.shape, chunks=(10, 10), dtype=a.dtype)\n z[:] = a\n assert a.shape == z.shape\n assert a.dtype == z.dtype\n assert (10, 10) == z.chunks\n assert_array_equal(a, z[:])\n\n b = np.arange(105*105, 2*105*105, dtype='i4').reshape((105, 105))\n e = np.append(a, b, axis=1)\n z.append(b, axis=1)\n assert e.shape == z.shape\n assert e.dtype == z.dtype\n assert (10, 10) == z.chunks\n assert_array_equal(e, z[:])\n\n z.store.close()\n\n def test_append_bad_shape(self):\n a = np.arange(100)\n z = self.create_array(shape=a.shape, chunks=10, dtype=a.dtype)\n z[:] = a\n b = a.reshape(10, 10)\n with pytest.raises(ValueError):\n z.append(b)\n z.store.close()\n\n def test_read_only(self):\n\n z = self.create_array(shape=1000, chunks=100)\n assert not z.read_only\n z.store.close()\n\n z = self.create_array(shape=1000, chunks=100, read_only=True)\n assert z.read_only\n with pytest.raises(PermissionError):\n z[:] = 42\n with pytest.raises(PermissionError):\n z.resize(2000)\n with pytest.raises(PermissionError):\n z.append(np.arange(1000))\n with pytest.raises(PermissionError):\n z.set_basic_selection(Ellipsis, 42)\n with pytest.raises(PermissionError):\n z.set_orthogonal_selection([0, 1, 2], 42)\n with pytest.raises(PermissionError):\n z.oindex[[0, 1, 2]] = 42\n with pytest.raises(PermissionError):\n z.set_coordinate_selection([0, 1, 2], 42)\n with pytest.raises(PermissionError):\n z.vindex[[0, 1, 2]] = 42\n with pytest.raises(PermissionError):\n z.set_mask_selection(np.ones(z.shape, dtype=bool), 42)\n\n z.store.close()\n\n def test_pickle(self):\n\n # setup array\n z = self.create_array(shape=1000, chunks=100, dtype=int, cache_metadata=False,\n cache_attrs=False)\n shape = z.shape\n chunks = z.chunks\n dtype = z.dtype\n compressor_config = None\n if z.compressor:\n compressor_config = z.compressor.get_config()\n fill_value = z.fill_value\n cache_metadata = z._cache_metadata\n attrs_cache = z.attrs.cache\n a = np.random.randint(0, 1000, 1000)\n z[:] = a\n\n # round trip through pickle\n dump = pickle.dumps(z)\n # some stores cannot be opened twice at the same time, need to close\n # store before can round-trip through pickle\n z.store.close()\n z2 = pickle.loads(dump)\n\n # verify\n assert shape == z2.shape\n assert chunks == z2.chunks\n assert dtype == z2.dtype\n if z2.compressor:\n assert compressor_config == z2.compressor.get_config()\n assert fill_value == z2.fill_value\n assert cache_metadata == z2._cache_metadata\n assert attrs_cache == z2.attrs.cache\n assert_array_equal(a, z2[:])\n\n z2.store.close()\n\n def test_np_ufuncs(self):\n z = self.create_array(shape=(100, 100), chunks=(10, 10))\n a = np.arange(10000).reshape(100, 100)\n z[:] = a\n\n assert np.sum(a) == np.sum(z)\n assert_array_equal(np.sum(a, axis=0), np.sum(z, axis=0))\n assert np.mean(a) == np.mean(z)\n assert_array_equal(np.mean(a, axis=1), np.mean(z, axis=1))\n condition = np.random.randint(0, 2, size=100, dtype=bool)\n assert_array_equal(np.compress(condition, a, axis=0),\n np.compress(condition, z, axis=0))\n indices = np.random.choice(100, size=50, replace=True)\n assert_array_equal(np.take(a, indices, axis=1),\n np.take(z, indices, axis=1))\n\n z.store.close()\n\n # use zarr array as indices or condition\n zc = self.create_array(shape=condition.shape, dtype=condition.dtype,\n chunks=10, filters=None)\n zc[:] = condition\n assert_array_equal(np.compress(condition, a, axis=0),\n np.compress(zc, a, axis=0))\n zc.store.close()\n\n zi = self.create_array(shape=indices.shape, dtype=indices.dtype,\n chunks=10, filters=None)\n zi[:] = indices\n # this triggers __array__() call with dtype argument\n assert_array_equal(np.take(a, indices, axis=1),\n np.take(a, zi, axis=1))\n zi.store.close()\n\n # noinspection PyStatementEffect\n def test_0len_dim_1d(self):\n # Test behaviour for 1D array with zero-length dimension.\n\n z = self.create_array(shape=0, fill_value=0)\n a = np.zeros(0)\n assert a.ndim == z.ndim\n assert a.shape == z.shape\n assert a.dtype == z.dtype\n assert a.size == z.size\n assert 0 == z.nchunks\n\n # cannot make a good decision when auto-chunking if a dimension has zero length,\n # fall back to 1 for now\n assert (1,) == z.chunks\n\n # check __getitem__\n assert isinstance(z[:], np.ndarray)\n assert_array_equal(a, np.array(z))\n assert_array_equal(a, z[:])\n assert_array_equal(a, z[...])\n assert_array_equal(a[0:0], z[0:0])\n with pytest.raises(IndexError):\n z[0]\n\n # check __setitem__\n # these should succeed but do nothing\n z[:] = 42\n z[...] = 42\n # this should error\n with pytest.raises(IndexError):\n z[0] = 42\n\n z.store.close()\n\n # noinspection PyStatementEffect\n def test_0len_dim_2d(self):\n # Test behavioud for 2D array with a zero-length dimension.\n\n z = self.create_array(shape=(10, 0), fill_value=0)\n a = np.zeros((10, 0))\n assert a.ndim == z.ndim\n assert a.shape == z.shape\n assert a.dtype == z.dtype\n assert a.size == z.size\n assert 0 == z.nchunks\n\n # cannot make a good decision when auto-chunking if a dimension has zero length,\n # fall back to 1 for now\n assert (10, 1) == z.chunks\n\n # check __getitem__\n assert isinstance(z[:], np.ndarray)\n assert_array_equal(a, np.array(z))\n assert_array_equal(a, z[:])\n assert_array_equal(a, z[...])\n assert_array_equal(a[0], z[0])\n assert_array_equal(a[0, 0:0], z[0, 0:0])\n assert_array_equal(a[0, :], z[0, :])\n assert_array_equal(a[0, 0:0], z[0, 0:0])\n with pytest.raises(IndexError):\n z[:, 0]\n\n # check __setitem__\n # these should succeed but do nothing\n z[:] = 42\n z[...] = 42\n z[0, :] = 42\n # this should error\n with pytest.raises(IndexError):\n z[:, 0] = 42\n\n z.store.close()\n\n # noinspection PyStatementEffect\n def test_array_0d(self):\n # test behaviour for array with 0 dimensions\n\n # setup\n a = np.zeros(())\n z = self.create_array(shape=(), dtype=a.dtype, fill_value=0, write_empty_chunks=False)\n\n # check properties\n assert a.ndim == z.ndim\n assert a.shape == z.shape\n assert a.size == z.size\n assert a.dtype == z.dtype\n assert a.nbytes == z.nbytes\n with pytest.raises(TypeError):\n len(z)\n assert () == z.chunks\n assert 1 == z.nchunks\n assert (1,) == z.cdata_shape\n # compressor always None - no point in compressing a single value\n assert z.compressor is None\n\n # check __getitem__\n b = z[...]\n assert isinstance(b, np.ndarray)\n assert a.shape == b.shape\n assert a.dtype == b.dtype\n assert_array_equal(a, np.array(z))\n assert_array_equal(a, z[...])\n assert a[()] == z[()]\n with pytest.raises(IndexError):\n z[0]\n with pytest.raises(IndexError):\n z[:]\n\n # check __setitem__\n z[...] = 42\n assert 42 == z[()]\n z[()] = 43\n assert 43 == z[()]\n z[()] = z.fill_value\n assert z.fill_value == z[()]\n with pytest.raises(IndexError):\n z[0] = 42\n with pytest.raises(IndexError):\n z[:] = 42\n with pytest.raises(ValueError):\n z[...] = np.array([1, 2, 3])\n\n z.store.close()\n\n def test_nchunks_initialized(self):\n for fill_value in (0, 1.0, np.nan):\n if isinstance(fill_value, int):\n dtype = 'int'\n else:\n dtype = 'float'\n z = self.create_array(shape=100,\n chunks=10,\n fill_value=fill_value,\n dtype=dtype,\n write_empty_chunks=True)\n\n assert 0 == z.nchunks_initialized\n # manually put something into the store to confuse matters\n z.store['foo'] = b'bar'\n assert 0 == z.nchunks_initialized\n z[:] = 42\n assert 10 == z.nchunks_initialized\n # manually remove the first chunk from the store\n del z.chunk_store[z._chunk_key((0,))]\n assert 9 == z.nchunks_initialized\n\n z.store.close()\n\n def test_array_dtype_shape(self):\n\n dt = \"(2, 2)f4\"\n # setup some data\n d = np.array([((0, 1),\n (1, 2)),\n ((1, 2),\n (2, 3)),\n ((2, 3),\n (3, 4))],\n dtype=dt)\n\n for a in (d, d[:0]):\n for fill_value in None, 0:\n z = self.create_array(shape=a.shape[:-2], chunks=2, dtype=dt, fill_value=fill_value)\n assert len(a) == len(z)\n if fill_value is not None:\n assert fill_value == z.fill_value\n z[...] = a\n assert_array_equal(a, z[...])\n z.store.close()\n\n def check_structured_array(self, d, fill_values):\n for a in (d, d[:0]):\n for fill_value in fill_values:\n z = self.create_array(shape=a.shape, chunks=2, dtype=a.dtype, fill_value=fill_value)\n assert len(a) == len(z)\n assert a.shape == z.shape\n assert a.dtype == z.dtype\n\n # check use of fill value before array is initialised with data\n if fill_value is not None:\n if fill_value == b'':\n # numpy 1.14 compatibility\n np_fill_value = np.array(fill_value, dtype=a.dtype.str).view(a.dtype)[()]\n else:\n np_fill_value = np.array(fill_value, dtype=a.dtype)[()]\n assert np_fill_value == z.fill_value\n if len(a):\n assert np_fill_value == z[0]\n assert np_fill_value == z[-1]\n empty = np.empty_like(a)\n empty[:] = np_fill_value\n assert empty[0] == z[0]\n assert_array_equal(empty[0:2], z[0:2])\n assert_array_equal(empty, z[...])\n for f in a.dtype.names:\n assert_array_equal(empty[f], z[f])\n\n # store data in array\n z[...] = a\n\n # check stored data\n if len(a):\n assert a[0] == z[0]\n assert a[-1] == z[-1]\n assert_array_equal(a[0:2], z[0:2])\n assert_array_equal(a, z[...])\n for f in a.dtype.names:\n assert_array_equal(a[f], z[f])\n\n z.store.close()\n\n def test_structured_array(self):\n d = np.array([(b'aaa', 1, 4.2),\n (b'bbb', 2, 8.4),\n (b'ccc', 3, 12.6)],\n dtype=[('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])\n fill_values = None, b'', (b'zzz', 42, 16.8)\n self.check_structured_array(d, fill_values)\n\n def test_structured_array_subshapes(self):\n d = np.array([(0, ((0, 1, 2), (1, 2, 3)), b'aaa'),\n (1, ((1, 2, 3), (2, 3, 4)), b'bbb'),\n (2, ((2, 3, 4), (3, 4, 5)), b'ccc')],\n dtype=[('foo', 'i8'), ('bar', '(2, 3)f4'), ('baz', 'S3')])\n fill_values = None, b'', (0, ((0, 0, 0), (1, 1, 1)), b'zzz')\n self.check_structured_array(d, fill_values)\n\n def test_structured_array_nested(self):\n d = np.array([(0, (0, ((0, 1), (1, 2), (2, 3)), 0), b'aaa'),\n (1, (1, ((1, 2), (2, 3), (3, 4)), 1), b'bbb'),\n (2, (2, ((2, 3), (3, 4), (4, 5)), 2), b'ccc')],\n dtype=[('foo', 'i8'), ('bar', [('foo', 'i4'), ('bar', '(3, 2)f4'),\n ('baz', 'u1')]), ('baz', 'S3')])\n fill_values = None, b'', (0, (0, ((0, 0), (1, 1), (2, 2)), 0), b'zzz')\n self.check_structured_array(d, fill_values)\n\n def test_dtypes(self):\n\n # integers\n for dtype in 'u1', 'u2', 'u4', 'u8', 'i1', 'i2', 'i4', 'i8':\n z = self.create_array(shape=10, chunks=3, dtype=dtype)\n assert z.dtype == np.dtype(dtype)\n a = np.arange(z.shape[0], dtype=dtype)\n z[:] = a\n assert_array_equal(a, z[:])\n z.store.close()\n\n # floats\n for dtype in 'f2', 'f4', 'f8':\n z = self.create_array(shape=10, chunks=3, dtype=dtype)\n assert z.dtype == np.dtype(dtype)\n a = np.linspace(0, 1, z.shape[0], dtype=dtype)\n z[:] = a\n assert_array_almost_equal(a, z[:])\n z.store.close()\n\n # complex\n for dtype in 'c8', 'c16':\n z = self.create_array(shape=10, chunks=3, dtype=dtype)\n assert z.dtype == np.dtype(dtype)\n a = np.linspace(0, 1, z.shape[0], dtype=dtype)\n a -= 1j * a\n z[:] = a\n assert_array_almost_equal(a, z[:])\n z.store.close()\n\n # datetime, timedelta\n for base_type in 'Mm':\n for resolution in 'D', 'us', 'ns':\n dtype = '{}8[{}]'.format(base_type, resolution)\n z = self.create_array(shape=100, dtype=dtype, fill_value=0)\n assert z.dtype == np.dtype(dtype)\n a = np.random.randint(np.iinfo('i8').min, np.iinfo('i8').max,\n size=z.shape[0],\n dtype='i8').view(dtype)\n z[:] = a\n assert_array_equal(a, z[:])\n z.store.close()\n\n # unicode and bytestring dtypes\n for dtype in ['S4', 'S6', 'U5', 'U5']:\n n = 10\n z = self.create_array(shape=n, chunks=3, dtype=dtype)\n assert z.dtype == np.dtype(dtype)\n if dtype.startswith('S'):\n a = np.asarray([b'name'] * n, dtype=dtype)\n else:\n a = np.asarray(['§Æ¥¿é'] * n, dtype=dtype)\n z[:] = a\n np.all(a == z[:])\n z.store.close()\n\n # check that datetime generic units are not allowed\n with pytest.raises(ValueError):\n self.create_array(shape=100, dtype='M8')\n with pytest.raises(ValueError):\n self.create_array(shape=100, dtype='m8')\n\n def test_object_arrays(self):\n\n # an object_codec is required for object arrays\n with pytest.raises(ValueError):\n self.create_array(shape=10, chunks=3, dtype=object)\n\n # an object_codec is required for object arrays, but allow to be provided via\n # filters to maintain API backwards compatibility\n with pytest.warns(FutureWarning):\n z = self.create_array(shape=10, chunks=3, dtype=object, filters=[MsgPack()])\n z.store.close()\n\n # create an object array using msgpack\n z = self.create_array(shape=10, chunks=3, dtype=object, object_codec=MsgPack())\n z[0] = 'foo'\n assert z[0] == 'foo'\n z[1] = b'bar'\n assert z[1] == b'bar'\n z[2] = 1\n assert z[2] == 1\n z[3] = [2, 4, 6, 'baz']\n assert z[3] == [2, 4, 6, 'baz']\n z[4] = {'a': 'b', 'c': 'd'}\n assert z[4] == {'a': 'b', 'c': 'd'}\n a = z[:]\n assert a.dtype == object\n z.store.close()\n\n # create an object array using pickle\n z = self.create_array(shape=10, chunks=3, dtype=object, object_codec=Pickle())\n z[0] = 'foo'\n assert z[0] == 'foo'\n z[1] = b'bar'\n assert z[1] == b'bar'\n z[2] = 1\n assert z[2] == 1\n z[3] = [2, 4, 6, 'baz']\n assert z[3] == [2, 4, 6, 'baz']\n z[4] = {'a': 'b', 'c': 'd'}\n assert z[4] == {'a': 'b', 'c': 'd'}\n a = z[:]\n assert a.dtype == object\n z.store.close()\n\n # create an object array using JSON\n z = self.create_array(shape=10, chunks=3, dtype=object, object_codec=JSON())\n z[0] = 'foo'\n assert z[0] == 'foo'\n # z[1] = b'bar'\n # assert z[1] == b'bar' # not supported for JSON\n z[2] = 1\n assert z[2] == 1\n z[3] = [2, 4, 6, 'baz']\n assert z[3] == [2, 4, 6, 'baz']\n z[4] = {'a': 'b', 'c': 'd'}\n assert z[4] == {'a': 'b', 'c': 'd'}\n a = z[:]\n assert a.dtype == object\n z.store.close()\n\n def test_object_arrays_vlen_text(self):\n\n data = np.array(greetings * 1000, dtype=object)\n z = self.create_array(shape=data.shape, dtype=object, object_codec=VLenUTF8())\n z[0] = 'foo'\n assert z[0] == 'foo'\n z[1] = 'bar'\n assert z[1] == 'bar'\n z[2] = 'baz'\n assert z[2] == 'baz'\n z[:] = data\n a = z[:]\n assert a.dtype == object\n assert_array_equal(data, a)\n z.store.close()\n\n # convenience API\n z = self.create_array(shape=data.shape, dtype=str)\n assert z.dtype == object\n assert isinstance(z.filters[0], VLenUTF8)\n z[:] = data\n assert_array_equal(data, z[:])\n z.store.close()\n\n z = self.create_array(shape=data.shape, dtype=object, object_codec=MsgPack())\n z[:] = data\n assert_array_equal(data, z[:])\n z.store.close()\n\n z = self.create_array(shape=data.shape, dtype=object, object_codec=JSON())\n z[:] = data\n assert_array_equal(data, z[:])\n z.store.close()\n\n z = self.create_array(shape=data.shape, dtype=object, object_codec=Pickle())\n z[:] = data\n assert_array_equal(data, z[:])\n z.store.close()\n\n z = self.create_array(shape=data.shape, dtype=object,\n object_codec=Categorize(greetings, dtype=object))\n z[:] = data\n assert_array_equal(data, z[:])\n z.store.close()\n\n def test_object_arrays_vlen_bytes(self):\n\n greetings_bytes = [g.encode('utf8') for g in greetings]\n data = np.array(greetings_bytes * 1000, dtype=object)\n\n z = self.create_array(shape=data.shape, dtype=object, object_codec=VLenBytes())\n z[0] = b'foo'\n assert z[0] == b'foo'\n z[1] = b'bar'\n assert z[1] == b'bar'\n z[2] = b'baz'\n assert z[2] == b'baz'\n z[:] = data\n a = z[:]\n assert a.dtype == object\n assert_array_equal(data, a)\n z.store.close()\n\n # convenience API\n z = self.create_array(shape=data.shape, dtype=bytes)\n assert z.dtype == object\n assert isinstance(z.filters[0], VLenBytes)\n z[:] = data\n assert_array_equal(data, z[:])\n z.store.close()\n\n z = self.create_array(shape=data.shape, dtype=object, object_codec=Pickle())\n z[:] = data\n assert_array_equal(data, z[:])\n z.store.close()\n\n def test_object_arrays_vlen_array(self):\n\n data = np.array([np.array([1, 3, 7]),\n np.array([5]),\n np.array([2, 8, 12])] * 1000, dtype=object)\n\n def compare_arrays(expected, actual, item_dtype):\n assert isinstance(actual, np.ndarray)\n assert actual.dtype == object\n assert actual.shape == expected.shape\n for ev, av in zip(expected.flat, actual.flat):\n assert isinstance(av, np.ndarray)\n assert_array_equal(ev, av)\n assert av.dtype == item_dtype\n\n codecs = VLenArray(int), VLenArray('<u4')\n for codec in codecs:\n z = self.create_array(shape=data.shape, dtype=object, object_codec=codec)\n z[0] = np.array([4, 7])\n assert_array_equal(np.array([4, 7]), z[0])\n z[:] = data\n a = z[:]\n assert a.dtype == object\n compare_arrays(data, a, codec.dtype)\n z.store.close()\n\n # convenience API\n for item_type in 'int', '<u4':\n z = self.create_array(shape=data.shape, dtype='array:{}'.format(item_type))\n assert z.dtype == object\n assert isinstance(z.filters[0], VLenArray)\n assert z.filters[0].dtype == np.dtype(item_type)\n z[:] = data\n compare_arrays(data, z[:], np.dtype(item_type))\n z.store.close()\n\n def test_object_arrays_danger(self):\n\n # do something dangerous - manually force an object array with no object codec\n z = self.create_array(shape=5, chunks=2, dtype=object, fill_value=0,\n object_codec=MsgPack())\n z._filters = None # wipe filters\n with pytest.raises(RuntimeError):\n z[0] = 'foo'\n with pytest.raises(RuntimeError):\n z[:] = 42\n z.store.close()\n\n # do something else dangerous\n data = greetings * 10\n for compressor in Zlib(1), Blosc():\n z = self.create_array(shape=len(data), chunks=30, dtype=object,\n object_codec=Categorize(greetings,\n dtype=object),\n compressor=compressor)\n z[:] = data\n v = z.view(filters=[])\n with pytest.raises(RuntimeError):\n # noinspection PyStatementEffect\n v[:]\n z.store.close()\n\n def test_object_codec_warnings(self):\n\n with pytest.warns(UserWarning):\n # provide object_codec, but not object dtype\n z = self.create_array(shape=10, chunks=5, dtype=\"i4\", object_codec=JSON())\n z.store.close()\n\n @unittest.skipIf(parse_version(np.__version__) < parse_version('1.14.0'),\n \"unsupported numpy version\")\n def test_structured_array_contain_object(self):\n\n if \"PartialRead\" in self.__class__.__name__:\n pytest.skip(\"partial reads of object arrays not supported\")\n\n # ----------- creation --------------\n\n structured_dtype = [('c_obj', object), ('c_int', int)]\n a = np.array([(b'aaa', 1),\n (b'bbb', 2)], dtype=structured_dtype)\n\n # zarr-array with structured dtype require object codec\n with pytest.raises(ValueError):\n self.create_array(shape=a.shape, dtype=structured_dtype)\n\n # create zarr-array by np-array\n za = self.create_array(shape=a.shape, dtype=structured_dtype, object_codec=Pickle())\n za[:] = a\n\n # must be equal\n assert_array_equal(a, za[:])\n\n # ---------- indexing ---------------\n\n assert za[0] == a[0]\n\n za[0] = (b'ccc', 3)\n za[1:2] = np.array([(b'ddd', 4)], dtype=structured_dtype) # ToDo: not work with list\n assert_array_equal(za[:], np.array([(b'ccc', 3), (b'ddd', 4)], dtype=structured_dtype))\n\n za['c_obj'] = [b'eee', b'fff']\n za['c_obj', 0] = b'ggg'\n assert_array_equal(za[:], np.array([(b'ggg', 3), (b'fff', 4)], dtype=structured_dtype))\n assert za['c_obj', 0] == b'ggg'\n assert za[1, 'c_int'] == 4\n\n def test_iteration_exceptions(self):\n # zero d array\n a = np.array(1, dtype=int)\n z = self.create_array(shape=a.shape, dtype=int)\n z[...] = a\n with pytest.raises(TypeError):\n # noinspection PyStatementEffect\n list(a)\n with pytest.raises(TypeError):\n # noinspection PyStatementEffect\n list(z)\n\n # input argument error handling\n a = np.array((10, 10), dtype=int)\n z = self.create_array(shape=a.shape, dtype=int)\n z[...] = a\n\n params = (\n (-1, 0),\n (0, -1),\n (0.5, 1),\n (0, 0.5)\n )\n\n for start, end in params:\n with pytest.raises(ValueError):\n # noinspection PyStatementEffect\n list(z.islice(start, end))\n\n # check behavior for start > end\n assert [] == list(z.islice(6, 5))\n\n z.store.close()\n\n def test_iter(self):\n params = (\n ((1,), (1,)),\n ((2,), (1,)),\n ((1,), (2,)),\n ((3,), (3,)),\n ((1000,), (100,)),\n ((100,), (1000,)),\n ((1, 100), (1, 1)),\n ((1, 0), (1, 1)),\n ((0, 1), (1, 1)),\n ((0, 1), (2, 1)),\n ((100, 1), (3, 1)),\n ((100, 100), (10, 10)),\n ((10, 10, 10), (3, 3, 3)),\n )\n for shape, chunks in params:\n z = self.create_array(shape=shape, chunks=chunks, dtype=int)\n a = np.arange(np.product(shape)).reshape(shape)\n z[:] = a\n for expect, actual in zip_longest(a, z):\n assert_array_equal(expect, actual)\n z.store.close()\n\n def test_islice(self):\n params = (\n ((1,), (1,), 0, 1),\n ((2,), (1,), 0, 1),\n ((1,), (2,), 0, 1),\n ((3,), (3,), 1, 2),\n ((1000,), (100,), 150, 1050),\n ((100,), (1000,), 25, 75),\n ((1, 100), (1, 1), 0, 1),\n ((100, 1), (3, 1), 56, 100),\n ((100, 100), (10, 10), 13, 99),\n ((10, 10, 10), (3, 3, 3), 2, 4),\n )\n for shape, chunks, start, end in params:\n z = self.create_array(shape=shape, chunks=chunks, dtype=int)\n a = np.arange(np.product(shape)).reshape(shape)\n z[:] = a\n end_array = min(end, a.shape[0])\n for expect, actual in zip_longest(a[start:end_array],\n z.islice(start, end)):\n assert_array_equal(expect, actual)\n if hasattr(z.store, 'close'):\n z.store.close()\n\n def test_compressors(self):\n compressors = [\n None, BZ2(), Blosc(), LZ4(), Zlib(), GZip()\n ]\n if LZMA:\n compressors.append(LZMA())\n for compressor in compressors:\n a = self.create_array(shape=1000, chunks=100, compressor=compressor)\n a[0:100] = 1\n assert np.all(a[0:100] == 1)\n a[:] = 1\n assert np.all(a[:] == 1)\n a.store.close()\n\n def test_endian(self):\n dtype = np.dtype('float32')\n a1 = self.create_array(shape=1000, chunks=100, dtype=dtype.newbyteorder('<'))\n a1[:] = 1\n x1 = a1[:]\n a2 = self.create_array(shape=1000, chunks=100, dtype=dtype.newbyteorder('>'))\n a2[:] = 1\n x2 = a2[:]\n assert_array_equal(x1, x2)\n a1.store.close()\n a2.store.close()\n\n def test_attributes(self):\n a = self.create_array(shape=10, chunks=10, dtype='i8')\n a.attrs['foo'] = 'bar'\n assert a.attrs.key in a.store\n attrs = json_loads(a.store[a.attrs.key])\n if self.version > 2:\n # in v3, attributes are in a sub-dictionary of the metadata\n attrs = attrs['attributes']\n assert 'foo' in attrs and attrs['foo'] == 'bar'\n\n a.attrs['bar'] = 'foo'\n assert a.attrs.key in a.store\n attrs = json_loads(a.store[a.attrs.key])\n if self.version > 2:\n # in v3, attributes are in a sub-dictionary of the metadata\n attrs = attrs['attributes']\n assert 'foo' in attrs and attrs['foo'] == 'bar'\n assert 'bar' in attrs and attrs['bar'] == 'foo'\n a.store.close()\n\n def test_structured_with_object(self):\n a = self.create_array(fill_value=(0.0, None),\n shape=10,\n chunks=10,\n dtype=[('x', float), ('y', object)],\n object_codec=Pickle())\n assert tuple(a[0]) == (0.0, None)\n\n\nclass TestArrayWithPath(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n store = KVStore(dict())\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n init_array(store, path='foo/bar', **kwargs)\n return Array(store, path='foo/bar', read_only=read_only,\n cache_metadata=cache_metadata, cache_attrs=cache_attrs,\n write_empty_chunks=write_empty_chunks)\n\n def test_nchunks_initialized(self):\n pass\n\n def expected(self):\n return [\n \"f710da18d45d38d4aaf2afd7fb822fdd73d02957\",\n \"1437428e69754b1e1a38bd7fc9e43669577620db\",\n \"6c530b6b9d73e108cc5ee7b6be3d552cc994bdbe\",\n \"4c0a76fb1222498e09dcd92f7f9221d6cea8b40e\",\n \"05b0663ffe1785f38d3a459dec17e57a18f254af\"\n ]\n\n def test_nbytes_stored(self):\n\n # MemoryStore as store\n z = self.create_array(shape=1000, chunks=100)\n expect_nbytes_stored = sum(buffer_size(v)\n for k, v in z.store.items()\n if k.startswith('foo/bar/'))\n assert expect_nbytes_stored == z.nbytes_stored\n z[:] = 42\n expect_nbytes_stored = sum(buffer_size(v)\n for k, v in z.store.items()\n if k.startswith('foo/bar/'))\n assert expect_nbytes_stored == z.nbytes_stored\n\n # mess with store\n z.store[z._key_prefix + 'foo'] = list(range(10))\n assert -1 == z.nbytes_stored\n\n\nclass TestArrayWithChunkStore(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n store = KVStore(dict())\n # separate chunk store\n chunk_store = KVStore(dict())\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n init_array(store, chunk_store=chunk_store, **kwargs)\n return Array(store, read_only=read_only, chunk_store=chunk_store,\n cache_metadata=cache_metadata, cache_attrs=cache_attrs,\n write_empty_chunks=write_empty_chunks)\n\n def expected(self):\n return [\n \"f710da18d45d38d4aaf2afd7fb822fdd73d02957\",\n \"1437428e69754b1e1a38bd7fc9e43669577620db\",\n \"6c530b6b9d73e108cc5ee7b6be3d552cc994bdbe\",\n \"4c0a76fb1222498e09dcd92f7f9221d6cea8b40e\",\n \"05b0663ffe1785f38d3a459dec17e57a18f254af\"\n ]\n\n def test_nbytes_stored(self):\n\n z = self.create_array(shape=1000, chunks=100)\n expect_nbytes_stored = sum(buffer_size(v) for v in z.store.values())\n expect_nbytes_stored += sum(buffer_size(v)\n for v in z.chunk_store.values())\n assert expect_nbytes_stored == z.nbytes_stored\n z[:] = 42\n expect_nbytes_stored = sum(buffer_size(v) for v in z.store.values())\n expect_nbytes_stored += sum(buffer_size(v)\n for v in z.chunk_store.values())\n assert expect_nbytes_stored == z.nbytes_stored\n\n # mess with store\n z.chunk_store[z._key_prefix + 'foo'] = list(range(10))\n assert -1 == z.nbytes_stored\n\n\nclass TestArrayWithDirectoryStore(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n path = mkdtemp()\n atexit.register(shutil.rmtree, path)\n store = DirectoryStore(path)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def test_nbytes_stored(self):\n\n # dict as store\n z = self.create_array(shape=1000, chunks=100)\n expect_nbytes_stored = sum(buffer_size(v) for v in z.store.values())\n assert expect_nbytes_stored == z.nbytes_stored\n z[:] = 42\n expect_nbytes_stored = sum(buffer_size(v) for v in z.store.values())\n assert expect_nbytes_stored == z.nbytes_stored\n\n\ndef test_array_init_from_dict():\n # initialization via non-Store MutableMapping\n store = dict()\n init_array(store, shape=100, chunks=10, dtype=\"<f8\")\n a = Array(store)\n assert isinstance(a, Array)\n assert a.store is not store\n assert isinstance(a.store, KVStore)\n\n\n@skip_test_env_var(\"ZARR_TEST_ABS\")\nclass TestArrayWithABSStore(TestArray):\n\n @staticmethod\n def absstore():\n client = abs_container()\n store = ABSStore(client=client)\n store.rmdir()\n return store\n\n def create_array(self, read_only=False, **kwargs):\n store = self.absstore()\n kwargs.setdefault('compressor', Zlib(1))\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n @pytest.mark.xfail\n def test_nbytes_stored(self):\n return super().test_nbytes_stored()\n\n @pytest.mark.skipif(sys.version_info < (3, 7), reason=\"attr not serializable in py36\")\n def test_pickle(self):\n # internal attribute on ContainerClient isn't serializable for py36 and earlier\n super().test_pickle()\n\n\nclass TestArrayWithNestedDirectoryStore(TestArrayWithDirectoryStore):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n path = mkdtemp()\n atexit.register(shutil.rmtree, path)\n store = NestedDirectoryStore(path)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def expected(self):\n return [\n \"d174aa384e660eb51c6061fc8d20850c1159141f\",\n \"125f00eea40032f16016b292f6767aa3928c00a7\",\n \"1b52ead0ed889a781ebd4db077a29e35d513c1f3\",\n \"719a88b34e362ff65df30e8f8810c1146ab72bc1\",\n \"6e0abf30daf45de51593c227fb907759ca725551\",\n ]\n\n\nclass TestArrayWithN5Store(TestArrayWithDirectoryStore):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n path = mkdtemp()\n atexit.register(shutil.rmtree, path)\n store = N5Store(path)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def test_array_0d(self):\n # test behaviour for array with 0 dimensions\n\n # setup\n a = np.zeros(())\n z = self.create_array(shape=(), dtype=a.dtype, fill_value=0)\n\n # check properties\n assert a.ndim == z.ndim\n assert a.shape == z.shape\n assert a.size == z.size\n assert a.dtype == z.dtype\n assert a.nbytes == z.nbytes\n with pytest.raises(TypeError):\n len(z)\n assert () == z.chunks\n assert 1 == z.nchunks\n assert (1,) == z.cdata_shape\n # compressor always None - no point in compressing a single value\n assert z.compressor.compressor_config is None\n\n # check __getitem__\n b = z[...]\n assert isinstance(b, np.ndarray)\n assert a.shape == b.shape\n assert a.dtype == b.dtype\n assert_array_equal(a, np.array(z))\n assert_array_equal(a, z[...])\n assert a[()] == z[()]\n with pytest.raises(IndexError):\n z[0]\n with pytest.raises(IndexError):\n z[:]\n\n # check __setitem__\n z[...] = 42\n assert 42 == z[()]\n z[()] = 43\n assert 43 == z[()]\n with pytest.raises(IndexError):\n z[0] = 42\n with pytest.raises(IndexError):\n z[:] = 42\n with pytest.raises(ValueError):\n z[...] = np.array([1, 2, 3])\n\n def test_array_1d_fill_value(self):\n nvalues = 1050\n dtype = np.int32\n for fill_value in 0, None:\n a = np.arange(nvalues, dtype=dtype)\n f = np.empty_like(a)\n f.fill(fill_value or 0)\n z = self.create_array(shape=a.shape, chunks=100, dtype=a.dtype,\n fill_value=fill_value)\n z[190:310] = a[190:310]\n\n assert_array_equal(f[:190], z[:190])\n assert_array_equal(a[190:310], z[190:310])\n assert_array_equal(f[310:], z[310:])\n\n with pytest.raises(ValueError):\n z = self.create_array(shape=(nvalues,), chunks=100, dtype=dtype,\n fill_value=1)\n\n def test_nchunks_initialized(self):\n fill_value = 0\n dtype = 'int'\n z = self.create_array(shape=100,\n chunks=10,\n fill_value=fill_value,\n dtype=dtype,\n write_empty_chunks=True)\n\n assert 0 == z.nchunks_initialized\n # manually put something into the store to confuse matters\n z.store['foo'] = b'bar'\n assert 0 == z.nchunks_initialized\n z[:] = 42\n assert 10 == z.nchunks_initialized\n # manually remove a chunk from the store\n del z.chunk_store[z._chunk_key((0,))]\n assert 9 == z.nchunks_initialized\n\n # second round of similar tests with write_empty_chunks set to\n # False\n z = self.create_array(shape=100,\n chunks=10,\n fill_value=fill_value,\n dtype=dtype,\n write_empty_chunks=False)\n z[:] = 42\n assert 10 == z.nchunks_initialized\n # manually remove a chunk from the store\n del z.chunk_store[z._chunk_key((0,))]\n assert 9 == z.nchunks_initialized\n z[:] = z.fill_value\n assert 0 == z.nchunks_initialized\n\n def test_array_order(self):\n\n # N5 only supports 'C' at the moment\n with pytest.raises(ValueError):\n self.create_array(shape=(10, 11), chunks=(10, 11), dtype='i8',\n order='F')\n\n # 1D\n a = np.arange(1050)\n z = self.create_array(shape=a.shape, chunks=100, dtype=a.dtype,\n order='C')\n assert z.order == 'C'\n assert z[:].flags.c_contiguous\n z[:] = a\n assert_array_equal(a, z[:])\n\n # 2D\n a = np.arange(10000).reshape((100, 100))\n z = self.create_array(shape=a.shape, chunks=(10, 10),\n dtype=a.dtype, order='C')\n\n assert z.order == 'C'\n assert z[:].flags.c_contiguous\n z[:] = a\n actual = z[:]\n assert_array_equal(a, actual)\n\n def test_structured_array(self):\n d = np.array([(b'aaa', 1, 4.2),\n (b'bbb', 2, 8.4),\n (b'ccc', 3, 12.6)],\n dtype=[('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])\n fill_values = None, b'', (b'zzz', 42, 16.8)\n with pytest.raises(TypeError):\n self.check_structured_array(d, fill_values)\n\n def test_structured_array_subshapes(self):\n d = np.array([(0, ((0, 1, 2), (1, 2, 3)), b'aaa'),\n (1, ((1, 2, 3), (2, 3, 4)), b'bbb'),\n (2, ((2, 3, 4), (3, 4, 5)), b'ccc')],\n dtype=[('foo', 'i8'), ('bar', '(2, 3)f4'), ('baz', 'S3')])\n fill_values = None, b'', (0, ((0, 0, 0), (1, 1, 1)), b'zzz')\n with pytest.raises(TypeError):\n self.check_structured_array(d, fill_values)\n\n def test_structured_array_nested(self):\n d = np.array([(0, (0, ((0, 1), (1, 2), (2, 3)), 0), b'aaa'),\n (1, (1, ((1, 2), (2, 3), (3, 4)), 1), b'bbb'),\n (2, (2, ((2, 3), (3, 4), (4, 5)), 2), b'ccc')],\n dtype=[('foo', 'i8'), ('bar', [('foo', 'i4'), ('bar', '(3, 2)f4'),\n ('baz', 'u1')]), ('baz', 'S3')])\n fill_values = None, b'', (0, (0, ((0, 0), (1, 1), (2, 2)), 0), b'zzz')\n with pytest.raises(TypeError):\n self.check_structured_array(d, fill_values)\n\n def test_dtypes(self):\n\n # integers\n for dtype in 'u1', 'u2', 'u4', 'u8', 'i1', 'i2', 'i4', 'i8':\n z = self.create_array(shape=10, chunks=3, dtype=dtype)\n assert z.dtype == np.dtype(dtype)\n a = np.arange(z.shape[0], dtype=dtype)\n z[:] = a\n assert_array_equal(a, z[:])\n\n # floats\n for dtype in 'f2', 'f4', 'f8':\n z = self.create_array(shape=10, chunks=3, dtype=dtype)\n assert z.dtype == np.dtype(dtype)\n a = np.linspace(0, 1, z.shape[0], dtype=dtype)\n z[:] = a\n assert_array_almost_equal(a, z[:])\n\n # check that datetime generic units are not allowed\n with pytest.raises(ValueError):\n self.create_array(shape=100, dtype='M8')\n with pytest.raises(ValueError):\n self.create_array(shape=100, dtype='m8')\n\n def test_object_arrays(self):\n\n # an object_codec is required for object arrays\n with pytest.raises(ValueError):\n self.create_array(shape=10, chunks=3, dtype=object)\n\n # an object_codec is required for object arrays, but allow to be provided via\n # filters to maintain API backwards compatibility\n with pytest.raises(ValueError):\n with pytest.warns(FutureWarning):\n self.create_array(shape=10, chunks=3, dtype=object, filters=[MsgPack()])\n\n # create an object array using an object codec\n with pytest.raises(ValueError):\n self.create_array(shape=10, chunks=3, dtype=object, object_codec=MsgPack())\n\n def test_object_arrays_vlen_text(self):\n\n data = np.array(greetings * 1000, dtype=object)\n\n with pytest.raises(ValueError):\n self.create_array(shape=data.shape, dtype=object, object_codec=VLenUTF8())\n\n # convenience API\n with pytest.raises(ValueError):\n self.create_array(shape=data.shape, dtype=str)\n\n def test_object_arrays_vlen_bytes(self):\n\n greetings_bytes = [g.encode('utf8') for g in greetings]\n data = np.array(greetings_bytes * 1000, dtype=object)\n\n with pytest.raises(ValueError):\n self.create_array(shape=data.shape, dtype=object, object_codec=VLenBytes())\n\n # convenience API\n with pytest.raises(ValueError):\n self.create_array(shape=data.shape, dtype=bytes)\n\n def test_object_arrays_vlen_array(self):\n\n data = np.array([np.array([1, 3, 7]),\n np.array([5]),\n np.array([2, 8, 12])] * 1000, dtype=object)\n\n codecs = VLenArray(int), VLenArray('<u4')\n for codec in codecs:\n with pytest.raises(ValueError):\n self.create_array(shape=data.shape, dtype=object, object_codec=codec)\n\n # convenience API\n for item_type in 'int', '<u4':\n with pytest.raises(ValueError):\n self.create_array(shape=data.shape, dtype='array:{}'.format(item_type))\n\n def test_object_arrays_danger(self):\n # Cannot hacking out object codec as N5 doesn't allow object codecs\n pass\n\n def test_structured_with_object(self):\n # Cannot hacking out object codec as N5 doesn't allow object codecs\n pass\n\n def test_structured_array_contain_object(self):\n # Cannot hacking out object codec as N5 doesn't allow object codecs\n pass\n\n def test_attrs_n5_keywords(self):\n z = self.create_array(shape=(1050,), chunks=100, dtype='i4')\n for k in n5_keywords:\n with pytest.warns(UserWarning):\n z.attrs[k] = \"\"\n\n def test_compressors(self):\n compressors = [\n None, BZ2(), Zlib(), GZip()\n ]\n if LZMA:\n compressors.append(LZMA())\n compressors.append(LZMA(preset=1))\n compressors.append(LZMA(preset=6))\n for compressor in compressors:\n a1 = self.create_array(shape=1000, chunks=100, compressor=compressor)\n a1[0:100] = 1\n assert np.all(a1[0:100] == 1)\n a1[:] = 1\n assert np.all(a1[:] == 1)\n\n compressors_warn = [\n Blosc()\n ]\n if LZMA:\n compressors_warn.append(LZMA(2)) # Try lzma.FORMAT_ALONE, which N5 doesn't support.\n for compressor in compressors_warn:\n with pytest.warns(RuntimeWarning):\n a2 = self.create_array(shape=1000, chunks=100, compressor=compressor)\n a2[0:100] = 1\n assert np.all(a2[0:100] == 1)\n a2[:] = 1\n assert np.all(a2[:] == 1)\n\n def expected(self):\n return [\n '4e9cf910000506455f82a70938a272a3fce932e5',\n 'f9d4cbf1402901f63dea7acf764d2546e4b6aa38',\n '1d8199f5f7b70d61aa0d29cc375212c3df07d50a',\n '874880f91aa6736825584509144afe6b06b0c05c',\n 'e2258fedc74752196a8c8383db49e27193c995e2',\n ]\n\n\[email protected](have_fsspec is False, reason=\"needs fsspec\")\nclass TestArrayWithN5FSStore(TestArrayWithN5Store):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n path = mkdtemp()\n atexit.register(shutil.rmtree, path)\n store = N5FSStore(path)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n kwargs.setdefault('compressor', Zlib(1))\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n\nclass TestArrayWithDBMStore(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n path = mktemp(suffix='.anydbm')\n atexit.register(atexit_rmglob, path + '*')\n store = DBMStore(path, flag='n')\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_attrs=cache_attrs,\n cache_metadata=cache_metadata, write_empty_chunks=write_empty_chunks)\n\n def test_nbytes_stored(self):\n pass # not implemented\n\n\nclass TestArrayWithDBMStoreBerkeleyDB(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n bsddb3 = pytest.importorskip(\"bsddb3\")\n path = mktemp(suffix='.dbm')\n atexit.register(os.remove, path)\n store = DBMStore(path, flag='n', open=bsddb3.btopen)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def test_nbytes_stored(self):\n pass # not implemented\n\n\nclass TestArrayWithLMDBStore(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n pytest.importorskip(\"lmdb\")\n path = mktemp(suffix='.lmdb')\n atexit.register(atexit_rmtree, path)\n store = LMDBStore(path, buffers=True)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def test_store_has_bytes_values(self):\n pass # returns values as memoryviews/buffers instead of bytes\n\n def test_nbytes_stored(self):\n pass # not implemented\n\n\nclass TestArrayWithLMDBStoreNoBuffers(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n pytest.importorskip(\"lmdb\")\n path = mktemp(suffix='.lmdb')\n atexit.register(atexit_rmtree, path)\n store = LMDBStore(path, buffers=False)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def test_nbytes_stored(self):\n pass # not implemented\n\n\nclass TestArrayWithSQLiteStore(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n pytest.importorskip(\"sqlite3\")\n path = mktemp(suffix='.db')\n atexit.register(atexit_rmtree, path)\n store = SQLiteStore(path)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def test_nbytes_stored(self):\n pass # not implemented\n\n\nclass TestArrayWithNoCompressor(TestArray):\n\n def create_array(self, read_only=False, **kwargs):\n store = KVStore(dict())\n kwargs.setdefault('compressor', None)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def expected(self):\n return [\n \"d3da3d485de4a5fcc6d91f9dfc6a7cba9720c561\",\n \"443b8dee512e42946cb63ff01d28e9bee8105a5f\",\n \"b75eb90f68aa8ee1e29f2c542e851d3945066c54\",\n \"42b6ae0d50ec361628736ab7e68fe5fefca22136\",\n \"a0535f31c130f5e5ac66ba0713d1c1ceaebd089b\",\n ]\n\n\nclass TestArrayWithBZ2Compressor(TestArray):\n\n def create_array(self, read_only=False, **kwargs):\n store = KVStore(dict())\n compressor = BZ2(level=1)\n kwargs.setdefault('compressor', compressor)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def expected(self):\n return [\n \"33141032439fb1df5e24ad9891a7d845b6c668c8\",\n \"44d719da065c88a412d609a5500ff41e07b331d6\",\n \"37c7c46e5730bba37da5e518c9d75f0d774c5098\",\n \"1e1bcaac63e4ef3c4a68f11672537131c627f168\",\n \"86d7b9bf22dccbeaa22f340f38be506b55e76ff2\",\n ]\n\n\nclass TestArrayWithBloscCompressor(TestArray):\n\n def create_array(self, read_only=False, **kwargs):\n store = KVStore(dict())\n compressor = Blosc(cname='zstd', clevel=1, shuffle=1)\n kwargs.setdefault('compressor', compressor)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def expected(self):\n return [\n \"7ff2ae8511eac915fad311647c168ccfe943e788\",\n \"962705c861863495e9ccb7be7735907aa15e85b5\",\n \"74ed339cfe84d544ac023d085ea0cd6a63f56c4b\",\n \"90e30bdab745a9641cd0eb605356f531bc8ec1c3\",\n \"95d40c391f167db8b1290e3c39d9bf741edacdf6\",\n ]\n\n\ntry:\n from numcodecs import LZMA\nexcept ImportError: # pragma: no cover\n LZMA = None\n\n\[email protected](LZMA is None, 'LZMA codec not available')\nclass TestArrayWithLZMACompressor(TestArray):\n\n def create_array(self, read_only=False, **kwargs):\n store = KVStore(dict())\n compressor = LZMA(preset=1)\n kwargs.setdefault('compressor', compressor)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def expected(self):\n return [\n \"93ecaa530a1162a9d48a3c1dcee4586ccfc59bae\",\n \"04a9755a0cd638683531b7816c7fa4fbb6f577f2\",\n \"9de97b5c49b38e68583ed701d7e8f4c94b6a8406\",\n \"cde499f3dc945b4e97197ff8e3cf8188a1262c35\",\n \"e2cf3afbf66ad0e28a2b6b68b1b07817c69aaee2\",\n ]\n\n\nclass TestArrayWithFilters(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n store = KVStore(dict())\n dtype = kwargs.get('dtype')\n filters = [\n Delta(dtype=dtype),\n FixedScaleOffset(dtype=dtype, scale=1, offset=0),\n ]\n kwargs.setdefault('filters', filters)\n compressor = Zlib(1)\n kwargs.setdefault('compressor', compressor)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_attrs=cache_attrs,\n cache_metadata=cache_metadata, write_empty_chunks=write_empty_chunks)\n\n def expected(self):\n return [\n \"b80367c5599d47110d42bd8886240c2f46620dba\",\n \"95a7b2471225e73199c9716d21e8d3dd6e5f6f2a\",\n \"7300f1eb130cff5891630038fd99c28ef23d3a01\",\n \"c649ad229bc5720258b934ea958570c2f354c2eb\",\n \"62fc9236d78af18a5ec26c12eea1d33bce52501e\",\n ]\n\n def test_astype_no_filters(self):\n shape = (100,)\n dtype = np.dtype(np.int8)\n astype = np.dtype(np.float32)\n\n store = KVStore(dict())\n init_array(store, shape=shape, chunks=10, dtype=dtype)\n\n data = np.arange(np.prod(shape), dtype=dtype).reshape(shape)\n\n z1 = Array(store)\n z1[...] = data\n z2 = z1.astype(astype)\n\n expected = data.astype(astype)\n assert_array_equal(expected, z2)\n assert z2.read_only\n\n def test_astype(self):\n shape = (100,)\n chunks = (10,)\n\n dtype = np.dtype(np.int8)\n astype = np.dtype(np.float32)\n\n data = np.arange(np.prod(shape), dtype=dtype).reshape(shape)\n\n z1 = self.create_array(shape=shape, chunks=chunks, dtype=dtype)\n z1[...] = data\n z2 = z1.astype(astype)\n\n expected = data.astype(astype)\n assert_array_equal(expected, z2)\n\n def test_array_dtype_shape(self):\n # skip this one, cannot do delta on unstructured array\n pass\n\n def test_structured_array(self):\n # skip this one, cannot do delta on structured array\n pass\n\n def test_structured_array_subshapes(self):\n # skip this one, cannot do delta on structured array\n pass\n\n def test_structured_array_nested(self):\n # skip this one, cannot do delta on structured array\n pass\n\n def test_dtypes(self):\n # skip this one, delta messes up floats\n pass\n\n def test_object_arrays(self):\n # skip this one, cannot use delta with objects\n pass\n\n def test_object_arrays_vlen_text(self):\n # skip this one, cannot use delta with objects\n pass\n\n def test_object_arrays_vlen_bytes(self):\n # skip this one, cannot use delta with objects\n pass\n\n def test_object_arrays_vlen_array(self):\n # skip this one, cannot use delta with objects\n pass\n\n def test_object_arrays_danger(self):\n # skip this one, cannot use delta with objects\n pass\n\n def test_structured_array_contain_object(self):\n # skip this one, cannot use delta on structured array\n pass\n\n\n# custom store, does not support getsize()\nclass CustomMapping:\n\n def __init__(self):\n self.inner = KVStore(dict())\n\n def __iter__(self):\n return iter(self.keys())\n\n def keys(self):\n return self.inner.keys()\n\n def values(self):\n return self.inner.values()\n\n def get(self, item, default=None):\n try:\n return self.inner[item]\n except KeyError:\n return default\n\n def __getitem__(self, item):\n return self.inner[item]\n\n def __setitem__(self, item, value):\n self.inner[item] = ensure_bytes(value)\n\n def __delitem__(self, key):\n del self.inner[key]\n\n def __contains__(self, item):\n return item in self.inner\n\n\nclass TestArrayWithCustomMapping(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n store = CustomMapping()\n kwargs.setdefault('compressor', Zlib(1))\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def test_nbytes_stored(self):\n z = self.create_array(shape=1000, chunks=100)\n assert 245 == z.nbytes_stored\n z[:] = 42\n assert 515 == z.nbytes_stored\n\n\nclass TestArrayNoCache(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n store = KVStore(dict())\n kwargs.setdefault('compressor', Zlib(level=1))\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def test_cache_metadata(self):\n a1 = self.create_array(shape=100, chunks=10, dtype='i1', cache_metadata=False)\n path = None if self.version == 2 else a1.path\n a2 = Array(a1.store, path=path, cache_metadata=True)\n assert a1.shape == a2.shape\n assert a1.size == a2.size\n assert a1.nbytes == a2.nbytes\n assert a1.nchunks == a2.nchunks\n\n # a1 is not caching so *will* see updates made via other objects\n a2.resize(200)\n assert (200,) == a2.shape\n assert 200 == a2.size\n assert 200 == a2.nbytes\n assert 20 == a2.nchunks\n assert a1.shape == a2.shape\n assert a1.size == a2.size\n assert a1.nbytes == a2.nbytes\n assert a1.nchunks == a2.nchunks\n\n a2.append(np.zeros(100))\n assert (300,) == a2.shape\n assert 300 == a2.size\n assert 300 == a2.nbytes\n assert 30 == a2.nchunks\n assert a1.shape == a2.shape\n assert a1.size == a2.size\n assert a1.nbytes == a2.nbytes\n assert a1.nchunks == a2.nchunks\n\n # a2 is caching so *will not* see updates made via other objects\n a1.resize(400)\n assert (400,) == a1.shape\n assert 400 == a1.size\n assert 400 == a1.nbytes\n assert 40 == a1.nchunks\n assert (300,) == a2.shape\n assert 300 == a2.size\n assert 300 == a2.nbytes\n assert 30 == a2.nchunks\n\n def test_cache_attrs(self):\n a1 = self.create_array(shape=100, chunks=10, dtype='i1', cache_attrs=False)\n path = None if self.version == 2 else 'arr1'\n a2 = Array(a1.store, path=path, cache_attrs=True)\n assert a1.attrs.asdict() == a2.attrs.asdict()\n\n # a1 is not caching so *will* see updates made via other objects\n a2.attrs['foo'] = 'xxx'\n a2.attrs['bar'] = 42\n assert a1.attrs.asdict() == a2.attrs.asdict()\n\n # a2 is caching so *will not* see updates made via other objects\n a1.attrs['foo'] = 'yyy'\n assert 'yyy' == a1.attrs['foo']\n assert 'xxx' == a2.attrs['foo']\n\n def test_object_arrays_danger(self):\n # skip this one as it only works if metadata are cached\n pass\n\n\nclass TestArrayWithStoreCache(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n store = LRUStoreCache(dict(), max_size=None)\n kwargs.setdefault('compressor', Zlib(level=1))\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def test_store_has_bytes_values(self):\n # skip as the cache has no control over how the store provides values\n pass\n\n\[email protected](have_fsspec is False, reason=\"needs fsspec\")\nclass TestArrayWithFSStore(TestArray):\n @staticmethod\n def create_array(read_only=False, **kwargs):\n path = mkdtemp()\n atexit.register(shutil.rmtree, path)\n key_separator = kwargs.pop('key_separator', \".\")\n store = FSStore(path, key_separator=key_separator, auto_mkdir=True)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault('compressor', Blosc())\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def expected(self):\n return [\n \"ab753fc81df0878589535ca9bad2816ba88d91bc\",\n \"c16261446f9436b1e9f962e57ce3e8f6074abe8a\",\n \"c2ef3b2fb2bc9dcace99cd6dad1a7b66cc1ea058\",\n \"6e52f95ac15b164a8e96843a230fcee0e610729b\",\n \"091fa99bc60706095c9ce30b56ce2503e0223f56\",\n ]\n\n\[email protected](have_fsspec is False, reason=\"needs fsspec\")\nclass TestArrayWithFSStorePartialRead(TestArray):\n @staticmethod\n def create_array(read_only=False, **kwargs):\n path = mkdtemp()\n atexit.register(shutil.rmtree, path)\n store = FSStore(path)\n cache_metadata = kwargs.pop(\"cache_metadata\", True)\n cache_attrs = kwargs.pop(\"cache_attrs\", True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault(\"compressor\", Blosc(blocksize=256))\n init_array(store, **kwargs)\n return Array(\n store,\n read_only=read_only,\n cache_metadata=cache_metadata,\n cache_attrs=cache_attrs,\n partial_decompress=True,\n write_empty_chunks=write_empty_chunks\n )\n\n def expected(self):\n return [\n \"dd7577d645c38767cf6f6d1ef8fd64002883a014\",\n \"aa0de9892cf1ed3cda529efbf3233720b84489b7\",\n \"e6191c44cf958576c29c41cef0f55b028a4dbdff\",\n \"88adeeabb819feecccadf50152293dbb42f9107e\",\n \"1426e084427f9920e29c9ec81b663d1005849455\",\n ]\n\n def test_non_cont(self):\n z = self.create_array(shape=(500, 500, 500), chunks=(50, 50, 50), dtype=\"<i4\")\n z[:, :, :] = 1\n # actually go through the partial read by accessing a single item\n assert z[0, :, 0].any()\n\n def test_read_nitems_less_than_blocksize_from_multiple_chunks(self):\n '''Tests to make sure decompression doesn't fail when `nitems` is\n less than a compressed block size, but covers multiple blocks\n '''\n z = self.create_array(shape=1000000, chunks=100_000)\n z[40_000:80_000] = 1\n path = None if self.version == 2 else z.path\n b = Array(z.store, path=path, read_only=True, partial_decompress=True)\n assert (b[40_000:80_000] == 1).all()\n\n def test_read_from_all_blocks(self):\n '''Tests to make sure `PartialReadBuffer.read_part` doesn't fail when\n stop isn't in the `start_points` array\n '''\n z = self.create_array(shape=1000000, chunks=100_000)\n z[2:99_000] = 1\n path = None if self.version == 2 else z.path\n b = Array(z.store, path=path, read_only=True, partial_decompress=True)\n assert (b[2:99_000] == 1).all()\n\n\[email protected](have_fsspec is False, reason=\"needs fsspec\")\nclass TestArrayWithFSStoreNested(TestArray):\n\n @staticmethod\n def create_array(read_only=False, **kwargs):\n path = mkdtemp()\n atexit.register(shutil.rmtree, path)\n key_separator = kwargs.pop('key_separator', \"/\")\n store = FSStore(path, key_separator=key_separator, auto_mkdir=True)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault('compressor', Blosc())\n init_array(store, **kwargs)\n return Array(store, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def expected(self):\n return [\n \"94884f29b41b9beb8fc99ad7bf9c0cbf0f2ab3c9\",\n \"077aa3bd77b8d354f8f6c15dce5ae4f545788a72\",\n \"22be95d83c097460adb339d80b2d7fe19c513c16\",\n \"85131cec526fa46938fd2c4a6083a58ee11037ea\",\n \"c3167010c162c6198cb2bf3c1da2c46b047c69a1\",\n ]\n\n\[email protected](have_fsspec is False, reason=\"needs fsspec\")\nclass TestArrayWithFSStoreNestedPartialRead(TestArray):\n @staticmethod\n def create_array(read_only=False, **kwargs):\n path = mkdtemp()\n atexit.register(shutil.rmtree, path)\n key_separator = kwargs.pop('key_separator', \"/\")\n store = FSStore(path, key_separator=key_separator, auto_mkdir=True)\n cache_metadata = kwargs.pop(\"cache_metadata\", True)\n cache_attrs = kwargs.pop(\"cache_attrs\", True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault(\"compressor\", Blosc())\n init_array(store, **kwargs)\n return Array(\n store,\n read_only=read_only,\n cache_metadata=cache_metadata,\n cache_attrs=cache_attrs,\n partial_decompress=True,\n write_empty_chunks=write_empty_chunks\n )\n\n def expected(self):\n return [\n \"94884f29b41b9beb8fc99ad7bf9c0cbf0f2ab3c9\",\n \"077aa3bd77b8d354f8f6c15dce5ae4f545788a72\",\n \"22be95d83c097460adb339d80b2d7fe19c513c16\",\n \"85131cec526fa46938fd2c4a6083a58ee11037ea\",\n \"c3167010c162c6198cb2bf3c1da2c46b047c69a1\",\n ]\n\n def test_non_cont(self):\n z = self.create_array(shape=(500, 500, 500), chunks=(50, 50, 50), dtype=\"<i4\")\n z[:, :, :] = 1\n # actually go through the partial read by accessing a single item\n assert z[0, :, 0].any()\n\n def test_read_nitems_less_than_blocksize_from_multiple_chunks(self):\n '''Tests to make sure decompression doesn't fail when `nitems` is\n less than a compressed block size, but covers multiple blocks\n '''\n z = self.create_array(shape=1000000, chunks=100_000)\n z[40_000:80_000] = 1\n path = None if self.version == 2 else z.path\n b = Array(z.store, path=path, read_only=True, partial_decompress=True)\n assert (b[40_000:80_000] == 1).all()\n\n def test_read_from_all_blocks(self):\n '''Tests to make sure `PartialReadBuffer.read_part` doesn't fail when\n stop isn't in the `start_points` array\n '''\n z = self.create_array(shape=1000000, chunks=100_000)\n z[2:99_000] = 1\n path = None if self.version == 2 else z.path\n b = Array(z.store, path=path, read_only=True, partial_decompress=True)\n assert (b[2:99_000] == 1).all()\n\n\n####\n# StoreV3 test classes inheriting from the above below this point\n####\n\n# Start with TestArrayWithPathV3 not TestArrayV3 since path must be supplied\n\n\nclass TestArrayV3(unittest.TestCase):\n\n version = 3\n\n def test_array_init(self):\n\n # normal initialization\n store = KVStoreV3(dict())\n with pytest.raises(ValueError):\n # cannot init_array for v3 without a path\n init_array(store, shape=100, chunks=10, dtype=\"<f8\")\n\n init_array(store, path='x', shape=100, chunks=10, dtype=\"<f8\")\n with pytest.raises(ValueError):\n # cannot initialize a v3 array without a path\n Array(store)\n\n def test_prefix_exceptions(self):\n store = KVStoreV3(dict())\n with pytest.raises(ValueError):\n _prefix_to_array_key(store, '')\n\n with pytest.raises(ValueError):\n _prefix_to_group_key(store, '')\n\n with pytest.raises(ValueError):\n _prefix_to_attrs_key(store, '')\n\n\nclass TestArrayWithPathV3(TestArrayWithPath):\n\n version = 3\n\n @staticmethod\n def create_array(array_path='arr1', read_only=False, **kwargs):\n store = KVStoreV3(dict())\n kwargs.setdefault('compressor', Zlib(level=1))\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n init_array(store, path=array_path, **kwargs)\n return Array(store, path=array_path, read_only=read_only,\n cache_metadata=cache_metadata, cache_attrs=cache_attrs,\n write_empty_chunks=write_empty_chunks)\n\n def test_array_init(self):\n\n # should not be able to initialize without a path in V3\n store = KVStoreV3(dict())\n with pytest.raises(ValueError):\n init_array(store, shape=100, chunks=10, dtype=\"<f8\")\n\n # initialize at path\n store = KVStoreV3(dict())\n path = 'foo/bar'\n init_array(store, shape=100, chunks=10, path=path, dtype='<f8')\n a = Array(store, path=path)\n assert not a.is_view\n assert isinstance(a, Array)\n assert (100,) == a.shape\n assert (10,) == a.chunks\n assert path == a.path # TODO: should this include meta/root?\n assert '/' + path == a.name # TODO: should this include meta/root?\n assert 'bar' == a.basename\n assert store is a.store\n assert \"968dccbbfc0139f703ead2fd1d503ad6e44db307\" == a.hexdigest()\n\n # store not initialized\n store = KVStoreV3(dict())\n with pytest.raises(ValueError):\n Array(store)\n\n # group is in the way\n store = KVStoreV3(dict())\n path = 'baz'\n init_group(store, path=path)\n # can't open with an uninitialized array\n with pytest.raises(ArrayNotFoundError):\n Array(store, path=path)\n # can't open at same path as an existing group\n with pytest.raises(ContainsGroupError):\n init_array(store, shape=100, chunks=10, path=path, dtype='<f8')\n group_key = meta_root + path + '.group.json'\n assert group_key in store\n del store[group_key]\n init_array(store, shape=100, chunks=10, path=path, dtype='<f8')\n Array(store, path=path)\n assert group_key not in store\n assert (meta_root + path + '.array.json') in store\n\n def test_array_no_path(self):\n # passing path=None to init_array will raise an exception\n with pytest.raises(ValueError):\n self.create_array(shape=1000, chunks=100, array_path=None)\n\n def expected(self):\n return [\n \"73ab8ace56719a5c9308c3754f5e2d57bc73dc20\",\n \"5fb3d02b8f01244721582929b3cad578aec5cea5\",\n \"26b098bedb640846e18dc2fbc1c27684bb02b532\",\n \"799a458c287d431d747bec0728987ca4fe764549\",\n \"c780221df84eb91cb62f633f12d3f1eaa9cee6bd\",\n ]\n\n def test_nbytes_stored(self):\n\n # dict as store\n z = self.create_array(shape=1000, chunks=100)\n expect_nbytes_stored = sum(buffer_size(v) for k, v in z.store.items() if k != 'zarr.json')\n assert expect_nbytes_stored == z.nbytes_stored\n z[:] = 42\n expect_nbytes_stored = sum(buffer_size(v) for k, v in z.store.items() if k != 'zarr.json')\n assert expect_nbytes_stored == z.nbytes_stored\n assert z.nchunks_initialized == 10 # TODO: added temporarily for testing, can remove\n\n # mess with store\n if not isinstance(z.store, (LRUStoreCacheV3, FSStoreV3)):\n z.store[data_root + z._key_prefix + 'foo'] = list(range(10))\n assert -1 == z.nbytes_stored\n\n z.store.close()\n\n def test_view(self):\n\n # dict as store\n z = self.create_array(shape=1005, chunks=100, dtype=float)\n\n # with with different dtype\n x = z.view(dtype=bytes)\n assert x.is_view\n assert x.dtype == bytes\n\n new_shape = (1, z.shape[0])\n x = z.view(shape=new_shape)\n assert x.is_view\n assert x.shape == new_shape\n\n x = z.view(chunks=10)\n assert x.is_view\n assert x.chunks == (10,)\n\n x = z.view(fill_value=5)\n assert x.is_view\n assert x[-1] == 5\n\n with pytest.raises(PermissionError):\n x.fill_value = 8\n\n def test_nchunks_initialized(self):\n # copied from TestArray so the empty version from TestArrayWithPath is\n # not used\n\n z = self.create_array(shape=100, chunks=10)\n assert 0 == z.nchunks_initialized\n # manually put something into the store to confuse matters\n z.store['meta/root/foo'] = b'bar'\n assert 0 == z.nchunks_initialized\n z[:] = 42\n assert 10 == z.nchunks_initialized\n\n z.store.close()\n\n\nclass TestArrayWithChunkStoreV3(TestArrayWithChunkStore, TestArrayWithPathV3):\n\n @staticmethod\n def create_array(array_path='arr1', read_only=False, **kwargs):\n store = KVStoreV3(dict())\n # separate chunk store\n chunk_store = KVStoreV3(dict())\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n init_array(store, path=array_path, chunk_store=chunk_store, **kwargs)\n return Array(store, path=array_path, read_only=read_only,\n chunk_store=chunk_store, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def expected(self):\n return [\n '1509abec4285494b61cd3e8d21f44adc3cf8ddf6',\n '7cfb82ec88f7ecb7ab20ae3cb169736bc76332b8',\n 'b663857bb89a8ab648390454954a9cdd453aa24b',\n '21e90fa927d09cbaf0e3b773130e2dc05d18ff9b',\n 'e8c1fdd18b5c2ee050b59d0c8c95d07db642459c',\n ]\n\n def test_nbytes_stored(self):\n\n z = self.create_array(shape=1000, chunks=100)\n expect_nbytes_stored = sum(buffer_size(v) for k, v in z.store.items() if k != 'zarr.json')\n expect_nbytes_stored += sum(buffer_size(v)\n for k, v in z.chunk_store.items() if k != 'zarr.json')\n assert expect_nbytes_stored == z.nbytes_stored\n z[:] = 42\n expect_nbytes_stored = sum(buffer_size(v) for k, v in z.store.items() if k != 'zarr.json')\n expect_nbytes_stored += sum(buffer_size(v)\n for k, v in z.chunk_store.items() if k != 'zarr.json')\n assert expect_nbytes_stored == z.nbytes_stored\n\n # mess with store\n z.chunk_store[data_root + z._key_prefix + 'foo'] = list(range(10))\n assert -1 == z.nbytes_stored\n\n\nclass TestArrayWithDirectoryStoreV3(TestArrayWithDirectoryStore, TestArrayWithPathV3):\n\n @staticmethod\n def create_array(array_path='arr1', read_only=False, **kwargs):\n path = mkdtemp()\n atexit.register(shutil.rmtree, path)\n store = DirectoryStoreV3(path)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, path=array_path, **kwargs)\n return Array(store, path=array_path, read_only=read_only,\n cache_metadata=cache_metadata, cache_attrs=cache_attrs,\n write_empty_chunks=write_empty_chunks)\n\n def test_nbytes_stored(self):\n # dict as store\n z = self.create_array(shape=1000, chunks=100)\n expect_nbytes_stored = sum(buffer_size(v) for k, v in z.store.items() if k != 'zarr.json')\n assert expect_nbytes_stored == z.nbytes_stored\n z[:] = 42\n expect_nbytes_stored = sum(buffer_size(v) for k, v in z.store.items() if k != 'zarr.json')\n assert expect_nbytes_stored == z.nbytes_stored\n\n\n@skip_test_env_var(\"ZARR_TEST_ABS\")\nclass TestArrayWithABSStoreV3(TestArrayWithABSStore, TestArrayWithPathV3):\n\n @staticmethod\n def absstore():\n client = abs_container()\n store = ABSStoreV3(client=client)\n store.rmdir()\n return store\n\n def create_array(self, array_path='arr1', read_only=False, **kwargs):\n store = self.absstore()\n kwargs.setdefault('compressor', Zlib(1))\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n init_array(store, path=array_path, **kwargs)\n return Array(store, path=array_path, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n\n# TODO: TestArrayWithN5StoreV3\n# class TestArrayWithN5StoreV3(TestArrayWithDirectoryStoreV3):\n\n\nclass TestArrayWithDBMStoreV3(TestArrayWithDBMStore, TestArrayWithPathV3):\n\n @staticmethod\n def create_array(array_path='arr1', read_only=False, **kwargs):\n path = mktemp(suffix='.anydbm')\n atexit.register(atexit_rmglob, path + '*')\n store = DBMStoreV3(path, flag='n')\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, path=array_path, **kwargs)\n return Array(store, path=array_path, read_only=read_only, cache_attrs=cache_attrs,\n cache_metadata=cache_metadata, write_empty_chunks=write_empty_chunks)\n\n def test_nbytes_stored(self):\n pass # not implemented\n\n\nclass TestArrayWithDBMStoreV3BerkeleyDB(TestArrayWithDBMStoreBerkeleyDB, TestArrayWithPathV3):\n\n @staticmethod\n def create_array(array_path='arr1', read_only=False, **kwargs):\n bsddb3 = pytest.importorskip(\"bsddb3\")\n path = mktemp(suffix='.dbm')\n atexit.register(os.remove, path)\n store = DBMStoreV3(path, flag='n', open=bsddb3.btopen)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, path=array_path, **kwargs)\n return Array(store, path=array_path, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def test_nbytes_stored(self):\n pass # not implemented\n\n\nclass TestArrayWithLMDBStoreV3(TestArrayWithLMDBStore, TestArrayWithPathV3):\n\n @staticmethod\n def create_array(array_path='arr1', read_only=False, **kwargs):\n pytest.importorskip(\"lmdb\")\n path = mktemp(suffix='.lmdb')\n atexit.register(atexit_rmtree, path)\n store = LMDBStoreV3(path, buffers=True)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, path=array_path, **kwargs)\n return Array(store, path=array_path, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def test_store_has_bytes_values(self):\n pass # returns values as memoryviews/buffers instead of bytes\n\n def test_nbytes_stored(self):\n pass # not implemented\n\n\nclass TestArrayWithLMDBStoreV3NoBuffers(TestArrayWithLMDBStoreNoBuffers, TestArrayWithPathV3):\n\n @staticmethod\n def create_array(array_path='arr1', read_only=False, **kwargs):\n pytest.importorskip(\"lmdb\")\n path = mktemp(suffix='.lmdb')\n atexit.register(atexit_rmtree, path)\n store = LMDBStoreV3(path, buffers=False)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, path=array_path, **kwargs)\n return Array(store, path=array_path, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def test_nbytes_stored(self):\n pass # not implemented\n\n\nclass TestArrayWithSQLiteStoreV3(TestArrayWithPathV3, TestArrayWithSQLiteStore):\n\n @staticmethod\n def create_array(array_path='arr1', read_only=False, **kwargs):\n pytest.importorskip(\"sqlite3\")\n path = mktemp(suffix='.db')\n atexit.register(atexit_rmtree, path)\n store = SQLiteStoreV3(path)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault('compressor', Zlib(1))\n init_array(store, path=array_path, **kwargs)\n return Array(store, path=array_path, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def test_nbytes_stored(self):\n pass # not implemented\n\n\n# skipped adding V3 equivalents for compressors (no change in v3):\n# TestArrayWithNoCompressor\n# TestArrayWithBZ2Compressor\n# TestArrayWithBloscCompressor\n# TestArrayWithLZMACompressor\n\n# skipped test with filters (v3 protocol removed filters)\n# TestArrayWithFilters\n\n\n# custom store, does not support getsize()\n# Note: this custom mapping doesn't actually have all methods in the\n# v3 spec (e.g. erase), but they aren't needed here.\nclass CustomMappingV3(StoreV3):\n\n def __init__(self):\n self.inner = KVStoreV3(dict())\n\n def __iter__(self):\n return iter(self.keys())\n\n def __len__(self):\n return len(self.inner)\n\n def keys(self):\n return self.inner.keys()\n\n def values(self):\n return self.inner.values()\n\n def get(self, item, default=None):\n try:\n return self.inner[item]\n except KeyError:\n return default\n\n def __getitem__(self, item):\n return self.inner[item]\n\n def __setitem__(self, item, value):\n self.inner[item] = ensure_bytes(value)\n\n def __delitem__(self, key):\n del self.inner[key]\n\n def __contains__(self, item):\n return item in self.inner\n\n\nclass TestArrayWithCustomMappingV3(TestArrayWithPathV3, TestArrayWithCustomMapping):\n\n @staticmethod\n def create_array(array_path='arr1', read_only=False, **kwargs):\n store = CustomMappingV3()\n kwargs.setdefault('compressor', Zlib(1))\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n init_array(store, path=array_path, **kwargs)\n return Array(store, path=array_path, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def test_nbytes_stored(self):\n z = self.create_array(shape=1000, chunks=100)\n expect_nbytes_stored = sum(buffer_size(v) for k, v in z.store.items() if k != 'zarr.json')\n assert expect_nbytes_stored == z.nbytes_stored\n z[:] = 42\n expect_nbytes_stored = sum(buffer_size(v) for k, v in z.store.items() if k != 'zarr.json')\n assert expect_nbytes_stored == z.nbytes_stored\n\n def test_len(self):\n\n # dict as store\n z = self.create_array(shape=1000, chunks=100)\n assert len(z._store) == 2\n\n\nclass TestArrayNoCacheV3(TestArrayWithPathV3, TestArrayNoCache):\n\n @staticmethod\n def create_array(array_path='arr1', read_only=False, **kwargs):\n store = KVStoreV3(dict())\n kwargs.setdefault('compressor', Zlib(level=1))\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n init_array(store, path=array_path, **kwargs)\n return Array(store, path=array_path, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def test_object_arrays_danger(self):\n # skip this one as it only works if metadata are cached\n pass\n\n\nclass TestArrayWithStoreCacheV3(TestArrayWithPathV3, TestArrayWithStoreCache):\n\n @staticmethod\n def create_array(array_path='arr1', read_only=False, **kwargs):\n store = LRUStoreCacheV3(dict(), max_size=None)\n kwargs.setdefault('compressor', Zlib(level=1))\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n init_array(store, path=array_path, **kwargs)\n return Array(store, path=array_path, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def test_store_has_bytes_values(self):\n # skip as the cache has no control over how the store provides values\n pass\n\n\[email protected](have_fsspec is False, reason=\"needs fsspec\")\nclass TestArrayWithFSStoreV3(TestArrayWithPathV3, TestArrayWithFSStore):\n @staticmethod\n def create_array(array_path='arr1', read_only=False, **kwargs):\n path = mkdtemp()\n atexit.register(shutil.rmtree, path)\n key_separator = kwargs.pop('key_separator', \".\")\n store = FSStoreV3(path, key_separator=key_separator, auto_mkdir=True)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault('compressor', Blosc())\n init_array(store, path=array_path, **kwargs)\n return Array(store, path=array_path, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def expected(self):\n return [\n \"1509abec4285494b61cd3e8d21f44adc3cf8ddf6\",\n \"7cfb82ec88f7ecb7ab20ae3cb169736bc76332b8\",\n \"b663857bb89a8ab648390454954a9cdd453aa24b\",\n \"21e90fa927d09cbaf0e3b773130e2dc05d18ff9b\",\n \"e8c1fdd18b5c2ee050b59d0c8c95d07db642459c\",\n ]\n\n\[email protected](have_fsspec is False, reason=\"needs fsspec\")\nclass TestArrayWithFSStoreV3PartialRead(TestArrayWithPathV3, TestArrayWithFSStorePartialRead):\n\n @staticmethod\n def create_array(array_path='arr1', read_only=False, **kwargs):\n path = mkdtemp()\n atexit.register(shutil.rmtree, path)\n store = FSStoreV3(path)\n cache_metadata = kwargs.pop(\"cache_metadata\", True)\n cache_attrs = kwargs.pop(\"cache_attrs\", True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault(\"compressor\", Blosc())\n init_array(store, path=array_path, **kwargs)\n return Array(\n store,\n path=array_path,\n read_only=read_only,\n cache_metadata=cache_metadata,\n cache_attrs=cache_attrs,\n partial_decompress=True,\n write_empty_chunks=write_empty_chunks,\n )\n\n def expected(self):\n return [\n \"1509abec4285494b61cd3e8d21f44adc3cf8ddf6\",\n \"7cfb82ec88f7ecb7ab20ae3cb169736bc76332b8\",\n \"b663857bb89a8ab648390454954a9cdd453aa24b\",\n \"21e90fa927d09cbaf0e3b773130e2dc05d18ff9b\",\n \"e8c1fdd18b5c2ee050b59d0c8c95d07db642459c\",\n ]\n\n\[email protected](have_fsspec is False, reason=\"needs fsspec\")\nclass TestArrayWithFSStoreV3Nested(TestArrayWithPathV3, TestArrayWithFSStoreNested):\n\n @staticmethod\n def create_array(array_path='arr1', read_only=False, **kwargs):\n path = mkdtemp()\n atexit.register(shutil.rmtree, path)\n key_separator = kwargs.pop('key_separator', \"/\")\n store = FSStoreV3(path, key_separator=key_separator, auto_mkdir=True)\n cache_metadata = kwargs.pop('cache_metadata', True)\n cache_attrs = kwargs.pop('cache_attrs', True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault('compressor', Blosc())\n init_array(store, path=array_path, **kwargs)\n return Array(store, path=array_path, read_only=read_only, cache_metadata=cache_metadata,\n cache_attrs=cache_attrs, write_empty_chunks=write_empty_chunks)\n\n def expected(self):\n return [\n \"1509abec4285494b61cd3e8d21f44adc3cf8ddf6\",\n \"7cfb82ec88f7ecb7ab20ae3cb169736bc76332b8\",\n \"b663857bb89a8ab648390454954a9cdd453aa24b\",\n \"21e90fa927d09cbaf0e3b773130e2dc05d18ff9b\",\n \"e8c1fdd18b5c2ee050b59d0c8c95d07db642459c\",\n ]\n\n\[email protected](have_fsspec is False, reason=\"needs fsspec\")\nclass TestArrayWithFSStoreV3NestedPartialRead(TestArrayWithPathV3,\n TestArrayWithFSStoreNestedPartialRead):\n @staticmethod\n def create_array(array_path='arr1', read_only=False, **kwargs):\n path = mkdtemp()\n atexit.register(shutil.rmtree, path)\n key_separator = kwargs.pop('key_separator', \"/\")\n store = FSStoreV3(path, key_separator=key_separator, auto_mkdir=True)\n cache_metadata = kwargs.pop(\"cache_metadata\", True)\n cache_attrs = kwargs.pop(\"cache_attrs\", True)\n write_empty_chunks = kwargs.pop('write_empty_chunks', True)\n kwargs.setdefault(\"compressor\", Blosc())\n init_array(store, path=array_path, **kwargs)\n return Array(\n store,\n path=array_path,\n read_only=read_only,\n cache_metadata=cache_metadata,\n cache_attrs=cache_attrs,\n partial_decompress=True,\n write_empty_chunks=write_empty_chunks,\n )\n\n def expected(self):\n return [\n \"1509abec4285494b61cd3e8d21f44adc3cf8ddf6\",\n \"7cfb82ec88f7ecb7ab20ae3cb169736bc76332b8\",\n \"b663857bb89a8ab648390454954a9cdd453aa24b\",\n \"21e90fa927d09cbaf0e3b773130e2dc05d18ff9b\",\n \"e8c1fdd18b5c2ee050b59d0c8c95d07db642459c\",\n ]\n\n\ndef test_array_mismatched_store_versions():\n store_v3 = KVStoreV3(dict())\n store_v2 = KVStore(dict())\n\n # separate chunk store\n chunk_store_v2 = KVStore(dict())\n chunk_store_v3 = KVStoreV3(dict())\n\n init_kwargs = dict(shape=100, chunks=10, dtype=\"<f8\")\n init_array(store_v2, path='dataset', chunk_store=chunk_store_v2, **init_kwargs)\n init_array(store_v3, path='dataset', chunk_store=chunk_store_v3, **init_kwargs)\n\n # store and chunk_store must have the same zarr protocol version\n with pytest.raises(ValueError):\n Array(store_v3, path='dataset', read_only=False, chunk_store=chunk_store_v2)\n with pytest.raises(ValueError):\n Array(store_v2, path='dataset', read_only=False, chunk_store=chunk_store_v3)\n"
] |
[
[
"numpy.product",
"numpy.take",
"numpy.linspace",
"numpy.asarray",
"numpy.dtype",
"numpy.all",
"numpy.zeros_like",
"numpy.mean",
"numpy.iinfo",
"numpy.random.randint",
"numpy.uint32",
"numpy.arange",
"numpy.empty_like",
"numpy.zeros",
"numpy.testing.assert_array_almost_equal",
"numpy.random.choice",
"numpy.int64",
"numpy.append",
"numpy.array",
"numpy.sum",
"numpy.random.random",
"numpy.random.seed",
"numpy.int32",
"numpy.compress",
"numpy.ones",
"numpy.testing.assert_array_equal",
"numpy.uint64",
"numpy.prod"
]
] |
sameertodkar/Car-Health-Monitor
|
[
"ff43dbe513e2fd35e37909b0021c3e08e95cc959"
] |
[
"Source/GUI_2/MonitorGUI.py"
] |
[
"import plotting_function\nimport os\nimport tkinter as tk\nfrom matplotlib import pyplot as plt\nfrom matplotlib import style\nimport matplotlib.animation as animation\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nimport matplotlib\n\nmatplotlib.use(\"TkAgg\")\n\n# Defining some style and fonts \nstyle.use(\"dark_background\")\nfontstyle = \"Helvetica\"\nsmall_fsize = 13\nlarge_fsize = 15\n\n# Creating an object for the figure to be plot\nf = plt.figure()\n\nselect_param = None\n\nchartLoad = True\npaneCount = 1\n\n\n# Creating a method for menu parameters\ndef changeParam(toWhat):\n \"\"\"Function to set the parameter whose graph needs to be displayed\n\n Arguments:\n toWhat {string} -- Parameter to be set\n \"\"\"\n global select_param\n select_param = toWhat\n\n\n# Creating an animate function for the matplotlib graphs\ndef animate(i):\n \"\"\"Function used to display live graphs\n \n Arguments:\n i {int} -- time interval\n \"\"\"\n if chartLoad:\n if paneCount == 1:\n csvData = []\n with open(\"TimeElapsed.csv\") as w:\n for row in w:\n csvData.append((row.split(\",\")))\n try:\n\n if select_param == \"OIL\":\n a = plt.subplot2grid((6, 4), (0, 0), rowspan=5, colspan=4)\n time = float(csvData[0][0])\n engineOilReliability = plotting_function.dataManipulation()\n # sample txt would be replaced with a file\n engineOilReliability.computeX(time)\n engineOilReliability.computeY(\"1-np.exp(-(i/5190)**1.55)\")\n\n a.clear()\n a.set_xlabel(\"time (hours)\")\n a.set_ylabel(\"Failure Probability\")\n a.plot(engineOilReliability.x_values,\n engineOilReliability.y_values, label=\"live data\")\n a.legend(bbox_to_anchor=(0, 1.02, 1, .102), loc=3,\n ncol=2, borderaxespad=0)\n title = \"OIL HEALTH \"\n a.set_title(title)\n\n elif select_param == \"TIRE\":\n a = plt.subplot2grid((6, 4), (0, 0), rowspan=5, colspan=4)\n time = float(csvData[0][1])\n engineOilReliability = plotting_function.dataManipulation()\n # sample txt would be replaced with a file\n engineOilReliability.computeX(time)\n engineOilReliability.computeY(\"1-np.exp(-(i/41667)**1.37)\")\n\n a.clear()\n a.set_xlabel(\"distance (kms)\")\n a.set_ylabel(\"Failure Probability\")\n a.plot(engineOilReliability.x_values,\n engineOilReliability.y_values, label=\"live data\")\n a.legend(bbox_to_anchor=(0, 1.02, 1, .102), loc=3,\n ncol=2, borderaxespad=0)\n title = \"TIRE HEALTH \"\n a.set_title(title)\n\n except Exception as e:\n print(e)\n\n\n# BASE-LINE code for adding pages\n\nclass HealthGraphs(tk.Tk):\n \"\"\"Class to define frame of the GUI\n \n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"Initialize the frame as an object of class HealthGraphs\n \"\"\"\n tk.Tk.__init__(self, *args, **kwargs)\n\n # Adding an icon for the GUI\n tk.Tk.iconbitmap(self, r\"graph.ico\")\n\n # Adding the GUI title\n tk.Tk.wm_title(self, \"Car Health Monitor\")\n\n # Setting up a minimum size for the GUI\n tk.Tk.wm_minsize(self, 850, 600)\n tk.Tk.wm_maxsize(self, 850, 600)\n\n # Adding a window frame\n container = tk.Frame(self)\n container.pack(side=\"top\", fill=\"both\", expand=True)\n\n # 0 is the min size, weight is the priority\n container.grid_rowconfigure(0, weight=1)\n container.grid_columnconfigure(0, weight=1)\n container.config(bg=\"black\")\n\n # creating an empty dictionary for all the frames that we will create\n self.frames = {}\n\n # creating a for loop for every new page\n for F in (StartPage, PageOne, PageTwo):\n # creating a start page for the GUI\n frame = F(container, self)\n\n self.frames[F] = frame\n\n # assigning the location\n # nswe = north,south,east,west. Can be expanded in all directions\n frame.grid(row=0, column=0, sticky=\"nsew\")\n\n # showing up of a frame StartPage whenever this GUI opens\n self.show_frame(StartPage)\n\n def show_frame(self, cont):\n \"\"\"Function to bring the frame to the top \n \n Arguments:\n cont -- represents the page container\n \"\"\"\n # cont is the key for the self.frames dictionary in the __init method\n frame = self.frames[cont]\n frame.tkraise() # brings up thw window to the top\n\n def restart_notif(self):\n \"\"\"Function to call notification executable\n \"\"\"\n os.startfile(\"alertloop.exe\")\n\n\n# Adding a Start page\nclass StartPage(tk.Frame):\n \"\"\"Inititalize the start page of the GUI\n \"\"\"\n\n def __init__(self, parent, controller):\n \"\"\"Initialize object of class StartPage\n \n Arguments:\n parent -- object of tk.frame\n controller -- object of class HealthGraphs\n\n \"\"\"\n tk.Frame.__init__(self, parent, bg='black')\n\n label = tk.Label(self, text=\"CAR HEALTH MONITOR\",\n bg=\"black\", fg=\"cyan2\",\n font=(fontstyle, 30))\n label.place(x=190, y=80)\n\n label2 = tk.Label(self, text=\"Select the component\", bg=\"black\",\n fg=\"white\",\n font=(fontstyle, 18))\n label2.place(x=310, y=240)\n\n label3 = tk.Label(self, text=\"When maintenance is carried out, click here\",\n bg=\"black\", fg=\"white\",\n font=(fontstyle, large_fsize))\n label3.place(x=130, y=500)\n\n button1 = tk.Button(self, bg=\"black\", bd=5, fg=\"cyan2\", height=3,\n width=10,\n relief='ridge', text=\"Engine Oil\",\n command=lambda: [controller.show_frame(PageOne),\n changeParam(\"OIL\")])\n button1.place(x=470, y=300)\n\n button2 = tk.Button(self, bg=\"black\", relief='ridge', fg=\"cyan2\", bd=5,\n height=3, width=10, text=\"Tire\",\n command=lambda: [controller.show_frame(PageOne),\n changeParam(\"TIRE\")])\n button2.place(x=300, y=300)\n\n button3 = tk.Button(self, bg=\"black\", fg=\"cyan2\", relief='ridge',\n height=3, width=15, bd=5,\n text=\"Service complete\",\n command=lambda: controller.restart_notif())\n button3.place(x=560, y=485)\n\n\n# Adding Page 1\nclass PageOne(tk.Frame):\n \"\"\" Inititalize the page one of the GUI\n \"\"\"\n\n def __init__(self, parent, controller):\n \"\"\"Initialize object of class PageOne\n \n Arguments:\n parent -- object of tk.frame\n controller -- object of class HealthGraphs\n\n \"\"\"\n tk.Frame.__init__(self, parent, bg='black')\n label = tk.Label(self, text=\"Failure Graphs\", bg=\"black\", fg=\"white\",\n font=(fontstyle, 17))\n label.place(x=360, y=30)\n\n button1 = tk.Button(self, bg=\"black\", fg=\"cyan2\", height=3, width=10,\n text=\"Home\",\n command=lambda: controller.show_frame(StartPage))\n button1.place(x=0, y=10)\n\n button2 = tk.Button(self, bg=\"black\", fg=\"cyan2\", height=2, width=10,\n text=\"Tire\", font=(fontstyle, 11),\n command=lambda: [controller.show_frame(PageOne),\n changeParam(\"TIRE\")])\n button2.place(x=260, y=90)\n\n button3 = tk.Button(self, bg=\"black\", fg=\"cyan2\", height=2, width=10,\n text=\"Engine Oil\", font=(fontstyle, 11),\n command=lambda: [controller.show_frame(PageOne),\n changeParam(\"OIL\")])\n button3.place(x=530, y=90)\n\n button4 = tk.Button(self, bg=\"black\", fg=\"cyan2\", height=3, width=10,\n text=\"Next\",\n command=lambda: controller.show_frame(PageTwo))\n button4.place(x=770, y=10)\n\n canvas1 = FigureCanvasTkAgg(f, self)\n canvas1.draw()\n canvas1.get_tk_widget().place(x=110, y=150)\n\n\nclass PageTwo(tk.Frame):\n \"\"\"Inititalize the page two of the GUI\n \"\"\"\n\n def __init__(self, parent, controller):\n \"\"\"Initialize object of class PageTwo\n \n Arguments:\n parent -- object of tk.frame\n controller -- object of class HealthGraphs\n\n \"\"\"\n tk.Frame.__init__(self, parent, bg='black')\n label = tk.Label(self, text=\"Project by:\", bg=\"black\",\n fg=\"cyan2\", font=(fontstyle, 14))\n label.place(x=355, y=220)\n\n labe2 = tk.Label(self, text=\"Ajaykumar Mudaliar\\nSameer Todkar\\nChinmay Mulay\\n\\\n Pranav Jain\", bg=\"black\", fg=\"white\", font=(fontstyle, 13))\n labe2.place(x=325, y=260)\n\n button1 = tk.Button(self, bg=\"black\", fg=\"cyan2\", height=3, width=10,\n text=\"Home\",\n command=lambda: controller.show_frame(StartPage))\n button1.place(x=0, y=10)\n\n# Creating an object of the class HealthGraphs()\napp = HealthGraphs()\n\n# plotting the graph using Funcanimation and the animate function\ngraph = animation.FuncAnimation(f, animate, interval=1000)\napp.mainloop()\n"
] |
[
[
"matplotlib.style.use",
"matplotlib.use",
"matplotlib.pyplot.figure",
"matplotlib.animation.FuncAnimation",
"matplotlib.pyplot.subplot2grid",
"matplotlib.backends.backend_tkagg.FigureCanvasTkAgg"
]
] |
shartoo/Tacotron-2
|
[
"24d4f2891c9def484406ec53b811d0caff15a62b"
] |
[
"datasets/preprocessor.py"
] |
[
"import glob, os\nfrom concurrent.futures import ProcessPoolExecutor\nfrom functools import partial\n\nimport numpy as np\nfrom datasets import audio\nfrom wavenet_vocoder.util import is_mulaw, is_mulaw_quantize, mulaw, mulaw_quantize\n\n\ndef build_from_path(hparams, input_dirs, mel_dir, linear_dir, wav_dir, n_jobs=12, tqdm=lambda x: x):\n\t\"\"\"\n\tPreprocesses the speech dataset from a gven input path to given output directories\n\n\tArgs:\n\t\t- hparams: hyper parameters\n\t\t- input_dir: input directory that contains the files to prerocess\n\t\t- mel_dir: output directory of the preprocessed speech mel-spectrogram dataset\n\t\t- linear_dir: output directory of the preprocessed speech linear-spectrogram dataset\n\t\t- wav_dir: output directory of the preprocessed speech audio dataset\n\t\t- n_jobs: Optional, number of worker process to parallelize across\n\t\t- tqdm: Optional, provides a nice progress bar\n\n\tReturns:\n\t\t- A list of tuple describing the train examples. this should be written to train.txt\n\t\"\"\"\n\n\t# We use ProcessPoolExecutor to parallelize across processes, this is just for\n\t# optimization purposes and it can be omited\n\texecutor = ProcessPoolExecutor(max_workers=n_jobs)\n\tfutures = []\n\tindex = 1\n\tfor input_dir in input_dirs:\n\t\ttrn_files = glob.glob(os.path.join(input_dir, 'xmly_record', 'A*', '*.trn'))\n\t\t# trn_files = glob.glob(os.path.join(input_dir, 'guoxuezhihui', 'guoxue_*', '*.trn'))\n\t\t# trn_files += glob.glob(os.path.join(input_dir, 'xuexun', 'xuexun_*', '*.trn'))\n\t\tfor trn in trn_files:\n\t\t\twith open(trn) as f:\n\t\t\t\tbasename = trn[:-4]\n\t\t\t\tif basename.endswith('.wav'):\n\t\t\t\t\t# THCHS30\n\t\t\t\t\tf.readline()\n\t\t\t\t\twav_file = basename\n\t\t\t\telse:\n\t\t\t\t\twav_file = basename + '.wav'\n\t\t\t\twav_path = wav_file\n\t\t\t\tbasename = basename.split('/')[-1]\n\t\t\t\ttext = f.readline().strip()\n\t\t# with open(os.path.join(input_dir, 'metadata.csv'), encoding='utf-8') as f:\n\n\t\t# \tfor line in f:\n\t\t# \t\tparts = line.strip().split('|')\n\t\t# \t\tbasename = parts[0]\n\t\t# \t\twav_path = os.path.join(input_dir, 'wavs', '{}.wav'.format(basename))\n\t\t# \t\ttext = parts[2]\n\t\t\t\tfutures.append(executor.submit(partial(_process_utterance, mel_dir, linear_dir, wav_dir, basename, wav_path, text, hparams)))\n\t\t\t\tindex += 1\n\n\treturn [future.result() for future in tqdm(futures) if future.result() is not None]\n\n\ndef _process_utterance(mel_dir, linear_dir, wav_dir, index, wav_path, text, hparams):\n\t\"\"\"\n\tPreprocesses a single utterance wav/text pair\n\n\tthis writes the mel scale spectogram to disk and return a tuple to write\n\tto the train.txt file\n\n\tArgs:\n\t\t- mel_dir: the directory to write the mel spectograms into\n\t\t- linear_dir: the directory to write the linear spectrograms into\n\t\t- wav_dir: the directory to write the preprocessed wav into\n\t\t- index: the numeric index to use in the spectogram filename\n\t\t- wav_path: path to the audio file containing the speech input\n\t\t- text: text spoken in the input audio file\n\t\t- hparams: hyper parameters\n\n\tReturns:\n\t\t- A tuple: (audio_filename, mel_filename, linear_filename, time_steps, mel_frames, linear_frames, text)\n\t\"\"\"\n\ttry:\n\t\t# Load the audio as numpy array\n\t\twav = audio.load_wav(wav_path, sr=hparams.sample_rate)\n\texcept FileNotFoundError: #catch missing wav exception\n\t\tprint('file {} present in csv metadata is not present in wav folder. skipping!'.format(\n\t\t\twav_path))\n\t\treturn None\n\n\t#rescale wav\n\tif hparams.rescale:\n\t\twav = wav / np.abs(wav).max() * hparams.rescaling_max\n\n\t#M-AILABS extra silence specific\n\tif hparams.trim_silence:\n\t\twav = audio.trim_silence(wav, hparams)\n\n\t#Mu-law quantize\n\tif is_mulaw_quantize(hparams.input_type):\n\t\t#[0, quantize_channels)\n\t\tout = mulaw_quantize(wav, hparams.quantize_channels)\n\n\t\t#Trim silences\n\t\tstart, end = audio.start_and_end_indices(out, hparams.silence_threshold)\n\t\twav = wav[start: end]\n\t\tout = out[start: end]\n\n\t\tconstant_values = mulaw_quantize(0, hparams.quantize_channels)\n\t\tout_dtype = np.int16\n\n\telif is_mulaw(hparams.input_type):\n\t\t#[-1, 1]\n\t\tout = mulaw(wav, hparams.quantize_channels)\n\t\tconstant_values = mulaw(0., hparams.quantize_channels)\n\t\tout_dtype = np.float32\n\n\telse:\n\t\t#[-1, 1]\n\t\tout = wav\n\t\tconstant_values = 0.\n\t\tout_dtype = np.float32\n\n\t# Compute the mel scale spectrogram from the wav\n\tmel_spectrogram = audio.melspectrogram(wav, hparams).astype(np.float32)\n\tmel_frames = mel_spectrogram.shape[1]\n\n\tif mel_frames > hparams.max_mel_frames and hparams.clip_mels_length:\n\t\treturn None\n\n\t#Compute the linear scale spectrogram from the wav\n\tlinear_spectrogram = audio.linearspectrogram(wav, hparams).astype(np.float32)\n\tlinear_frames = linear_spectrogram.shape[1]\n\n\t#sanity check\n\tassert linear_frames == mel_frames\n\n\t#Ensure time resolution adjustement between audio and mel-spectrogram\n\tfft_size = hparams.n_fft if hparams.win_size is None else hparams.win_size\n\tl, r = audio.pad_lr(wav, fft_size, audio.get_hop_size(hparams))\n\n\t#Zero pad for quantized signal\n\tout = np.pad(out, (l, r), mode='constant', constant_values=constant_values)\n\tassert len(out) >= mel_frames * audio.get_hop_size(hparams)\n\n\t#time resolution adjustement\n\t#ensure length of raw audio is multiple of hop size so that we can use\n\t#transposed convolution to upsample\n\tout = out[:mel_frames * audio.get_hop_size(hparams)]\n\tassert len(out) % audio.get_hop_size(hparams) == 0\n\ttime_steps = len(out)\n\n\t# Write the spectrogram and audio to disk\n\taudio_filename = 'audio-{}.npy'.format(index)\n\tmel_filename = 'mel-{}.npy'.format(index)\n\tlinear_filename = 'linear-{}.npy'.format(index)\n\tnp.save(os.path.join(wav_dir, audio_filename), out.astype(out_dtype), allow_pickle=False)\n\tnp.save(os.path.join(mel_dir, mel_filename), mel_spectrogram.T, allow_pickle=False)\n\tnp.save(os.path.join(linear_dir, linear_filename), linear_spectrogram.T, allow_pickle=False)\n\n\t# Return a tuple describing this training example\n\treturn (audio_filename, mel_filename, linear_filename, time_steps, mel_frames, text)\n"
] |
[
[
"numpy.abs",
"numpy.pad"
]
] |
dcorre/ImSimpy
|
[
"9c9a23e7f0d757204d181c25acfe178d0a8aebbf"
] |
[
"ImSimpy/utils/plot_3D.py"
] |
[
"from mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\nimport numpy as np\nfrom astropy.io import fits\n\n\n\ndata=fits.getdata('zemax/PSF_z_edge.fits')\n#data=fits.getdata('oversampled_psf/zemax_moffat_128_z_edge_s04.fits')\n#data=fits.getdata('psf_degradation/zemax_moffat_1024_z_edge_s04_z300.fits')\n#data=fits.getdata('airy_ideal_psfs/airy_1024_g.fits')\n\nif np.sum(data)!=1: data/=np.sum(data)\n\nfig = plt.figure()\nax = fig.gca(projection='3d')\n\ncenter=np.unravel_index(data.argmax(), data.shape)\nwidth=50\nprint (center)\n# Make data.\nX = np.arange(center[0]-width,center[0]+width,1)\nY = np.arange(center[1]-width,center[1]+width,1)\nX, Y = np.meshgrid(X, Y)\nZ = data[center[0]-width:center[0]+width,center[1]-width:center[1]+width]\n# Plot the surface.\nsurf = ax.plot_surface(X, Y, Z, cmap=cm.jet,rstride=1, cstride=1,\n linewidth=0, antialiased=False,shade=False)\n\n# Customize the z axis.\n#ax.set_zlim(0, 1.)\n#ax.zaxis.set_major_locator(LinearLocator(10))\n#ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\n\n# Add a color bar which maps values to colors.\nfig.colorbar(surf, shrink=0.5, aspect=5)\n\nplt.show()\n"
] |
[
[
"numpy.arange",
"numpy.meshgrid",
"numpy.sum",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
DelSquared/cdf-transform-rng
|
[
"8515aeea030220b729eedf9229380136c4f393ea"
] |
[
"RNGDistributionTransform.py"
] |
[
"import numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\nn=5000\r\n#number of generated points\r\nUnifR=np.random.uniform(size=(1,n))\r\n#uniform array\r\nDistR=np.array([1,n])\r\n#output array radial\r\nUnifT=2*np.pi*np.random.uniform(size=(1,n))\r\n# output array angular\r\nx=np.arange(0,10,0.1)\r\ny=np.ones([100,1])/10\r\n#x-y arrays currently unused\r\n\r\ndef ExpCDFinv (x, L):\r\n return -np.log(1-x)*L\r\ndef BellCDFinv (x, s, m):\r\n return (np.log((1/x)-1)*s)-m\r\ndef InvSqCDFinv (x, k):\r\n return ((1/x)-1)/k\r\n#inverse CDF functions: exponential, \"bell\" (not a real Gaussian), and an inverse square law\r\n\r\nfig0=plt.figure()\r\nplt.scatter(UnifR*np.cos(UnifT),UnifR*np.sin(UnifT),marker=\".\")\r\nplt.show()\r\n\r\nfig0=plt.figure()\r\nplt.plot(x,y)\r\nplt.show()\r\n\r\nDistR=BellCDFinv(UnifR,1,0)\r\ny=(1/(1 + np.exp(-x)))*(1- 1/(1 + np.exp(-x)))\r\n\r\nfig1=plt.figure()\r\nplt.scatter(DistR*np.cos(UnifT),DistR*np.sin(UnifT),marker=\".\")\r\nplt.show()\r\n\r\nfig1=plt.figure()\r\nplt.plot(x,y)\r\nplt.show()\r\n\r\nDistR=ExpCDFinv(UnifR,1)\r\ny=np.exp(-x)\r\n\r\nfig2=plt.figure()\r\nplt.scatter(DistR*np.cos(UnifT),DistR*np.sin(UnifT),marker=\".\")\r\nplt.show()\r\n\r\nfig2=plt.figure()\r\nplt.plot(x,y)\r\nplt.show()\r\n\r\nDistR=InvSqCDFinv(UnifR,1)\r\ny=1/(1+x)\r\n\r\nfig3=plt.figure()\r\nplt.scatter(DistR*np.cos(UnifT),DistR*np.sin(UnifT),marker=\".\")\r\nplt.show()\r\n\r\nfig3=plt.figure()\r\nplt.plot(x,y)\r\nplt.show()\r\n#plots\r\n"
] |
[
[
"numpy.log",
"numpy.arange",
"numpy.cos",
"numpy.ones",
"matplotlib.pyplot.plot",
"numpy.sin",
"numpy.exp",
"numpy.random.uniform",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
oscovida/oscovida
|
[
"6afb3fb5f8c94d19b60463c311812fb291b28a91"
] |
[
"oscovida/oscovida.py"
] |
[
"\"\"\"Code used for notebooks and data exploration on\nhttps://github.com/oscovida/oscovida\"\"\"\n\n\nimport datetime\nimport math\nimport os\nimport pytz\nimport time\nimport joblib\nimport numpy as np\nimport pandas as pd\nimport IPython.display\nfrom typing import Tuple, Union\n# choose font - can be deactivated\nfrom matplotlib import rcParams\nfrom oscovida.data_sources import base_url, hungary_data, jhu_population_url, rki_data, rki_population_url, rki_population_backup_file\nfrom oscovida.plotting_helpers import align_twinx_ticks, cut_dates, has_twin, limit_to_smoothed, uncertain_tail\n\nrcParams['font.family'] = 'sans-serif'\nrcParams['font.sans-serif'] = ['Tahoma', 'DejaVu Sans', 'Lucida Grande', 'Verdana']\nrcParams['svg.fonttype'] = 'none'\n# need many figures for index.ipynb and germany.ipynb\nrcParams['figure.max_open_warning'] = 50\nfrom matplotlib.collections import LineCollection\nfrom matplotlib.colors import LinearSegmentedColormap\nfrom matplotlib.dates import DateFormatter, date2num, MONDAY, WeekdayLocator\nfrom matplotlib.ticker import ScalarFormatter, FuncFormatter, FixedLocator\nfrom bisect import bisect\n\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')\n\n# suppress warning\nfrom pandas.plotting import register_matplotlib_converters\nregister_matplotlib_converters()\n\nLW = 3 # line width\n\n# set up joblib memory to avoid re-fetching files\njoblib_location = \"./cachedir\"\njoblib_memory = joblib.Memory(joblib_location, verbose=0)\n\n\ndef compute_binder_link(notebook_name):\n \"\"\"Given a string \"\"\"\n root_url = \"https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/\"\n return root_url + notebook_name\n\n\ndef display_binder_link(notebook_name):\n url = compute_binder_link(notebook_name)\n # print(f\"url is {url}\")\n IPython.display.display(\n IPython.display.Markdown(f'[Execute this notebook with Binder]({url})'))\n\n\ndef clear_cache():\n \"\"\"Need to run this before new data for the day is created\"\"\"\n joblib_memory.clear()\n\n\ndef double_time_exponential(q2_div_q1, t2_minus_t1=None):\n \"\"\" See https://en.wikipedia.org/wiki/Doubling_time\"\"\"\n if t2_minus_t1 is None:\n t2_minus_t1 = np.ones(q2_div_q1.shape)\n return t2_minus_t1 * np.log(2) / np.log(q2_div_q1)\n\n\ndef report_download(url, df):\n print(f\"Downloaded data: last data point {df.columns[-1]} from {url}\")\n\n\n@joblib_memory.cache\ndef fetch_deaths_last_execution():\n \"\"\"Use to remember at what time and date the last set of deaths was downloaded.\n A bit of a hack as we didn't know how to get this out of joblib.\n \"\"\"\n return datetime.datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\")\n\n\n@joblib_memory.cache\ndef fetch_cases_last_execution():\n \"\"\"See fetch_deaths_last_execution\"\"\"\n return datetime.datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\")\n\n\n@joblib_memory.cache\ndef fetch_deaths():\n \"\"\"Download deaths from Johns Hopkins data repository\"\"\"\n url = os.path.join(base_url, \"time_series_covid19_\" + \"deaths\" + \"_global.csv\")\n df = pd.read_csv(url, index_col=1)\n report_download(url, df)\n fetch_deaths_last_execution()\n return df\n\n\n@joblib_memory.cache\ndef fetch_deaths_US():\n \"\"\"Download deaths for US states from Johns Hopkins data repository\"\"\"\n url = os.path.join(base_url, \"time_series_covid19_\" + \"deaths\" + \"_US.csv\")\n df = pd.read_csv(url, index_col=1)\n report_download(url, df)\n # fetch_deaths_last_execution_()\n return df\n\n\n@joblib_memory.cache\ndef fetch_cases():\n \"\"\"Download cases from Johns Hopkins data repository\"\"\"\n url = os.path.join(base_url, \"time_series_covid19_\" + \"confirmed\" + \"_global.csv\")\n df = pd.read_csv(url, index_col=1)\n report_download(url, df)\n fetch_cases_last_execution()\n return df\n\n\n@joblib_memory.cache\ndef fetch_cases_US():\n \"\"\"Download cases for US status from Johns Hopkins data repository\"\"\"\n url = os.path.join(base_url, \"time_series_covid19_\" + \"confirmed\" + \"_US.csv\")\n df = pd.read_csv(url, index_col=1)\n report_download(url, df)\n fetch_cases_last_execution()\n return df\n\n\ndef get_country_data_johns_hopkins(country: str,\n region: str = None, subregion: str = None) -> Tuple[pd.DataFrame, pd.DataFrame]:\n \"\"\"Given a country name, return deaths and cases as a tuple of\n pandas time series. Works for all (?) countries in the world, or at least\n those in the Johns Hopkins data set. All rows should contain a datetime\n index and a value.\n \"\"\"\n\n deaths = fetch_deaths()\n cases = fetch_cases()\n\n assert country in deaths.index, f\"{country} not in available countries. These are {sorted(deaths.index)}\"\n\n # Some countries report sub areas (i.e. multiple rows per country) such as China, France, United Kingdom\n # Denmark. In that case, we sum over all regions (by summing over the relevant rows).\n\n tmp = deaths.loc[country]\n if len(tmp.shape) == 1: # most countries (Germany, Italy, ...)\n d = tmp\n elif len(tmp.shape) == 2: # China, France, United Kingdom, ...\n d = tmp.drop(columns=['Province/State']).sum()\n d.rename(\"deaths\", inplace=True)\n else:\n raise ValueError(\"Unknown data set structure for deaths {country}:\", tmp)\n\n tmp = cases.loc[country]\n if len(tmp.shape) == 1:\n c = tmp\n elif len(tmp.shape) == 2:\n c = tmp.drop(columns=['Province/State']).sum()\n c.rename(\"cases\", inplace=True)\n else:\n raise ValueError(\"Unknown data set structure for cases {country}:\", tmp)\n\n # make date string into timeindex\n d.index = pd.to_datetime(d.index, errors=\"coerce\", format=\"%m/%d/%y\")\n c.index = pd.to_datetime(c.index, errors=\"coerce\", format=\"%m/%d/%y\")\n # drop all rows that don't have data\n # sanity check: how many do we drop?\n if c.index.isnull().sum() > 3:\n print(f\"about to drop {c.index.isnull().sum()} entries due to NaT in index\", c)\n c = c[c.index.notnull()]\n\n if d.index.isnull().sum() > 3:\n print(f\"about to drop {d.index.isnull().sum()} entries due to NaT in index\", d)\n d = d[d.index.notnull()]\n\n # check there are no NaN is in the data\n assert c.isnull().sum() == 0, f\"{c.isnull().sum()} NaNs in {c}\"\n assert d.isnull().sum() == 0, f\"{d.isnull().sum()} NaNs in {d}\"\n\n # label data\n c.name = country + \" cases\"\n d.name = country + \" deaths\"\n\n return c, d\n\n\ndef get_US_region_list():\n \"\"\"return list of strings with US state names\"\"\"\n deaths = fetch_deaths_US()\n return list(deaths.groupby(\"Province_State\").sum().index)\n\n\ndef get_region_US(state, county=None, debug=False):\n \"\"\"Given a US state name and county, return deaths and cases as a tuple of pandas time\n series. (Johns Hopkins data set)\n\n If country is None, then sum over all counties in that state (i.e. return\n the numbers for the state.)\n\n \"\"\"\n\n if not county is None:\n raise NotImplementedError(\"Can only process US states (no counties)\")\n\n deaths = fetch_deaths_US()\n cases = fetch_cases_US()\n\n assert state in deaths['Province_State'].values, \\\n f\"{state} not in available states. These are {sorted(set(deaths['Province_State']))}\"\n\n if county is None:\n tmpd = deaths.groupby('Province_State').sum()\n d = tmpd.loc[state]\n tmpc = cases.groupby('Province_State').sum()\n c = tmpc.loc[state]\n else:\n raise NotImplementedError(\"Can't do counties yet.\")\n # Some countries report sub areas (i.e. multiple rows per country) such as China, France, United Kingdom\n # Denmark. In that case, we sum over all regions.\n\n # make date string into timeindex\n d.index = pd.to_datetime(d.index, errors=\"coerce\", format=\"%m/%d/%y\")\n c.index = pd.to_datetime(c.index, errors=\"coerce\", format=\"%m/%d/%y\")\n # drop all rows that don't have data\n # sanity check: how many do we drop?\n if c.index.isnull().sum() > 3:\n if debug:\n print(f\"about to drop {c.index.isnull().sum()} entries due to NaT in index\", c)\n c = c[c.index.notnull()]\n\n if d.index.isnull().sum() > 3:\n if debug:\n print(f\"about to drop {d.index.isnull().sum()} entries due to NaT in index\", d)\n d = d[d.index.notnull()]\n\n # check there are no NaN is in the data\n assert c.isnull().sum() == 0, f\"{c.isnull().sum()} NaNs in {c}\"\n assert d.isnull().sum() == 0, f\"{d.isnull().sum()} NaNs in {d}\"\n\n # label data\n country = f\"US-{state}\"\n c.name = country + \" cases\"\n d.name = country + \" deaths\"\n\n return c, d\n\n\ndef compose_dataframe_summary(cases, deaths):\n \"\"\"Used in per-country template to show data table.\n Could be extended.\n\n Expects series of cases and deaths (time-aligned), combines those in DataFrame and returns it\n \"\"\"\n df = pd.DataFrame()\n df[\"total cases\"] = cases\n df[\"daily new cases\"] = cases.diff()\n if deaths is not None:\n df[\"total deaths\"] = deaths\n df[\"daily new deaths\"] = deaths.diff()\n\n # drop first row with nan -> otherwise ints are shows as float in table\n df = df.dropna().astype(int)\n\n # change index: latest numbers shown first\n df = df[::-1]\n\n return df\n\n\n@joblib_memory.cache\ndef fetch_data_germany_last_execution():\n return datetime.datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\")\n\n\n@joblib_memory.cache\ndef fetch_data_germany(include_last_day=True) -> pd.DataFrame:\n \"\"\"Fetch data for Germany from Robert Koch institute and return as a pandas\n DataFrame with the `Meldedatum` as the index.\n\n Data source is https://npgeo-corona-npgeo-de.hub.arcgis.com . The text on that\n webpage implies that the data comes from the Robert Koch Institute.\n\n As an option (`include_last_day`), we can omit the last day with data from\n the retrieved data sets (see reasoning below in source), as the data is\n commonly update one day later with more accurate (and typically higher)\n numbers.\n \"\"\"\n\n # outdated: datasource = \"https://opendata.arcgis.com/datasets/dd4580c810204019a7b8eb3e0b329dd6_0.csv\"\n datasource = rki_data\n t0 = time.time()\n print(f\"Please be patient - downloading data from {datasource} ...\")\n germany = pd.read_csv(datasource)\n delta_t = time.time() - t0\n print(f\"Completed downloading {len(germany)} rows in {delta_t:.1f} seconds.\")\n\n ## create new column 'landkreis' and get rid of \"SK \" and \"LK \" for this\n ## - this is too simplistic. We have fields like \"Region Hannover\"\n # germany['landkreis'] = germany['Landkreis'].apply(lambda s: s[3:])\n\n # (at least) the last data from the Robert-Koch-Institute (RKI) seems not to be\n # fully reported the day after. For example, on 3 April, the number of cases\n # from RKI is well below what is expected. Example:\n #\n # From RKI (as of evening of 2020-04-03:)\n # 2020-03-29 62653\n # 2020-03-30 66692\n # 2020-03-31 72333\n # 2020-04-01 77464\n # 2020-04-02 79625\n #\n # From Johns Hopkins (as of evening of 2020-04-03:):\n # 2020-03-29 62095\n # 2020-03-30 66885\n # 2020-03-31 71808\n # 2020-04-01 77872\n # 2020-04-02 84794\n #\n # So we must assume that the RKI data will be corrected later; maybe the next day.\n #\n # To make our plots not inaccurate, we'll remove the last data point from the RKI data:\n g2 = germany.set_index(pd.to_datetime(germany['Meldedatum']))\n g2.index.name = 'date'\n\n # get rid of last day in data if desired\n if include_last_day == False:\n last_day = g2.index.max()\n sel = g2.index == last_day\n cleaned = g2.drop(g2[sel].index, inplace=False)\n else:\n cleaned = g2\n\n fetch_data_germany_last_execution()\n return cleaned\n\n\ndef pad_cumulative_series_to_yesterday(series):\n \"\"\"Given a time series with date as index and cumulative cases/deaths as values:\n\n - if the last date in the index is older than yesterday, then\n - add that date\n - resample the series with a daily interval, using padding with last known value\n - and return.\n\n Required for Robert Koch Data, where only a new data point is provided if\n the numbers change, but the plotting algorithms need to know that there is\n no change. Without this padding, the data set looks old as the last plotted\n data point is the last one for which data is provided.\n \"\"\"\n now = datetime.datetime.now()\n rki_tz = pytz.timezone('Europe/Berlin')\n now_tz = datetime.datetime.now(rki_tz)\n\n # remove time zone information from datetime, so we can compare against\n # datatime dates from get_country_data which has no timezone information\n # attached.\n now = now.replace(tzinfo=None)\n today = now.replace(hour=0, minute=0, second=0, microsecond=0)\n yesterday = today - pd.Timedelta(\"1D\")\n last = series.index.max()\n if last < yesterday:\n # repeat last data point with index for yesterday\n series[yesterday] = series[last]\n series2 = series.resample(\"1D\").pad()\n return series2\n else:\n return series\n\n\ndef germany_get_region(state=None, landkreis=None, pad2yesterday=False):\n \"\"\" Returns cases and deaths time series for Germany, and a label for the state/kreis.\n\n If state is given, return sum of cases (as function of time) in that state (state=Bundesland)\n\n If Landkreis is given, return data from just that Landkreis.\n\n Landkreis seems unique, so there is no need to provide state and Landkreis.\n\n [Should tidy up names here; maybe go to region and subregion in the function argument name, and\n translate later.]\n \"\"\"\n germany = fetch_data_germany()\n \"\"\"Returns two time series: (cases, deaths)\"\"\"\n assert state or landkreis, \"Need to provide a value for state or landkreis\"\n\n if state and landkreis:\n raise NotImplementedError(\"Try to use 'None' for the state.\")\n # TODO: We need to check if this is important.\n\n if state:\n if not state in germany['Bundesland'].values:\n raise Exception(\n f\"{state} not in available German states. These are \"\n f\"{sorted(germany['Bundesland'].drop_duplicates())}\"\n )\n\n land = germany[germany['Bundesland'] == state]\n land = land.set_index(pd.to_datetime(land['Meldedatum']))\n land.index.name = 'date'\n land.sort_index(inplace=True)\n\n # group over multiple rows for the same date\n # (this will also group over the different landkreise in the state)\n cases = land[\"AnzahlFall\"].groupby('date').agg('sum').cumsum()\n region_label = f'Germany-{state}'\n cases.name = region_label + \" cases\"\n\n # group over all multiple entries per day\n deaths = land[\"AnzahlTodesfall\"].groupby('date').agg('sum').cumsum()\n deaths.name = region_label + \" deaths\"\n\n if pad2yesterday:\n deaths = pad_cumulative_series_to_yesterday(deaths)\n cases = pad_cumulative_series_to_yesterday(cases)\n\n return cases, deaths\n\n if landkreis:\n assert landkreis in germany['Landkreis'].values, \\\n f\"{state} not in available German states. These are {sorted(germany['Landkreis'].drop_duplicates())}\"\n\n lk = germany[germany[\"Landkreis\"] == landkreis]\n lk.index = pd.to_datetime(lk['Meldedatum'])\n lk.index.name = 'date'\n lk = lk.sort_index()\n\n cases = lk[\"AnzahlFall\"].groupby('date').agg('sum').cumsum()\n region_label = f'Germany-{landkreis}'\n cases.name = region_label + ' cases'\n\n deaths = lk[\"AnzahlTodesfall\"].groupby('date').agg('sum').cumsum()\n deaths.name = region_label + ' deaths'\n\n if pad2yesterday:\n deaths = pad_cumulative_series_to_yesterday(deaths)\n cases = pad_cumulative_series_to_yesterday(cases)\n\n return cases, deaths\n\n\n@joblib_memory.cache\ndef fetch_csv_data_from_url(source) -> pd.DataFrame:\n \"\"\"Given a URL, fetch the csv using pandas. Put into separate function (from germany_get_population)\n to avoid repeated download of file (for better performance).\"\"\"\n data = pd.read_csv(source)\n return data # type: ignore\n\n\ndef _germany_get_population_backup_data_raw() -> pd.DataFrame:\n \"\"\"Function is not meant to be used directly.\n Use germany_get_population() instead (which will call this function if required).\n \"\"\"\n\n # where is the backup file?\n rki_population_backup_path = os.path.join(os.path.split(__file__)[0],\n rki_population_backup_file)\n\n population = pd.read_csv(rki_population_backup_path)\n return population\n\n\n\n@joblib_memory.cache\ndef germany_get_population() -> pd.DataFrame:\n \"\"\"The function's behavior duplicates the one for `germany_get_region()` one.\"\"\"\n source = rki_population_url\n\n population = fetch_csv_data_from_url(source)\n try:\n \tpopulation = (\n \t population\n \t .set_index('county')\n \t)\n except KeyError as exception:\n print(f\"Couldn't retrieve population data from RKI ({rki_population_url}). \"\n \"Using backup data from August 2020 instead \"\n \"(https://github.com/oscovida/oscovida/blob/master/oscovida/backup_data/RKI_Corona_Landkreise.csv)\"\n )\n population = _germany_get_population_backup_data_raw()\n \tpopulation = (\n \t population\n \t .set_index('county')\n \t)\n\n population = population.rename(columns={\"EWZ\": \"population\"})\n\n # Some tidy up of the data:\n\n # see https://github.com/oscovida/oscovida/issues/210\n # try to remove this if-clause and see if tests fail:\n if \"LK Saar-Pfalz-Kreis\" in population.index:\n population.loc['LK Saarpfalz-Kreis'] = population.loc['LK Saar-Pfalz-Kreis']\n population = population.drop('LK Saar-Pfalz-Kreis')\n\n # 27 July 2021 - test fail because name is \"Städteregion Aachen'\" in actual data (\n # i.e. 'StädteRegion' versus 'Städteregion' Aachen)\n # see https://github.com/oscovida/oscovida/runs/3170956651?check_suite_focus=true#step:6:651\n if \"StädteRegion Aachen\" in population.index:\n population.loc['Städteregion Aachen'] = population.loc['StädteRegion Aachen']\n population = population.drop('StädteRegion Aachen')\n\n\n return population # type: ignore\n\n\n@joblib_memory.cache\ndef get_population() -> pd.DataFrame:\n \"\"\"Returns a DataFrame with population data\"\"\"\n source = jhu_population_url\n population = fetch_csv_data_from_url(source)\n # Only include population of entire countries by excluding rows that belong\n # to a province or state\n population = population[population['Province_State'].isnull()]\n population = population[population[\"Population\"] != 0]\n population = (\n population\n .groupby('Country_Region')\n .sum() # Here we sum over individual regions in a country to get the total country population\n .rename(columns={\"Population\": \"population\"}) # Rename Population to population\n )\n return population # type: ignore\n\n\ndef population(country: str,\n region: str = None, subregion: str = None) -> Union[int, None]:\n \"\"\"\n Returns an `int` which corresponds to the population.\n Only supports JHU countries and Germany Landkreise so far.\n\n Example:\n\n $> population(country=\"Germany\", subregion=\"LK Pinneberg\")\n 316103\n $> population(country=\"France\")\n 65273512\n \"\"\"\n df = fetch_csv_data_from_url(jhu_population_url)\\\n .rename(columns={\"Population\": \"population\",\n \"Country_Region\": \"country\",\n \"Province_State\": \"region\",\n \"Admin2\": \"subregion\"})\n df = df[df['population'].notnull()]\n\n if country in df.country.values:\n if region is None and subregion is None:\n # use JHU data\n return int(df[(df['country'] == country)\n & (df['region'].isnull())\n & (df['subregion'].isnull())\n ].population)\n elif region and subregion:\n raise NotImplementedError(\"Cannot use both region and subregion\")\n\n elif country.casefold() == 'germany':\n if region or subregion:\n df = germany_get_population()\n if region in df['BL'].values:\n return int(df[df['BL'] == region].population.sum())\n elif subregion in df.index:\n return int(df.population[subregion])\n elif region in df.index: # silently try to use as subregion\n return int(df.population[region])\n else:\n raise NotImplementedError(f\"{region} in neither in available German Lands nor in Landkreises. \" \\\n f\"These are {', '.join(sorted(df['BL'].drop_duplicates()))} for Lands and \" \\\n f\"{', '.join(sorted(df.index))} for Landkreises.\")\n else:\n if region or subregion:\n if region in df['region'].values:\n combined_key = f\"{region}, {country}\"\n if combined_key in df['Combined_Key'].values: # the total population of the region is known\n return int(df[df['Combined_Key'] == combined_key].population)\n else: # there's no total population in the dataset, we have to sum up on our own\n return int(df[df['region'] == region].population.sum())\n elif subregion in df['subregion'].values:\n return int(df.population[subregion])\n elif region in df['subregion']: # silently try to use as subregion\n return int(df.population[subregion])\n else:\n return\n else:\n return\n\n\n@joblib_memory.cache\ndef get_incidence_rates_countries(period=14):\n cases = fetch_cases()\n deaths = fetch_deaths()\n\n cases = cases.groupby(cases.index).sum().astype(int)\n deaths = deaths.groupby(deaths.index).sum().astype(int)\n\n # Sanity checks that the column format is as expected\n assert all(cases.columns == deaths.columns)\n assert all(cases.columns[:2] == [\"Lat\", \"Long\"])\n\n yesterday = datetime.datetime.now() - datetime.timedelta(days=1)\n fortnight_ago = yesterday - datetime.timedelta(days=period+1)\n periods = (fortnight_ago < pd.to_datetime(cases.columns[2:])) & (\n pd.to_datetime(cases.columns[2:]) < yesterday\n )\n periods = np.concatenate((np.full(2, False), periods)) # Add the 3 ignored columns\n\n assert len(periods) == len(cases.columns)\n\n cases_sum = (\n cases[cases.columns[periods]]\n .diff(axis=1)\n .sum(axis=1).astype(int)\n .to_frame(f\"{period}-day-sum\")\n )\n deaths_sum = (\n deaths[deaths.columns[periods]]\n .diff(axis=1)\n .sum(axis=1).astype(int)\n .to_frame(f\"{period}-day-sum\")\n )\n\n # Now we have tables like:\n # 14-day-sum\n # Country/Region\n # Afghanistan 841.0\n # ... ...\n # Zimbabwe 1294.0\n #\n # [266 rows x 1 columns]\n # Where the values are the total cases/deaths in the past `period` days\n\n population = (\n get_population()\n .population.astype(int)\n )\n\n cases_incidence = cases_sum.join(population)\n cases_incidence.index.name = \"Country\"\n cases_incidence[f\"{period}-day-incidence-rate\"] = (\n cases_incidence[f\"{period}-day-sum\"] / cases_incidence[\"population\"] * 100_000\n ).round(decimals=1)\n deaths_incidence = deaths_sum.join(population)\n deaths_incidence.index.name = \"Country\"\n deaths_incidence[f\"{period}-day-incidence-rate\"] = (\n deaths_incidence[f\"{period}-day-sum\"] / deaths_incidence[\"population\"] * 100_000\n ).round(decimals=1)\n\n # We could join the tables, but it's easier to join them than to split so\n # we'll just return two instead\n return cases_incidence, deaths_incidence\n\n\n@joblib_memory.cache\ndef get_incidence_rates_germany(period=14):\n germany = fetch_data_germany()\n germany = germany.rename(\n columns={\"AnzahlFall\": \"cases\", \"AnzahlTodesfall\": \"deaths\"}\n )\n\n yesterday = datetime.datetime.now() - datetime.timedelta(days=1)\n fortnight_ago = yesterday - datetime.timedelta(days=period)\n periods = (fortnight_ago < germany.index) & (germany.index < yesterday)\n\n index = germany[['Bundesland', 'Landkreis']]\n\n index['Landkreis'] = 'Germany: ' + index['Landkreis']\n index['Bundesland'] = '(' + index['Bundesland'] + ')'\n\n germany['metadata-index'] = index['Landkreis'] + ' ' + index['Bundesland']\n\n # save the list of districts for the future. There must be 412 elements\n all_districts = germany.groupby(\"Landkreis\").agg({'Bundesland': 'first', 'metadata-index': 'first'})\n\n # Limit the timeframe to the last `period` days (we may loose some of districts here):\n germany = germany.iloc[periods]\n\n cases_sum = (\n germany.groupby(\"Landkreis\")\n .agg({'cases': 'sum', 'Bundesland': 'first', 'metadata-index': 'first'})\n .rename(columns={\"cases\": f\"{period}-day-sum\"})\n )\n # restore dropped districts:\n if len(cases_sum) < len(all_districts):\n cases_sum = cases_sum.reindex(all_districts.index, fill_value=0)\n for kreis in cases_sum[cases_sum[f'{period}-day-sum'] == 0].index:\n cases_sum.loc[kreis, 1:] = all_districts.loc[kreis]\n\n deaths_sum = (\n germany.groupby(\"Landkreis\")\n .agg({'deaths': 'sum', 'Bundesland': 'first', 'metadata-index': 'first'})\n .rename(columns={\"deaths\": f\"{period}-day-sum\"})\n )\n # restore dropped districts:\n if len(deaths_sum) < len(all_districts):\n deaths_sum = deaths_sum.reindex(all_districts.index, fill_value=0)\n for kreis in deaths_sum[deaths_sum[f'{period}-day-sum'] == 0].index:\n deaths_sum.loc[kreis, 1:] = all_districts.loc[kreis]\n\n # Now we have tables like:\n # cases\n # Landkreis\n # LK Ahrweiler 32\n # ... ...\n # StadtRegion Aachen 109\n # [406 rows x 1 columns]\n # Where the values are the total cases/deaths in the past `period` days\n\n population = germany_get_population().population.astype(int).to_frame()\n\n cases_incidence = cases_sum.join(population)\n cases_incidence[f\"{period}-day-incidence-rate\"] = (\n cases_incidence[f\"{period}-day-sum\"] / cases_incidence[\"population\"] * 100_000\n ).round(decimals=1)\n # one-line-summary is used for the index entry on the table\n cases_incidence['one-line-summary'] = (cases_incidence.index\n .map(lambda x: x[3:] + \" (LK)\" if x.startswith(\"LK \") else x)\n .map(lambda x: x[3:] + \" (SK)\" if x.startswith(\"SK \") else x)\n + ' (' + cases_incidence['Bundesland'] + ')'\n )\n\n deaths_incidence = deaths_sum.join(population)\n deaths_incidence[f\"{period}-day-incidence-rate\"] = (\n deaths_incidence[f\"{period}-day-sum\"] / deaths_incidence[\"population\"] * 100_000\n ).round(decimals=1)\n deaths_incidence['one-line-summary'] = (deaths_incidence.index\n .map(lambda x: x[3:] + \" (LK)\" if x.startswith(\"LK \") else x)\n .map(lambda x: x[3:] + \" (SK)\" if x.startswith(\"SK \") else x)\n + ' (' + deaths_incidence['Bundesland'] + ')'\n )\n\n # We could join the tables, but it's easier to join them than to split so\n # we'll just return two instead\n return cases_incidence, deaths_incidence\n\n\n\n@joblib_memory.cache\ndef fetch_data_hungary_last_execution():\n return datetime.datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\")\n\n\n@joblib_memory.cache\ndef fetch_data_hungary():\n \"\"\"\n Fetch data for Hungary from https://github.com/sanbrock/covid19\n\n Dataset does not contain the number of deaths in each county/capital city.\n \"\"\"\n datasource = hungary_data\n\n t0 = time.time()\n print(f\"Please be patient - downloading data from {datasource} ...\")\n hungary = pd.read_csv(datasource)\n delta_t = time.time() - t0\n print(f\"Completed downloading {len(hungary)} rows in {delta_t:.1f} seconds.\")\n\n # Dropping the last row, because it is a duplicate of header.\n hungary.drop(hungary.index[-1], inplace=True)\n # Will be at least one date with no values.\n hungary.dropna(inplace=True)\n\n hungary = hungary.astype({col_name: int for col_name in hungary.columns[1:]})\n\n fetch_data_hungary_last_execution()\n return hungary\n\n\ndef get_counties_hungary():\n # return fetch_data_hungary().columns[1:]\n return ['Bács-Kiskun', 'Baranya', 'Békés', 'Borsod-Abaúj-Zemplén', 'Budapest', 'Csongrád', 'Fejér',\n 'Győr-Moson-Sopron', 'Hajdú-Bihar', 'Heves', 'Jász-Nagykun-Szolnok', 'Komárom-Esztergom', 'Nógrád', 'Pest',\n 'Somogy', 'Szabolcs-Szatmár-Bereg', 'Tolna', 'Vas', 'Veszprém', 'Zala']\n\n\ndef get_region_hungary(county):\n \"\"\"\n Returns cases int time series and label for county in Hungary.\n\n \"\"\"\n counties_and_the_capital_city = get_counties_hungary()\n\n if county not in counties_and_the_capital_city:\n raise ValueError(f'{county} must be one of: \\n{counties_and_the_capital_city}')\n\n hungary = fetch_data_hungary()\n\n hungary.set_index(pd.to_datetime(hungary['Dátum']), inplace=True)\n cases = hungary[county]\n region_label = f'Hungary-{county}'\n cases.name = region_label + \" cases\"\n\n return cases, None\n\n\ndef plot_time_step(ax, series, style=\"-\", labels=None, logscale=True):\n \"\"\"Plot the series as cumulative cases/deaths, plotted as step function.\n Parameters:\n - ax : axis object from matplotlib\n - series: the actual data as pandas Series\n - style : matplotlib style/Colour\n - labels: tuple of (region_name, kind) where\n both elements are strings, and 'kind' is either 'cases' or 'deaths'.\n - logscale: plot y-axis in logscale (default=True)\n\n Returns ax object.\n \"\"\"\n\n ax.step(series.index, series.values, style, label=series.name,\n linewidth=LW)\n if logscale:\n ax.set_yscale('log')\n ax.legend()\n ax.set_ylabel(\"total numbers\")\n ax.yaxis.set_major_formatter(ScalarFormatter())\n return ax\n\n\ndef plot_incidence_rate(ax, cases: pd.Series, country: str,\n region: str = None, subregion: str = None,\n dates: str = None, weeks: int = 0):\n if dates:\n cases = cut_dates(cases, dates)\n if weeks:\n cases = cases[-7 * (weeks+1):] # we need to add one week, because we loose one on rolling\n\n habitants = population(country=country, region=region, subregion=subregion)\n\n if habitants:\n incidence = (cases.diff().dropna().rolling(7).sum()/habitants*100000)\n norm_title = \"\\n(per 100K people)\"\n else:\n incidence = (cases.diff().dropna().rolling(7).sum())\n norm_title = ''\n\n # convert dates to numbers first\n inxval = date2num(incidence.index.to_pydatetime())\n # smoothing\n if len(incidence.values) > 100:\n # the number of consecutive segments of the same color, bigger number produces less spaces between segments:\n chain_len = 2 # 2 means that each segment of the curve is of length 2\n else:\n chain_len = 1\n # a little trick here: we can't split odd amount of points into even number of segments of length 2, therefore\n # we simply throw away the very first point of the curve making the number of points even\n starting_point = len(inxval) % chain_len\n points = np.array([inxval[starting_point:], incidence.values[starting_point:]]).T.reshape(-1, chain_len, 2)\n segments = np.concatenate([points[:-1], points[1:]], axis=1)\n\n # colormap: the line is green on the bottom, near zero value, then it's yellow around 30,\n # then in becomes more red, and above 100 it's totally maroon\n colors = [\"green\", \"gold\", \"red\", \"maroon\"]\n cmap = LinearSegmentedColormap.from_list('RedGreen', colors, len(incidence))\n norm = plt.Normalize(0, 100)\n if country == \"Germany\" and not dates: # see https://github.com/oscovida/oscovida/issues/228\n # plot the end of the incidence curve dotted for Germany (the last four points)\n lc = LineCollection(segments[:-int(4/chain_len)], cmap=cmap, norm=norm, linewidth=LW)\n lc_end = LineCollection(segments[-int(4/chain_len):], cmap=cmap, norm=norm, linewidth=3, linestyles=[':'], alpha=0.5)\n lc_end.set_array(incidence.values[-int(4/chain_len)::chain_len]) # set the colors according to y values\n ax.add_collection(lc_end)\n else:\n lc = LineCollection(segments, cmap=cmap, norm=norm, linewidth=LW)\n lc.set_array(incidence.values[::chain_len]) # set the colors according to y values\n\n # add collection to axes\n ax.add_collection(lc)\n ax.autoscale_view()\n ax.set_ylabel(\"7-day incidence rate\"+norm_title)\n ax.yaxis.set_major_formatter(ScalarFormatter())\n\n x, y = incidence.index[-1], incidence.values[-1]\n ax.plot([x], [y], marker=\"+\", color=cmap(norm(y))) # marker at the end of the line\n ax.annotate(f\"{y:.1f}\", xy=(x, y * 1.1), color=cmap(norm(y))) # marker annotation\n return ax\n\n\ndef compute_daily_change(series: pd.Series) -> Tuple[Tuple[pd.Series, str],\n Tuple[pd.Series, str],\n Tuple[pd.Series, str]]:\n \"\"\"returns (change, smooth, smooth2)\n\n where 'change' is a tuple of (series, label)\n and smooth is a tuple of (series, label).\n and smooth2 is a tuple of (series, label).\n\n 'change' returns the raw data (with nan's dropped)\n 'smooth' makes the data smoother\n 'smooth2' does some additional smoothing - more artistic than scientific\n\n The 'change' under consideration, is the day-to-day change of the series.\n We assume that there is one entry per day in the Series.\n\n \"\"\"\n diff = series.diff().dropna()\n label = \"\"\n change = diff, label\n\n # smoothed curve, technical description\n smooth_label = f\"Gaussian window (stddev=3 days)\"\n # shorter description\n smooth_label = f\"(rolling 7d mean)\"\n\n # Smoothing step 1: get rid of weekly cycles\n rolling_series = diff.rolling(7, center=True,\n win_type=None,\n min_periods=7).mean()\n smooth = rolling_series, smooth_label\n\n # extra smoothing for better visual effects\n rolling_series2 = rolling_series.rolling(7, center=True,\n win_type='gaussian',\n min_periods=7).mean(std=3)\n\n # extra smooth curve\n smooth2_label = \"Smoothed \" + smooth_label\n # shorter description\n smooth2_label = smooth_label\n\n smooth2 = rolling_series2, smooth2_label\n\n return change, smooth, smooth2\n\n\ndef plot_daily_change(ax, series: pd.Series, color: str, labels: Tuple[str, str] = None,\n country: str = None, region: str = None, subregion: str = None,\n dates: str = None, weeks: int = 0, uncertainty: int = 7):\n \"\"\"Given a series of data and matplotlib axis ax, plot the\n - difference in the series data from day to day as bars and plot a smooth\n - line to show the overall development\n\n - series is pandas.Series with data as index, and cumulative cases (or\n deaths)\n - `color` is color to be used for plotting\n - `dates` or `weeks` specify the time range to plot\n - `uncertainty` is a number of days we plot as a dashed line\n\n See plot_time_step for documentation on other parameters.\n \"\"\"\n bar_alpha = 0.2\n if labels is None:\n type_label = \"\"\n region_label = \"\"\n else:\n region_label, type_label = labels\n ax_label = region_label + \" new \" + type_label\n (change, change_label), _, (smooth2, smooth2_label) = compute_daily_change(series)\n if dates:\n change = cut_dates(change, dates)\n smooth2 = cut_dates(smooth2, dates)\n uncertainty = 1\n if weeks:\n change = change[-7 * weeks:]\n smooth2 = smooth2[-7 * weeks:]\n\n if country and (region or subregion):\n habitants = population(country=country, region=region, subregion=subregion)\n else:\n habitants = population(region_label)\n if habitants and max(change) > 0:\n # create another Y-axis on the right hand side\n # unfortunately there's no simple way of swapping the axes,\n # therefore we define normalised axis first\n ax2 = ax\n # this is just to be sure that we plot the same graph (please leave it commented in the production):\n # ax2.plot(smooth2.index, smooth2.values * 1E5 / habitants, color='green')\n ax2.set_ylim((0, max(change) * 1E5 / habitants))\n ax2.set_ylabel('daily change\\nnormalised per 100K')\n\n ax1 = ax2.twinx() # create an independent y-axis\n ax1.set_ylim((0, max(change)))\n\n ticks = align_twinx_ticks(ax_left=ax2, ax_right=ax1)\n ax1.yaxis.set_major_locator(FixedLocator(ticks))\n ax1.bar(change.index, change.values, color=color,\n label=ax_label, alpha=bar_alpha, linewidth=LW)\n # RKI data for deaths in German regions is very untrustworthy,\n # see https://oscovida.github.io/2020-germany-reporting-delay-meldeverzug.html\n if country == \"Germany\" and (region or subregion) and labels[1] == \"deaths\" and not dates:\n uncertainty = 6 * 7 # six weeks\n\n ax1.plot(smooth2.index[:-uncertainty], smooth2.values[:-uncertainty], color=color,\n label=ax_label + \" \" + smooth2_label, linewidth=LW)\n # uncertain (dashed) line on the right\n if uncertainty > 1:\n uncertain_tail(ax1, series[-2 * uncertainty:].diff().dropna(), days=uncertainty,\n color=color, linewidth=LW, alpha=0.7)\n\n ax1.legend()\n ax1.set_ylabel('daily change')\n\n else:\n ax.tick_params(left=True, right=True, labelleft=True, labelright=True)\n ax.yaxis.set_ticks_position('both')\n ax.plot(smooth2.index, smooth2.values, color=color,\n label=ax_label + \" \" + smooth2_label, linewidth=LW)\n ax.bar(change.index, change.values, color=color,\n label=ax_label, alpha=bar_alpha, linewidth=LW)\n\n ax.legend()\n ax.set_ylabel('daily change')\n\n\n # Data cleaning: France new cases daily reports had a huge spike\n # on 12 April 2020 with 26849 reported new cases. This would set\n # too large a ymax for a while, which was fixed manually by setting\n # ymax to min(10000, ymax)... until in October 2020 daily reported\n # cases soared beyond that anomalous reported value of 12 April 2020.\n # France also has a negative value of circa -2000 on 22 April 2020.\n # We limit the y-scale to correct manually for this:\n if region_label == \"France\" and type_label == \"cases\":\n # get current limits\n ymin, ymax = ax.get_ylim()\n ax.set_ylim([max(-500, ymin), ymax])\n\n return ax\n\n\ndef compute_doubling_time(series, minchange=0.5, labels=None, debug=False):\n\n \"\"\"\n Compute and return doubling time of (assumed exponential) growth, based on two\n data points. We use data points from subsequent days.\n\n returns (dtime, smooth)\n\n Where 'dtime' is a tuple of (series, label)\n and smooth is a tuple of (series, label).\n\n 'dtime' returns the raw data (with nan's dropped)\n 'smooth' makes the data smoother\n\n The 'dtime' under consideration, is the day-to-day dtime of the series.\n We assume that there is one entry per day in the Series.\n\n If there is not enough data to compute the doubling time, returns\n ((None, message), (None, None)) where 'message' provides\n data for debugging the analysis.\n \"\"\"\n\n if labels is None:\n label = \"\"\n region = \"\"\n else:\n region, label = labels\n\n\n # only keep values where there is a change of a minumum number\n # get rid of data points where change is small values\n (f, f_label) , (change_smoothed, smoothed_label), _ = compute_daily_change(series)\n sel = change_smoothed < minchange\n reduced = series.drop(f[sel].index, inplace=False)\n if len(reduced) <= 1: # no data left\n return (None, \"no data in reduced data set\"), (None, None)\n\n ratio = reduced.pct_change() + 1 # computes q2/q1 =\n ratio_smooth = reduced.rolling(7, center=True, win_type='gaussian',\n min_periods=7).mean(std=3).pct_change() + 1\n\n if debug:\n print(f\"len(ratio) = {len(ratio.dropna())}, {ratio}\")\n print(f\"len(ratio_smooth) = {len(ratio_smooth.dropna())}, {ratio_smooth}\")\n\n\n # can have np.inf and np.nan at this point in ratio\n # if those are the only values, then we should stop\n ratio.replace(np.inf, np.nan, inplace=True)\n if ratio.isna().all():\n return (None, \"Cannot compute ratio\"), (None, None)\n\n ratio_smooth.replace(np.inf, np.nan, inplace=True)\n if ratio_smooth.isna().all():\n # no useful data in smooth line, but data for dots is okay\n # Give up anyway\n return (None, \"Cannot compute smooth ratio\"), (None, None)\n\n # computes q2/q1\n # compute the actual doubling time\n dtime = double_time_exponential(ratio, t2_minus_t1=1)\n dtime_smooth = double_time_exponential(ratio_smooth, t2_minus_t1=1)\n\n if debug:\n print(f\"len(dtime) = {len(dtime.dropna())}, {dtime}\")\n print(f\"len(dtime_smooth) = {len(dtime_smooth.dropna())}, {dtime_smooth}\")\n\n # can have np.inf and np.nan at this point in dtime_smooth and dtime\n # if those are the only values, then we should stop\n dtime_smooth.replace(np.inf, np.nan, inplace=True)\n if dtime_smooth.isna().all():\n # We could at this point carry on and return the dtime, but not dtime_smooth.\n # This may not be a common use case and not worth the extra complications.\n return (None, \"Cannot compute doubling time\"), (None, None)\n\n dtime.replace(np.inf, np.nan, inplace=True)\n if dtime.isna().all():\n return (None, \"Cannot compute smooth doubling time\"), (None, None)\n\n dtime_label = region + \" doubling time \" + label\n dtime_smooth_label = dtime_label + ' 7-day rolling mean (stddev=3)'\n # simplified label\n dtime_smooth_label = dtime_label + ' (rolling mean)'\n\n return (dtime, dtime_label), (dtime_smooth, dtime_smooth_label)\n\n\n@limit_to_smoothed\ndef plot_doubling_time(ax, series, color, minchange=0.5, labels=None, debug=False):\n \"\"\"Plot doubling time of series, assuming series is accumulated cases/deaths as\n function of days.\n\n Returns axis.\n\n See plot_time_step for documentation on other parameters.\n \"\"\"\n\n if labels is None:\n labels = \"\", \"\"\n region, label = labels\n\n (dtime, dtime_label), (dtime_smooth, dtime_smooth_label) = \\\n compute_doubling_time(series, minchange=minchange, debug=debug, labels=labels)\n\n if dtime is None:\n if debug:\n print(dtime_label)\n return ax\n\n ax.plot(dtime.index, dtime.values, 'o', color=color, alpha=0.3, label=dtime_label)\n\n # good to take maximum value from here\n dtime_smooth.replace(np.inf, np.nan, inplace=True) # get rid of x/0 results, which affect max()\n # ymax = min(dtime_smooth.max()*1.5, 5000) # China has doubling time of 3000 in between\n\n ## Adding a little bit of additional smoothing just for visual effects\n dtime_smooth2 = dtime_smooth.rolling(3, win_type='gaussian', min_periods=1, center=True).mean(std=1)\n\n # ax.set_ylim(0, max(ymax, ax.get_ylim()[1])) # since we combine two plots, let's take another one into account\n ax.plot(dtime_smooth2.index, dtime_smooth2.values, \"-\", color=color, alpha=1.0,\n label=dtime_smooth_label,\n linewidth=LW)\n ax.set_ylabel(f\"{labels[1]}\\ndoubling time [days]\")\n return ax\n\n\ndef compute_growth_factor(series):\n \"\"\"returns (growth, smooth)\n\n where 'growth' is a tuple of (series, label)\n and smooth is a tuple of (series, label).\n\n 'growth' returns the raw data (with nan's dropped)\n 'smooth' makes the data smoother\n\n \"\"\"\n\n # start from smooth diffs as used in plot 1\n (change, change_label) , (smooth, smooth_label), \\\n (smooth2, smooth2_label) = compute_daily_change(series)\n\n # Compute ratio of yesterday to day\n f = smooth.pct_change() + 1 # compute ratio of subsequent daily changes\n # f for growth Factor\n label = \"\"\n growth = (f, label)\n\n # division by zero may lead to np.inf in the data: get rid of that\n f.replace(np.inf, np.nan, inplace=True) # seems not to affect plot\n\n # pct_change computed between two values that are NaN each, returns 0\n # (which should be interpreted as: no change from yesterday's NaN to\n # today's NaN. However, the way we use it, this gives misleading values. )\n # Let's take out those values from f, where the input data was NaN:\n f[smooth.isna()]=np.nan\n\n # Compute smoother version for line in plots\n f_smoothed = f.rolling(7, center=True, win_type='gaussian', min_periods=3).mean(std=2)\n smooth_label = f\"Gaussian window (stddev=2 days)\"\n # simplified label\n smooth_label = \"(rolling mean)\"\n\n smoothed = f_smoothed, smooth_label\n\n return growth, smoothed\n\n\n#def plot_growth_factor(ax, series, color):\n# \"\"\"relative change of number of new cases/deaths from day to day\n# See https://youtu.be/Kas0tIxDvrg?t=330, 5:30 onwards\n#\n# Computed based smooth daily change data.\n# \"\"\"\n#\n# # get smooth data from plot 1 to base this plot on\n# (f, f_label) , (f_smoothed, smoothed_label) = compute_growth_factor(series)\n#\n#\n# label = series.country + \" \" + series.label + \" growth factor \" + f_label\n# ax.plot(f.index, f.values, 'o', color=color, alpha=0.3, label=label)\n#\n# label = series.country + \" \" + series.label + \" growth factor \" + smoothed_label\n# ax.plot(f_smoothed.index, f_smoothed.values, '-', color=color, label=label, linewidth=LW)\n#\n# # ax.legend(loc='lower left')\n# ax.legend()\n# ax.set_ylabel(\"growth factor\")\n# ax.set_ylim(0.5, 1.5) # should generally be below 1\n# ax.plot([series.index.min(), series.index.max()], [1.0, 1.0], '-C3') # label=\"critical value\"\n# return ax\n\n\n# Computation or R\n#\ndef compute_R(daily_change, tau=4):\n \"\"\"Given a time series s, estimate R based on description from RKI [1].\n\n [1] [Robert Koch Institute: Epidemiologisches Bulletin 17 | 2020 23. April 2020]\n https://www.rki.de/DE/Content/Infekt/EpidBull/Archiv/2020/Ausgaben/17_20.html\n\n Steps:\n\n 1. Compute change from day to day\n 2. Take tau-day averages (tau=4 is recommended as of April/May 2020)\n 3. divide average from days 4 to 7 by averages from day 0 to 3, and use this data point for day[7]\n\n \"\"\"\n # change = s.diff()\n change = daily_change\n mean4d = change.rolling(tau).mean()\n R = mean4d / mean4d.shift(tau)\n R2 = R.shift(-tau) # this is not the RKI method, but seems more appropriate:\n # we centre the reported value between the 2-intervals of length tau\n # that have been used to compute it.\n\n # Can we create an R-value of 1.0 for small numbers (approaching 0)\n # of new cases/deaths? At least if we have no new cases, then\n # R=1 seems a reasonable outcome.\n R2[(mean4d.shift(tau) == 0.0) & (mean4d == 0)] = 1.0\n\n return R2\n\n\ndef min_max_in_past_n_days(series, n, at_least = [0.75, 1.25], alert=[0.1, 100], print_alert=False):\n \"\"\"Given a time series, find the min and max values in the time series within the last n days.\n\n If those values are within the interval `at_least`, then use the values in at_least as the limits.\n if those values are outside the interval `at_least` then exchange the interval accordingly.\n\n If the values exceed the min and max value in 'alerts', then print an error message.\n Return min, max.\n \"\"\"\n if n > len(series):\n n = len(series)\n\n series = series.replace(math.inf, math.nan)\n series = series.replace(-math.inf, math.nan)\n\n min_ = series[-n:].min() - 0.1 # the -0.1 is to make extra space because the line we draw is thick\n max_ = series[-n:].max() + 0.1\n\n if min_ < at_least[0]:\n min_final = min_\n else:\n min_final = at_least[0]\n\n if max_ > at_least[1]:\n max_final = max_\n else:\n max_final = at_least[1]\n\n if print_alert:\n if max_final > alert[1]:\n # print(f\"Large value for R_max = {max_final} > {alert[1]} in last {n} days: \\n\", series[-n:])\n print(f\"Large value for R_max = {max_final} > {alert[1]} in last {n} days: \\n\")\n if min_final < alert[0]:\n # print(f\"Small value for R_min = {min_final} < {alert[0]} in last {n} days: \\n\", series[-n:])\n print(f\"Small value for R_min = {min_final} < {alert[0]} in last {n} days: \\n\")\n\n\n # print(f\"DDD: min_={min_}, max_={max_}\")\n return min_final, max_final\n\n\ndef plot_reproduction_number(ax, series, color_g='C1', color_R='C4',\n yscale_days=28, max_yscale=10, smoothing=0,\n labels=None):\n \"\"\"\n - series is expected to be time series of cases or deaths\n - label is 'cases' or 'deaths' or whatever is desired as the description\n - country is the name of the region/country\n - color_g is the colour for the growth factor\n - color_R is the colour for the reproduction number\n\n R number is calculated based on a 7-day average of the daily changes.\n See details in compute_R().\n\n By default the resulting data is not smoothed further. If desired,\n for visual purposes, the parameter `smoothing` can be given the number\n of days over which the computer R-values are averaged out (using a Gaussian\n window with a width of 3 days). A number of 5 or 7 gives smooth results.\n However, the plotted data then stops 5/2 (=2 days) or 7/2 (=3) days earlier.\n\n See plot_time_step for documentation on other parameters.\n \"\"\"\n\n if labels is None:\n region, label = \"\", \"\"\n else:\n region, label = labels\n\n # get smooth data for growth factor from plot 1 to base this plot on\n (f, f_label), (f_smoothed, smoothed_label) = compute_growth_factor(series)\n\n label_ = region + \" \" + label + \" daily growth factor \" + f_label\n ax.plot(f.index, f.values, 'o', color=color_g, alpha=0.3, label=label_)\n\n label_ = region + \" \" + label + \" daily growth factor \" + smoothed_label\n ax.plot(f_smoothed.index, f_smoothed.values, '-', color=color_g,\n label=label_, linewidth=LW, alpha=0.7)\n\n\n # # data for computation or R\n # start from smooth diffs as used in plot 1\n (change, change_label) , (smooth, smooth_label), \\\n (smooth2, smooth2_label) = compute_daily_change(series)\n\n # we only use one return value (the 7-day average)\n smooth_diff = smooth\n R = compute_R(smooth_diff)\n # do some additional smoothing\n if smoothing != 0:\n R = R.rolling(smoothing, win_type='gaussian', center=True,\n min_periods=smoothing).mean(std=3)\n ax.plot(R.index, R, \"-\", color=color_R,\n label=region + f\" estimated R (using {label})\",\n linewidth=4.5, alpha=1)\n\n # choose y limits so that all data points of R in the last 28 days are visible\n min_, max_ = min_max_in_past_n_days(R, yscale_days);\n\n # set upper bound for R\n # (Germany data has huge spike in February )\n if max_ > max_yscale:\n max_ = max_yscale\n\n ax.set_ylim([min_, max_]);\n\n # Plot ylim interval for debugging\n # ax.plot([R.index.min(), R.index.max()], [min_, min_], 'b-')\n # ax.plot([R.index.min(), R.index.max()], [max_, max_], 'b-')\n\n\n ax.set_ylabel(f\"R & growth factor\\n(based on {label})\")\n # plot line at 0\n ax.plot([series.index.min(), series.index.max()], [1.0, 1.0], '-C3') # label=\"critical value\"\n ax.legend()\n return ax\n\n\ndef get_region_label(country: str, region: str = None, subregion: str = None) -> str:\n \"\"\"\n Produce unique and unambiguous name from region and subregion\n \"\"\"\n # TODO: this might be used to decouple the label creation and fetching data\n _country = country.casefold()\n region_label = None\n if _country == 'germany':\n # if region == None and subregion == None:\n # region_label = _country\n if region is not None and subregion is None:\n region_label = f\"Germany-{region}\"\n elif region is None and subregion is not None:\n region_label = f\"Germany-{subregion}\"\n elif region is None and subregion is not None:\n region_label = f\"Germany-{subregion}\"\n\n elif _country == 'us' and region != None:\n region_label = f\"United States: {region}\"\n\n elif _country == 'hungary':\n # region -> térség\n # subregion -> kistérség\n # county -> megye\n\n if region is not None:\n region_label = f\"Hungary-{region}\"\n\n # finally:\n if not region_label:\n region_label = country\n\n return region_label\n\n\ndef get_country_data(country: str, region: str = None, subregion: str = None, verbose: bool = False,\n pad_RKI_data_to_yesterday: bool = True) -> Tuple[pd.Series, pd.Series]:\n \"\"\"Given the name of a country, get the Johns Hopkins data for cases and deaths,\n and return them as a tuple of pandas.Series objects and a string describing the region:\n (cases, deaths, region_label)\n\n If the country is \"Germany\", use the region (=Land) and subregion (=Kreis)\n to select the appropriate subset from the Robert Koch Institute. If only\n the region is provided, the data from all subregions in that region is\n accumulated.\n\n If the country is \"US\", get US data (states are available as regions) from Johns Hopkins\n repository.\n\n Returns \"cases, deaths, country_region\" where country region is a string\n describing the country and region.\n\n The series are resampled at a daily interval. Missing data points are replaced\n by the last provided value (seems reasonable for a data set representing\n cumulative numbers as a function of time: where no new data point is provided,\n assume the change was zero, thus the last data point can be re-used).\n\n Data from Johns Hopkins is reported daily, even if there is no change in numbers.\n\n Data from Robert Koch Institute (RKI) is only provided if the cumulative\n numbers change. We thus resample the data set if the last provided data\n point is not from yesterday, up to yesterday (which is the most recent day\n for which data could be available).\n\n Note that some data sets are updated retrospectively (in particular data\n from RKI), so the numbers for the a particular date may increase after one\n or two days (or even later in extreme cases).\n\n \"\"\"\n special_countries = {\n 'germany': (germany_get_region, {'state': region, 'landkreis': subregion,\n 'pad2yesterday': pad_RKI_data_to_yesterday}),\n 'us': (get_region_US, {'state': region}),\n 'hungary': (get_region_hungary, {'county': region})\n }\n\n if country.casefold() in special_countries and (region is not None or subregion is not None):\n func, kwargs = special_countries[country.casefold()]\n c, d = func(**kwargs)\n else:\n c, d = get_country_data_johns_hopkins(country) # use johns hopkins data\n\n len_cases1 = len(c)\n # hungarian county data doesn't contain number of deaths\n len_deaths1 = 0 if d is None else len(d)\n # resample data so we have one value per day\n c = c.resample(\"D\").pad()\n d = None if d is None else d.resample(\"D\").pad()\n\n len_cases2 = len(c)\n len_deaths2 = 0 if d is None else len(d)\n\n if verbose:\n print(f\"get_country_data: cases [{len_cases1}] -> [{len_cases2}]\")\n print(f\"get_country_data: deaths[{len_deaths1}] -> [{len_deaths2}]\")\n return c, d\n\n\ndef day0atleast(v0: int, series: pd.Series) -> pd.Series:\n try:\n day0 = series[series > v0].index[0]\n except IndexError: # means no days found for which series.values > v0\n # print(f\"Haven't found value > {v0} in {series.name}\")\n result = pd.Series(dtype=object) # return an empty object\n return result\n # compute timedelta\n timedelta = series.index - day0\n # convert to int as index\n t = pd.to_numeric(timedelta.astype(\"timedelta64[D]\").astype(int))\n # Assemble new series\n result = pd.Series(index=t, data=series.values)\n return result\n\n\ndef align_sets_at(v0: int, df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Accepts data frame, and aligns so that all entries close to v0 are on the same row.\n\n Returns new dataframe with integer index (representing days after v0).\n \"\"\"\n res = pd.DataFrame()\n for col in df.columns:\n # res[col] = day0for(v0, df[col])\n series = day0atleast(v0, df[col])\n series.name = col\n res = pd.merge(res, series, how='outer', left_index=True, right_index=True)\n\n return res\n\n\ndef get_compare_data(countrynames, rolling=7):\n \"\"\"Given a list of country names, return two dataframes: one with cases and one with deaths\n where\n - each column is one country\n - data in the column is the diff of accumulated numbers\n - any zero values are removed for italy (data error)\n - apply some smoothing\n \"\"\"\n df_c = pd.DataFrame()\n df_d = pd.DataFrame()\n\n for countryname in countrynames:\n c, d = get_country_data_johns_hopkins(countryname)\n\n df_c[countryname] = c.diff().rolling(rolling, center=True).mean() # cases\n df_d[countryname] = d.diff().rolling(rolling, center=True).mean() # deaths\n\n return df_c, df_d\n\n\ndef plot_logdiff_time(ax, df, xaxislabel=None, yaxislabel=None, style=\"\", labels=True, labeloffset=2, v0=0,\n highlight={}, other_lines_alpha=0.4):\n \"\"\"highlight is dictionary: {country_name : color}\n\n - df: DataFrame with time series to align\n \"\"\"\n\n for i, col in enumerate(df.columns):\n if col in highlight:\n alpha = 1.0\n color = highlight[col]\n linewidth = 4\n else:\n alpha = other_lines_alpha\n # have only 10 colours\n color = style + 'C' + str(i % 10)\n linewidth = 2\n\n ax.plot(df.index, df[col].values, color, label=col, linewidth=linewidth, alpha=alpha)\n tmp = df[col].dropna()\n if len(tmp) > 0: # possible we have no data points\n x, y = tmp.index[-1], tmp.values[-1]\n ax.plot([x], [y], \"o\" + color, alpha=alpha) # dots at the end of each line\n if labels:\n # If we use the 'annotate' function on a data point with value 0 or a negative value,\n # we run into a bizarre bug that the created figure has very large dimensions in the\n # vertical direction when rendered to svg. The next line prevents this.\n #\n # Our fix/hack means that the label of the country will not be visible. That's not so bad\n # at the moment as the situation of zero new deaths causes the problem, and the infections\n # are higher and non-zero, thus we can see the country label in the infections plot.\n #\n # If this stops, we could consider choosing a data point from\n # earlier in the series to put the label there.\n #\n # The comparison for \"y < 0\" should not be necessary as the new deaths per day can at\n # most be zero. However, for Australia, there is a -1 reported for first of June,\n # which can lead to negative values when computing a rolling mean.\n y = np.NaN if y <= 0 else y\n\n # Add country/region name as text next to last data point of the line:\n ax.annotate(col, xy=(x + labeloffset, y), textcoords='data')\n else:\n ax.legend()\n ax.set_ylabel(yaxislabel)\n ax.set_xlabel(xaxislabel)\n ax.set_yscale('log')\n # use integer numbers for values > 1, and decimal presentation below\n # from https://stackoverflow.com/questions/21920233/matplotlib-log-scale-tick-label-number-formatting/33213196\n ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: '{:g}'.format(y)))\n # ax.set_xscale('log') # also interesting\n if isinstance(df.index[0], (int, np.integer)):\n ax.set_ylim(bottom=set_y_axis_limit(df, v0))\n ax.set_xlim(left=-1) #ax.set_xlim(-1, df.index.max())\n else:\n ax.legend(loc='upper left')\n ax.tick_params(left=True, right=True, labelleft=True, labelright=True)\n ax.yaxis.set_ticks_position('both')\n\n\ndef set_y_axis_limit(data, current_lim):\n \"\"\"The function analyses the data set given and lowers\n the y-limit if there are data points below `current_lim`\n\n :param data: data to plot\n :param current_lim: initial y-axis lower limit\n :return: new y-axis lower limit\n \"\"\"\n data_0 = data[data.index >= 0] # from \"day 0\" only\n limits = [0.01, 0.1, 1, 10, 100]\n # if we have values within the `limits`, we set the lower `y_limit` on the graph to the value on the left of bisect\n # example: if the minimum value is 3, then y_limit = 1\n index = bisect(limits, data_0.min().min())\n if 0 < index < len(limits):\n return limits[index - 1]\n elif index == 0:\n return limits[0]\n else:\n return current_lim\n\n\ndef make_compare_plot(main_country, compare_with=[\"Germany\", \"Australia\", \"Poland\", \"Korea, South\",\n \"Belarus\", \"Switzerland\", \"US\"],\n v0c=10, v0d=3, normalise=True, align=False):\n rolling = 7\n df_c, df_d = get_compare_data([main_country] + compare_with, rolling=rolling)\n\n if align:\n res_c = align_sets_at(v0c, df_c)\n res_d = align_sets_at(v0d, df_d)\n c_xlabel = f'days since {v0c} cases'\n d_xlabel = f'days since {v0d} deaths'\n else:\n res_c, res_d = df_c, df_d\n c_xlabel, d_xlabel = None, None\n\n if normalise:\n for country in res_c.keys():\n res_c[country] *= 100000 / population(country)\n res_d[country] *= 100000 / population(country)\n\n # We get NaNs for some lines. This seems to originate in the original data set not having a value recorded\n # for all days.\n # For the purpose of this plot, we'll just interpolate between the last and next known values.\n # We limit the number of fills to 3 days. (Just a guess to avoid accidental\n # filling of too many NaNs.)\n\n res_c = res_c.interpolate(method='linear', limit=3)\n res_d = res_d.interpolate(method='linear', limit=3)\n\n fig, axes = plt.subplots(2, 1, figsize=(10, 6))\n ax = axes[0]\n norm_str = '\\nper 100K people'\n plot_logdiff_time(ax, res_c, xaxislabel=c_xlabel,\n yaxislabel=f\"daily new cases{norm_str if normalise else ''}\\n(rolling 7-day mean)\",\n v0=v0c, highlight={main_country: \"C1\"}, labels=False)\n ax = axes[1]\n plot_logdiff_time(ax, res_d, xaxislabel=d_xlabel,\n yaxislabel=f\"daily new deaths{norm_str if normalise else ''}\\n(rolling 7-day mean)\",\n v0=v0d, highlight={main_country: \"C0\"}, labels=False)\n\n if not normalise:\n fig.tight_layout(pad=1)\n title = f\"Daily cases (top) and deaths (below) for {main_country}\"\n axes[0].set_title(title)\n\n return axes, res_c, res_d\n\n\n###################### Compare plots for Germany\n\ndef label_from_region_subregion(region_subregion):\n region, subregion = unpack_region_subregion(region_subregion)\n if subregion:\n if region:\n label = f\"{region}-{subregion}\"\n else:\n label = f\"{subregion}\"\n else:\n label = f\"{region}\"\n return label\n\n\ndef unpack_region_subregion(region_subregion):\n \"\"\"Convention for regions in Germany (could also be useful for other countries later):\n\n - region_subregion is either\n - a tuple of strings (region, subregion) or\n - a string \"region\"\n\n Return a a tuple (region, subregion), where subregion is None if not provided.\n \"\"\"\n if isinstance(region_subregion, tuple):\n if len(region_subregion) == 1:\n region = region_subregion[0]\n subregion = None\n elif len(region_subregion) == 2:\n region, subregion = region_subregion\n else:\n raise ValueError(\"region_subregion must be single value or 2-valued tuple\", region_subregion)\n else:\n # assume it is just the region\n assert isinstance(region_subregion, str)\n region, subregion = region_subregion, None\n return region, subregion\n\n\ndef get_compare_data_germany(region_subregion, compare_with_local, rolling=7):\n \"\"\"Given a region_subregion for Germany, and a list of region_subregion to compare with,\n return two dataframes: one with cases and one with deaths\n where\n - each column is one country\n - data in the column is the diff of accumulated numbers\n - any zero values are removed for italy (data error)\n - apply some smoothing\n\n See unpack_region_subregion for details on region_subregion.\n \"\"\"\n df_c = pd.DataFrame()\n df_d = pd.DataFrame()\n\n for reg_subreg in [region_subregion] + compare_with_local:\n\n region, subregion = unpack_region_subregion(reg_subreg)\n c, d = germany_get_region(state=region, landkreis=subregion)\n\n label = label_from_region_subregion((region, subregion))\n df_c[label] = c.diff().rolling(rolling, center=True).mean() # cases\n df_d[label] = d.diff().rolling(rolling, center=True).mean() # deaths\n\n return df_c, df_d\n\n\ndef get_compare_data_hungary(region, compare_with_local: list, rolling=7):\n \"\"\"Given a region for Hungary, and a list of regions to compare with,\n return two dataframes: one with cases and one with deaths\n where\n - each column is one country\n - data in the column is the diff of accumulated numbers\n - any zero values are removed for italy (data error)\n - apply some smoothing\n\n \"\"\"\n df_c = pd.DataFrame()\n # df_d = pd.DataFrame()\n for reg in [region] + compare_with_local:\n c, d = get_region_hungary(county=reg)\n label = str(reg)\n df_c[label] = c.diff().rolling(rolling, center=True).mean() # cases\n # df_d[label] = d.diff().rolling(rolling, center=True).mean() # deaths\n return df_c, None\n\n\ndef make_compare_plot_germany(region=None, subregion=None,\n compare_with=[], # \"China\", \"Italy\", \"Germany\"],\n compare_with_local=['Bayern',\n 'Berlin', 'Bremen',\n 'Hamburg', 'Hessen',\n 'Nordrhein-Westfalen',\n 'Sachsen-Anhalt'],\n v0c=10, v0d=1, normalise=True,\n weeks=0, dates=None):\n rolling = 7\n df_c1, df_d1 = get_compare_data_germany((region, subregion), compare_with_local, rolling=rolling)\n df_c2, df_d2 = get_compare_data(compare_with, rolling=rolling)\n\n # need to get index into same timezone before merging\n df_d1.set_index(df_d1.index.tz_localize(None), inplace=True)\n df_c1.set_index(df_c1.index.tz_localize(None), inplace=True)\n\n df_c = pd.merge(df_c1, df_c2, how='outer', left_index=True, right_index=True)\n df_d = pd.merge(df_d1, df_d2, how='outer', left_index=True, right_index=True)\n\n kwargs_c, kwargs_d = {}, {}\n\n if dates and weeks == 0:\n res_c = cut_dates(df_c, dates)\n res_d = cut_dates(df_d, dates)\n kwargs_c.update({'labels': False})\n kwargs_d.update({'labels': False})\n elif dates and weeks:\n raise ValueError(\"`dates` and `weeks` cannot be used together\")\n else:\n res_c = df_c[- weeks * 7:]\n res_d = df_d[- weeks * 7:]\n kwargs_d.update({'yaxislabel': '', 'labels': False})\n kwargs_c.update({'labels': False})\n kwargs_d.update({'labels': False})\n\n kwargs_c.update({\"yaxislabel\": \"daily new cases\\n(rolling 7-day mean)\"})\n kwargs_d.update({\"yaxislabel\": \"daily new deaths\\n(rolling 7-day mean)\"})\n\n # We get NaNs for some lines. This seems to originate in the original data set not having a value recorded\n # for all days.\n # For the purpose of this plot, we'll just interpolate between the last and next known values.\n # We limit the number of fills to 7 days. (Just a guess to avoid accidental\n # filling of too many NaNs.)\n res_c = res_c.interpolate(method='linear', limit=7)\n res_d = res_d.interpolate(method='linear', limit=7)\n\n if normalise:\n kwargs_c[\"yaxislabel\"] += \"\\nnormalised by 100K people\"\n kwargs_d[\"yaxislabel\"] += \"\\nnormalised by 100K people\"\n kwargs_c.update({'labels': False})\n kwargs_d.update({'labels': False})\n for area in res_c.keys():\n res_c[area] *= 100000 / population(\"Germany\", area)\n res_d[area] *= 100000 / population(\"Germany\", area)\n\n fig, axes = plt.subplots(2, 1, figsize=(10, 6))\n ax = axes[0]\n plot_logdiff_time(ax, res_c, v0=v0c, highlight={res_c.columns[0]: \"C1\"}, **kwargs_c)\n ax = axes[1]\n\n plot_logdiff_time(ax, res_d, v0=v0d, highlight={res_d.columns[0]: \"C0\"}, **kwargs_d)\n\n # fig.tight_layout(pad=1)\n\n title = f\"Daily cases (top) and deaths (below) for Germany: {label_from_region_subregion((region, subregion))}\"\n axes[0].set_title(title)\n\n return axes, res_c, res_d\n\n#######################\n\n\ndef choose_random_counties(exclude_region, size) -> list:\n counties = get_counties_hungary()\n assert exclude_region in counties\n\n counties.remove('Budapest')\n if exclude_region != 'Budapest':\n counties.remove(exclude_region)\n\n indices = np.arange(len(counties))\n np.random.shuffle(indices)\n\n counties = np.array(counties)\n choosen = counties[indices[:size]]\n choosen = list(np.concatenate((choosen, ['Budapest'])))\n return choosen\n\n\ndef make_compare_plot_hungary(region: str, compare_with_local: list, v0c=10):\n rolling = 7\n\n df_c1, _ = get_compare_data_hungary(region, compare_with_local, rolling=rolling)\n # df_c2, _ = get_compare_data(['Germany', 'Italy'], rolling=rolling)\n\n # need to get index into same timezone before merging\n df_c1.set_index(df_c1.index.tz_localize(None), inplace=True)\n # df_c = pd.merge(df_c1, df_c2, how='outer', left_index=True, right_index=True)\n\n res_c = align_sets_at(v0c, df_c1)\n res_c = res_c.interpolate(method='linear', limit=7)\n\n fig, axes = plt.subplots(2, 1, figsize=(10, 6))\n plot_logdiff_time(axes[0], res_c, f\"days since {v0c} cases\",\n \"daily new cases\\n(rolling 7-day mean)\",\n v0=v0c, highlight={res_c.columns[0]: \"C1\"}, labeloffset=0.5)\n\n # plot_no_data_available(axes[1], mimic_subplot=axes[0], text=\"daily new deaths\\n(rolling 7-day mean)\")\n axes[1].set_visible(False)\n\n title = f\"Daily cases for Hungary: {label_from_region_subregion(region)}\"\n axes[0].set_title(title)\n fig.tight_layout(pad=1)\n return axes, res_c, None\n\n\ndef plot_no_data_available(ax, mimic_subplot, text):\n # Hungary county deaths data missing\n xticks = mimic_subplot.get_xticks()\n yticks = mimic_subplot.get_yticks()\n ax.set_xticks(xticks)\n ax.set_yticks(yticks)\n ax.text(xticks.mean(), yticks.mean(),\n f'No data available\\n to plot {text}',\n horizontalalignment='center',\n verticalalignment='center')\n ax.set_yticklabels([])\n ax.set_xticklabels([])\n\n\ndef overview(country: str, region: str = None, subregion: str = None,\n savefig: bool = False, dates: str = None,\n weeks: int = 0, data: Tuple[pd.Series, pd.Series] = None) -> Tuple[plt.axes, pd.Series, pd.Series]:\n \"\"\"The `overview` function provides 6 graphs for the region:\n\n 0) the total cumulative number of cases and deaths\n 1) the daily change (cases)\n 2) the daily change (deaths)\n 3) R number and growth factor (cases)\n 4) R number and growth factor (deaths)\n 5) the doubling time (both cases and death)\n\n `weeks` parameter refers to the last N number of weeks to show. Omit this\n parameter or use zero value to see the pandemic since the very beginning.\n\n Returns: subplots, cases (pandas Series), deaths (pandas Series)\n \"\"\"\n if data is None:\n _c, _d = get_country_data(country, region=region, subregion=subregion)\n else:\n _c, _d = data\n assert isinstance(_c.index[0], pd.Timestamp), f\"The index of 'cases' is not of type `Timestamp`, \" \\\n f\"try to use `index=pd.DatetimeIndex(dates)`\"\n assert isinstance(_d.index[0], pd.Timestamp), f\"The index of 'deaths' is not of type `Timestamp`, \" \\\n f\"try to use `index=pd.DatetimeIndex(dates)`\"\n\n region_label = get_region_label(country, region=region, subregion=subregion)\n fig, axes = plt.subplots(6, 1, figsize=(10, 15), sharex=False)\n if dates and weeks == 0:\n c = cut_dates(_c, dates)\n elif dates and weeks:\n raise ValueError(\"`dates` and `weeks` cannot be used together\")\n else:\n c = _c[- weeks * 7:]\n # plot_time_step(ax=axes[0], series=c, style=\"-C1\", labels=(region_label, \"cases\"))\n plot_incidence_rate(ax=axes[0], cases=_c,\n country=country, region=region, subregion=subregion, dates=dates, weeks=weeks)\n plot_daily_change(ax=axes[1], series=_c, color=\"C1\", labels=(region_label, \"cases\"),\n country=country, region=region, subregion=subregion, dates=dates, weeks=weeks)\n # data cleaning\n if country == \"Spain\": # https://github.com/oscovida/oscovida/issues/44\n axes[1].set_ylim(bottom=0)\n plot_reproduction_number(axes[3], series=c, color_g=\"C1\", color_R=\"C5\", labels=(region_label, \"cases\"))\n ax_dt_c = axes[5]\n plot_doubling_time(ax_dt_c, series=c, color=\"C1\", labels=(region_label, \"cases\"))\n if _d is not None:\n if dates and weeks == 0:\n d = cut_dates(_d, dates)\n else:\n d = _d[- weeks * 7:]\n # plot_time_step(ax=axes[0], series=d, style=\"-C0\", labels=(region_label, \"deaths\"))\n plot_daily_change(ax=axes[2], series=_d, color=\"C0\", labels=(region_label, \"deaths\"),\n country=country, region=region, subregion=subregion, dates=dates, weeks=weeks)\n plot_reproduction_number(axes[4], series=d, color_g=\"C0\", color_R=\"C4\", labels=(region_label, \"deaths\"))\n problems = (\"no data in reduced data set\", \"Cannot compute smooth ratio\")\n if compute_doubling_time(d)[0][1] not in problems:\n ax_dt_d = plt.twinx(ax_dt_c)\n plot_doubling_time(ax_dt_d, series=d, color=\"C0\", labels=(region_label, \"deaths\"))\n # combining doubling time plots\n ticks = align_twinx_ticks(ax_dt_c, ax_dt_d)\n ax_dt_d.yaxis.set_major_locator(FixedLocator(ticks))\n ax_dt_d.grid(False) # don't draw the second grid on top of the legend\n # create a combined legend\n h_c, l_c = ax_dt_c.get_legend_handles_labels() # may return [], []\n h_d, l_d = ax_dt_d.get_legend_handles_labels() # may return [], []\n labels = [[], []]\n for x, y in [[h_c, l_c], [h_d, l_d]]:\n if x:\n labels[0] += [x[1]]\n labels[1] += [y[1]]\n axes[5].legend(*labels)\n else: # just create a legend as is\n axes[5].legend()\n if _d is None:\n d = _d\n plot_no_data_available(axes[2], mimic_subplot=axes[1], text='daily change in deaths')\n plot_no_data_available(axes[4], mimic_subplot=axes[3], text='R & growth factor (based on deaths)')\n\n # enforce same x-axis on all plots\n for i in range(0, axes.shape[0]):\n axes[i].set_xlim(axes[0].get_xlim())\n for i in range(0, axes.shape[0]):\n if not has_twin(axes[i]):\n axes[i].tick_params(left=True, right=True, labelleft=True, labelright=True)\n axes[i].yaxis.set_ticks_position('both')\n if weeks > 0:\n axes[i].get_xaxis().set_major_locator(WeekdayLocator(byweekday=MONDAY)) # put ticks every Monday\n axes[i].get_xaxis().set_major_formatter(DateFormatter('%d %b')) # date format: `15 Jun`\n else:\n axes[i].xaxis.set_major_formatter(DateFormatter(\"%b %y\"))\n\n week_str = f\", last {weeks} weeks\" if weeks else ''\n region_str = f\"{region or subregion}, {country}\" if (region or subregion) else country\n title = f\"{region_str}{week_str}, last data point from {c.index[-1].date().isoformat()}\"\n axes[0].set_title(title)\n\n # tight_layout gives warnings, for example for Heinsberg\n # fig.tight_layout(pad=1)\n\n filename = os.path.join(\"figures\", region_label.replace(\" \", \"-\").replace(\",\", \"-\") + '.svg')\n if savefig:\n fig.savefig(filename)\n return axes, c, d\n\n\ndef compare_plot(country: str, region: str = None, subregion: str = None,\n savefig: bool = False, normalise: bool = True,\n dates: str = None, align: bool = False) -> Tuple[plt.axes, pd.Series, pd.Series]:\n \"\"\" Create a pair of plots which show comparison of the region with other most suffering countries\n\n :param country: mandatory\n :param region: default: None\n :param subregion: default: None\n :param savefig: save figure as PDF, default: False\n :param normalise: whether to normalise data, default: True\n :param dates: range in the format \"2020-03-21:2020-05-21\"\n :param align: whether to align the starting point for different countries, default: False\n \"\"\"\n c, d = get_country_data(country, region=region, subregion=subregion)\n region_label = get_region_label(country, region=region, subregion=subregion)\n if normalise:\n _population = population(country=country, region=region, subregion=subregion)\n c *= 100000 / _population\n d *= 100000 / _population\n\n if not subregion and not region: # i.e. not a region of Germany\n axes_compare, res_c, res_d = make_compare_plot(country, normalise=normalise, align=align)\n\n elif country == \"Germany\": # Germany specific plots\n # On 11 April, Mecklenburg Vorpommern data was missing from data set.\n # We thus compare only against those Laender, that are in the data set:\n # germany = fetch_data_germany()\n # laender = list(germany['Bundesland'].drop_duplicates().sort_values())\n axes_compare, res_c, red_d = make_compare_plot_germany(region=region, subregion=subregion, normalise=normalise,\n dates=dates)\n elif country == \"US\" and region is not None:\n # skip comparison plot for the US states at the moment\n return None, c, d\n\n elif country == 'Hungary':\n # choosing random counties. not sure if this make sense or not because not every county has enough data.\n with_local = choose_random_counties(exclude_region=region, size=18)\n axes_compare, res_c, red_d = make_compare_plot_hungary(region, compare_with_local=with_local)\n return axes_compare, c, d\n else:\n raise NotImplementedError\n\n fig2 = plt.gcf()\n\n if savefig:\n filename = os.path.join(\"figures\", region_label.replace(\" \", \"-\").replace(\",\", \"-\") + '2.svg')\n fig2.savefig(filename)\n\n return axes_compare, c, d\n\n\ndef get_cases_last_week(cases):\n \"\"\"Given cumulative cases time series, return the number of cases from the last week.\n \"\"\"\n # make sure we have one value for every day\n c2 = cases.resample('D').pad()\n # last week is difference between last value, and the one 7 days before\n cases_last_week = c2[-1] - c2[-8]\n return cases_last_week\n"
] |
[
[
"pandas.merge",
"pandas.to_datetime",
"pandas.Series",
"pandas.DataFrame",
"numpy.concatenate",
"matplotlib.ticker.FixedLocator",
"pandas.read_csv",
"matplotlib.pyplot.twinx",
"matplotlib.pyplot.gcf",
"numpy.full",
"pandas.plotting.register_matplotlib_converters",
"matplotlib.ticker.ScalarFormatter",
"matplotlib.pyplot.style.use",
"numpy.log",
"matplotlib.dates.DateFormatter",
"matplotlib.collections.LineCollection",
"pandas.Timedelta",
"matplotlib.pyplot.Normalize",
"numpy.array",
"matplotlib.dates.WeekdayLocator",
"matplotlib.pyplot.subplots",
"numpy.random.shuffle",
"numpy.ones"
]
] |
kimbring2/pysc2_transformer
|
[
"a147d29342ac2b75b6e837bcd3c2d6b802595427"
] |
[
"pseudocode/network.py"
] |
[
"import tensorflow as tf\nimport numpy as np\n\n\ndef scaled_dot_product_attention(q, k, v, mask):\n \"\"\"Calculate the attention weights.\n q, k, v must have matching leading dimensions.\n k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.\n The mask has different shapes depending on its type(padding or look ahead) \n but it must be broadcastable for addition.\n \n Args:\n q: query shape == (..., seq_len_q, depth)\n k: key shape == (..., seq_len_k, depth)\n v: value shape == (..., seq_len_v, depth_v)\n mask: Float tensor with shape broadcastable \n to (..., seq_len_q, seq_len_k). Defaults to None.\n \n Returns:\n output, attention_weights\n \"\"\"\n\n matmul_qk = tf.matmul(q, k, transpose_b=True) # (..., seq_len_q, seq_len_k)\n \n # scale matmul_qk\n dk = tf.cast(tf.shape(k)[-1], tf.float32)\n scaled_attention_logits = matmul_qk / tf.math.sqrt(dk)\n\n # add the mask to the scaled tensor.\n if mask is not None:\n scaled_attention_logits += (mask * -1e9) \n\n # softmax is normalized on the last axis (seq_len_k) so that the scores\n # add up to 1.\n attention_weights = tf.nn.softmax(scaled_attention_logits, axis=-1) # (..., seq_len_q, seq_len_k)\n\n output = tf.matmul(attention_weights, v) # (..., seq_len_q, depth_v)\n\n return output, attention_weights\n\n\nclass MultiHeadAttention(tf.keras.layers.Layer):\n def __init__(self, d_model, num_heads):\n super(MultiHeadAttention, self).__init__()\n self.num_heads = num_heads\n self.d_model = d_model\n \n assert d_model % self.num_heads == 0\n \n self.depth = d_model // self.num_heads\n \n self.wq = tf.keras.layers.Dense(d_model)\n self.wk = tf.keras.layers.Dense(d_model)\n self.wv = tf.keras.layers.Dense(d_model)\n \n self.dense = tf.keras.layers.Dense(d_model)\n \n def split_heads(self, x, batch_size):\n \"\"\"Split the last dimension into (num_heads, depth).\n Transpose the result such that the shape is (batch_size, num_heads, seq_len, depth)\n \"\"\"\n x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth))\n return tf.transpose(x, perm=[0, 2, 1, 3])\n \n def call(self, v, k, q, mask):\n batch_size = tf.shape(q)[0]\n \n q = self.wq(q) # (batch_size, seq_len, d_model)\n k = self.wk(k) # (batch_size, seq_len, d_model)\n v = self.wv(v) # (batch_size, seq_len, d_model)\n \n q = self.split_heads(q, batch_size) # (batch_size, num_heads, seq_len_q, depth)\n k = self.split_heads(k, batch_size) # (batch_size, num_heads, seq_len_k, depth)\n v = self.split_heads(v, batch_size) # (batch_size, num_heads, seq_len_v, depth)\n \n # scaled_attention.shape == (batch_size, num_heads, seq_len_q, depth)\n # attention_weights.shape == (batch_size, num_heads, seq_len_q, seq_len_k)\n scaled_attention, attention_weights = scaled_dot_product_attention(q, k, v, mask)\n \n scaled_attention = tf.transpose(scaled_attention, perm=[0, 2, 1, 3]) # (batch_size, seq_len_q, num_heads, depth)\n\n concat_attention = tf.reshape(scaled_attention, (batch_size, -1, self.d_model)) # (batch_size, seq_len_q, d_model)\n # concat_attention.shape: (1, 512, 464)\n\n input_shape = concat_attention.shape\n output = tf.keras.layers.Conv1D(32, 1, activation='relu', input_shape=input_shape[1:])(concat_attention)\n # output.shape: (1, 512, 32)\n\n output = self.dense(concat_attention) # (batch_size, seq_len_q, d_model)\n \n return output, attention_weights\n\n\nclass EntityEncoder(tf.keras.layers.Layer):\n def __init__(self, d_model, num_heads, rate=0.1):\n super(EntityEncoder, self).__init__()\n\n self.mha = MultiHeadAttention(d_model=464, num_heads=8)\n\n def call(self, embedded_feature_units):\n # enc_output.shape == (batch_size, input_seq_len, d_model)\n #y = tf.random.uniform((1, 512, 464)) # (batch_size, encoder_sequence, d_model)\n out, attn = self.mha(embedded_feature_units, k=embedded_feature_units, q=embedded_feature_units, mask=None)\n # out.shape: (1, 512, 32)\n \n '''\n The transformer output is passed through a ReLU, 1D convolution with 256 channels and kernel size 1, and another ReLU to yield \n `entity_embeddings`. The mean of the transformer output across the units (masked by the missing entries) is fed through a linear \n layer of size 256 and a ReLU to yield `embedded_entity`.\n '''\n\n entity_embeddings = tf.keras.layers.Conv1D(256, 1, activation='relu')(out)\n embedded_entity = tf.reduce_mean(out, 1)\n embedded_entity = tf.keras.layers.Dense(256, activation='relu')(embedded_entity)\n #print(\"embedded_entity.shape: \" + str(embedded_entity.shape))\n #embedded_entity.shape: (1, 464)\n\n return embedded_entity, entity_embeddings\n\n'''\nsample_decoder_layer = ScalarEncoder(464, 8)\nsample_decoder_layer_output = sample_decoder_layer(tf.random.uniform((1,512)))\nprint(\"sample_decoder_layer_output.shape: \" + str(sample_decoder_layer_output.shape))\n'''\n\nclass SpatialEncoder(tf.keras.layers.Layer):\n def __init__(self, img_height, img_width, channel):\n super(SpatialEncoder, self).__init__()\n\n self.map_model = tf.keras.Sequential([\n tf.keras.layers.experimental.preprocessing.Rescaling(1./255, input_shape=(img_height, img_width, channel)),\n tf.keras.layers.Conv2D(4, 3, padding='same', activation='relu'),\n tf.keras.layers.MaxPooling2D(),\n tf.keras.layers.Conv2D(8, 3, padding='same', activation='relu'),\n tf.keras.layers.MaxPooling2D(),\n tf.keras.layers.Conv2D(16, 3, padding='same', activation='relu'),\n tf.keras.layers.MaxPooling2D()\n ])\n\n def call(self, feature_screen):\n '''\n Two additional map layers are added to those described in the interface. The first is a camera layer with two possible values: whether a location is inside \n or outside the virtual camera. The second is the scattered entities. `entity_embeddings` are embedded through a size 32 1D convolution followed by a ReLU, \n then scattered into a map layer so that the size 32 vector at a specific location corresponds to the units placed there. The planes are preprocessed as follows:\n '''\n\n '''\n After preprocessing, the planes are concatenated, projected to 32 channels by a 2D convolution with kernel size 1, passed through a ReLU, then downsampled \n from 128x128 to 16x16 through 3 2D convolutions and ReLUs with channel size 64, 128, and 128 respectively. The kernel size for those 3 downsampling convolutions \n is 4, and the stride is 2. 4 ResBlocks with 128 channels and kernel size 3 and applied to the downsampled map, with the skip connections placed into `map_skip`. \n The ResBlock output is embedded into a 1D tensor of size 256 by a linear layer and a ReLU, which becomes `embedded_spatial`.\n '''\n\n # out_entity.shape: (1, 510, 32)\n map_ = tf.transpose(feature_screen, perm=[1, 2, 0])\n map_ = tf.expand_dims(map_, axis=0)\n #print(\"map_.shape: \" + str(map_.shape))\n map_ = self.map_model(map_)\n\n map_flatten = tf.keras.layers.Flatten()(map_)\n # out_map.shape: (1, 16384)\n\n embedded_spatial = tf.keras.layers.Dense(256, activation='relu')(map_flatten)\n #print(\"embedded_spatial.shape: \" + str(embedded_spatial.shape))\n\n return map_, embedded_spatial\n\n'''\nsample_decoder_layer = SpatialEncoder(128, 128, 27)\nsample_input = tf.random.uniform((27, 128, 128))\nsample_input = tf.transpose(sample_input, perm=[1, 2, 0])\nprint(\"sample_input.shape: \" + str(sample_input.shape))\nsample_input = tf.reshape(sample_input, [1, 128, 128, 27])\nprint(\"sample_input.shape: \" + str(sample_input.shape))\n\nsample_decoder_layer_output = sample_decoder_layer([sample_input])\n\nprint(\"sample_decoder_layer_output.shape: \" + str(sample_decoder_layer_output.shape))\n'''\n\nclass Core(tf.keras.layers.Layer):\n def __init__(self, unit_number):\n super(Core, self).__init__()\n\n self.model = tf.keras.layers.LSTM(unit_number, return_sequences=True, return_state=True)\n\n def call(self, prev_state, embedded_entity, embedded_spatial, embedded_scalar):\n # enc_output.shape == (batch_size, input_seq_len, d_model)\n core_input = tf.concat((embedded_spatial, embedded_scalar, embedded_entity), axis=1)\n #print(\"encoder_input.shape: \" + str(encoder_input.shape))\n # encoder_input.shape: (1, 819)\n\n core_input = tf.reshape(core_input, [1, 9, 91])\n lstm_output = self.model(core_input, initial_state=prev_state, training=True)\n #print(\"out_3.shape: \" + str(out_3.shape))\n\n return lstm_output\n\n'''\nsample_core_layer = Core(12)\n\ninputs = tf.random.normal([32, 10, 8])\nwhole_seq_output, final_memory_state, final_carry_state = sample_core_layer(inputs)\nprint(whole_seq_output.shape)\nprint(final_memory_state.shape)\nprint(final_carry_state.shape)\n'''\n'''\ndef sample(a, temperature=0.8):\n #print(\"a: \" + str(a))\n\n a = np.array(a)**(1 / temperature)\n p_sum = a.sum()\n\n a = np.log(a) / temperature\n a = np.exp(a) / np.sum(np.exp(a))\n\n print(\"p_sum: \" + str(p_sum))\n\n sample_temp = a / p_sum \n\n #print(\"sample_temp.shape: \" + str(sample_temp.shape))\n sample_temp = np.random.multinomial(1, sample_temp, 1)\n #print(\"sample_temp: \" + str(sample_temp))\n\n return np.argmax(sample_temp)\n'''\n\ndef sample(a, temperature=0.8):\n a = a + 1\n a = np.log(a) / temperature\n a = np.exp(a) / np.sum(np.exp(a))\n\n return np.argmax(np.random.multinomial(1, a, 1))\n\n\nclass ResBlock_MLP(tf.keras.layers.Layer):\n def __init__(self, output_dim, **kwargs):\n #self.shortcut = tf.keras.layers.Conv2D(output_dim, 1, strides=(1, 1), padding='same', activation='relu')\n self.shortcut = tf.keras.layers.Dense(256, activation='relu')\n\n #self.conv_0 = tf.keras.layers.Conv2D(output_dim, 3, padding='same', activation='relu')\n #self.conv_1 = tf.keras.layers.Conv2D(output_dim, 3, padding='same', activation='relu')\n self.mlp_0 = tf.keras.layers.Dense(256, activation='relu')\n self.mlp_1 = tf.keras.layers.Dense(256, activation='relu')\n\n self.bn_0 = tf.keras.layers.BatchNormalization(momentum=0.9, epsilon=1e-5)\n self.bn_1 = tf.keras.layers.BatchNormalization(momentum=0.9, epsilon=1e-5)\n super(ResBlock_MLP, self).__init__(**kwargs)\n\n def call(self, inputs, training):\n net = self.bn_0(inputs, training=training)\n net = tf.keras.layers.ReLU()(net)\n\n shortcut = self.shortcut(net)\n\n net = self.mlp_0(net)\n net = self.bn_1(net, training=training)\n net = tf.nn.relu(net)\n net = self.mlp_1(net)\n\n output = net + shortcut\n return output\n\n\nclass ActionTypeHead(tf.keras.layers.Layer):\n def __init__(self, action_num):\n super(ActionTypeHead, self).__init__()\n\n self.action_num = action_num\n self.model = ResBlock_MLP(256)\n \n def call(self, lstm_output, scalar_context):\n out = self.model(lstm_output, True)\n out_gate = tf.keras.layers.Dense(256)(scalar_context)\n #print(\"out_3.shape: \" + str(out_3.shape))\n\n out_gated = tf.keras.layers.Multiply()([out, out_gate])\n output_flatten = tf.keras.layers.Flatten()(out_gated)\n output = tf.keras.layers.Dense(self.action_num)(output_flatten)\n #print(\"output: \" + str(output))\n\n action_type_logits = tf.nn.softmax(output, axis=-1)[0]\n #print(\"action_type_logits: \" + str(action_type_logits))\n\n #action_type = tf.argmax(action_type_logits, axis=0)\n action_type = sample(action_type_logits)\n #print(\"action_type: \" + str(action_type))\n\n action_type_onehot = tf.one_hot(action_type, self.action_num)\n action_type_onehot = tf.expand_dims(action_type_onehot, axis=0)\n #print(\"action_type_onehot.shape: \" + str(action_type_onehot.shape))\n\n autoregressive_embedding = tf.keras.layers.Dense(1024)(action_type_onehot)\n #print(\"autoregressive_embedding.shape: \" + str(autoregressive_embedding.shape))\n\n autoregressive_embedding_gate = tf.keras.layers.Dense(1024)(scalar_context)\n autoregressive_embedding = tf.keras.layers.Multiply()([autoregressive_embedding, autoregressive_embedding_gate])\n # autoregressive_embedding.shape: (1, 1024)\n\n lstm_output_embedding = tf.keras.layers.Flatten()(lstm_output)\n lstm_output_embedding = tf.keras.layers.Dense(1024)(lstm_output_embedding)\n lstm_output_embedding_gate = tf.keras.layers.Dense(1024)(scalar_context)\n lstm_output_embedding = tf.keras.layers.Multiply()([lstm_output_embedding, lstm_output_embedding_gate])\n #print(\"lstm_output_embedding.shape: \" + str(lstm_output_embedding.shape))\n\n autoregressive_embedding = autoregressive_embedding + lstm_output_embedding\n #print(\"autoregressive_embedding.shape: \" + str(autoregressive_embedding.shape))\n '''\n `autoregressive_embedding` is then generated by first applying a ReLU and linear layer of size 256 to the one-hot version of `action_type`, \n and projecting it to a 1D tensor of size 1024 through a `GLU` gated by `scalar_context`. That projection is added to another projection of \n `lstm_output` into a 1D tensor of size 1024 gated by `scalar_context` to yield `autoregressive_embedding`.\n '''\n\n return action_type_logits, action_type, autoregressive_embedding\n\n\nclass SelectedUnitsHead(tf.keras.layers.Layer):\n def __init__(self):\n super(SelectedUnitsHead, self).__init__()\n\n self.model = tf.keras.layers.Dense(256, activation='relu')\n\n def call(self, autoregressive_embedding, action_acceptable_entity_type_binary, entity_embeddings):\n #action_acceptable_entity_type_onehot = tf.one_hot(action_acceptable_entity_type, 512)\n action_acceptable_entity_type_binary = tf.expand_dims(action_acceptable_entity_type_binary, axis=0)\n\n #print(\"action_acceptable_entity_type_onehot.shape: \" + str(action_acceptable_entity_type_onehot.shape))\n func_embed = tf.keras.layers.Dense(256, activation='relu')(action_acceptable_entity_type_binary)\n\n '''\n It then computes a key corresponding to each entity by feeding `entity_embeddings` through a 1D convolution with 32 channels and kernel size 1, \n and creates a new variable corresponding to ending unit selection. \n '''\n\n #print(\"entity_embeddings.shape: \" + str(entity_embeddings.shape))\n #entity_embeddings.shape: (1, 512, 256)\n key = tf.keras.layers.Conv1D(32, 1, activation='relu')(entity_embeddings)\n #print(\"key.shape: \" + str(key.shape))\n # key.shape: (1, 512, 32) \n #print(\"key: \" + str(key))\n\n #print(\"autoregressive_embedding.shape: \" + str(autoregressive_embedding.shape))\n # autoregressive_embedding.shape: (1, 1024)\n query = tf.keras.layers.Dense(256, activation='relu')(autoregressive_embedding)\n query = tf.keras.layers.Dense(32, activation='relu')(func_embed + query)\n query = tf.expand_dims(query, axis=0)\n #print(\"query: \" + str(query))\n\n dim = tf.zeros([1, 32])\n query, state_h, state_c = tf.keras.layers.LSTM(units=32, activation='relu', return_state=True, return_sequences=True)(query, \n initial_state=[dim, dim], \n training=True)\n #print(\"query.shape: \" + str(query.shape))\n # query.shape: (1, 1, 32)\n #print(\"query: \" + str(query))\n\n entity_selection_result = tf.matmul(query, key, transpose_b=True)\n #print(\"entity_selection_result.shape: \" + str(entity_selection_result.shape))\n # entity_selection_result.shape: (1, 512, 32)\n\n units_logits = entity_selection_result[0][0]\n #print(\"units_logits: \" + str(units_logits))\n\n #print(\"entity_selection_result[0][0].shape: \" + str(entity_selection_result[0][0].shape))\n units = sample(entity_selection_result[0][0])\n #print(\"units: \" + str(units))\n '''\n Then, repeated for selecting up to 64 units, the network passes `autoregressive_embedding` through a linear of size 256, adds `func_embed`, \n and passes the combination through a ReLU and a linear of size 32. The result is fed into a LSTM with size 32 and zero initial state to get a query. \n The entity keys are multiplied by the query, and are sampled using the mask and temperature 0.8 to decide which entity to select. That entity is \n masked out so that it cannot be selected in future iterations. The one-hot position of the selected entity is multiplied by the keys, reduced by \n the mean across the entities, passed through a linear layer of size 1024, and added to `autoregressive_embedding` for subsequent iterations. The \n final `autoregressive_embedding` is returned. If `action_type` does not involve selecting units, this head is ignored.\n '''\n\n #print(\"autoregressive_embedding.shape: \" + str(autoregressive_embedding.shape))\n # autoregressive_embedding.shape: (1, 1024)\n\n autoregressive_embedding_ = tf.one_hot(units, 512)\n # autoregressive_embedding_.shape: (512,)\n # key.shape: (1, 512, 32)\n autoregressive_embedding_ = tf.keras.layers.Multiply()([autoregressive_embedding_, key[0]])\n autoregressive_embedding_ = tf.reduce_mean(autoregressive_embedding_, 0)\n #print(\"autoregressive_embedding_.shape: \" + str(autoregressive_embedding_.shape))\n autoregressive_embedding_ = tf.expand_dims(autoregressive_embedding_, axis=0)\n autoregressive_embedding_ = tf.keras.layers.Dense(1024, activation='relu')(autoregressive_embedding_)\n autoregressive_embedding += autoregressive_embedding_\n #print(\"autoregressive_embedding.shape: \" + str(autoregressive_embedding.shape))\n\n return units_logits, units, autoregressive_embedding\n\n\nclass TargetUnitHead(tf.keras.layers.Layer):\n def __init__(self):\n super(TargetUnitHead, self).__init__()\n\n self.model = tf.keras.layers.Dense(256, activation='relu')\n\n def call(self,autoregressive_embedding, action_acceptable_entity_type_binary, entity_embeddings):\n action_acceptable_entity_type_binary = tf.expand_dims(action_acceptable_entity_type_binary, axis=0)\n\n func_embed = tf.keras.layers.Dense(256, activation='relu')(action_acceptable_entity_type_binary)\n\n key = tf.keras.layers.Conv1D(32, 1, activation='relu')(entity_embeddings)\n\n query = tf.keras.layers.Dense(256, activation='relu')(autoregressive_embedding)\n query = tf.keras.layers.Dense(32, activation='relu')(func_embed + query)\n query = tf.expand_dims(query, axis=0)\n\n dim = tf.zeros([1, 32])\n query, state_h, state_c = tf.keras.layers.LSTM(units=32, activation='relu', return_state=True, return_sequences=True)(query, initial_state=[dim, dim], training=True)\n entity_selection_result = tf.matmul(query, key, transpose_b=True)\n\n target_unit_logits = entity_selection_result[0][0]\n target_unit = sample(entity_selection_result[0][0])\n\n return target_unit_logits, target_unit\n\n\nclass ResBlock_CNN(tf.keras.layers.Layer):\n def __init__(self, output_dim, strides=(1, 1, 1, 1), **kwargs):\n self.strides = strides\n if strides != (1, 1, 1, 1):\n self.shortcut = tf.keras.layers.Conv2D(4, 1, padding='same', activation='relu')\n\n self.conv_0 = tf.keras.layers.Conv2D(output_dim, 3, padding='same', activation='relu')\n self.conv_1 = tf.keras.layers.Conv2D(output_dim, 3, padding='same', activation='relu')\n self.bn_0 = tf.keras.layers.BatchNormalization(momentum=0.9, epsilon=1e-5)\n self.bn_1 = tf.keras.layers.BatchNormalization(momentum=0.9, epsilon=1e-5)\n super(ResBlock_CNN, self).__init__(**kwargs)\n\n def call(self, inputs, training):\n net = self.bn_0(inputs, training=training)\n\n if self.strides != (1, 1, 1, 1):\n shortcut = self.shortcut(net)\n else:\n shortcut = inputs\n\n net = self.conv_0(net)\n net = self.bn_1(net, training=training)\n net = self.conv_1(net)\n\n output = net + shortcut\n return output\n\n\nclass LocationHead(tf.keras.layers.Layer):\n def __init__(self):\n super(LocationHead, self).__init__()\n\n self.model = ResBlock_CNN(20)\n\n def call(self, autoregressive_embedding, action_acceptable_entity_type, map_):\n '''\n `autoregressive_embedding` is reshaped to have the same height/width as the final skip in `map_skip` (which was just before map information was \n reshaped to a 1D embedding) with 4 channels, and the two are concatenated together along the channel dimension, passed through a ReLU, passed \n through a 2D convolution with 128 channels and kernel size 1, then passed through another ReLU. The 3D tensor (height, width, and channels) is \n then passed through a series of Gated ResBlocks with 128 channels, kernel size 3, and FiLM, gated on `autoregressive_embedding` and using the \n elements of `map_skip` in order of last ResBlock skip to first. Afterwards, it is upsampled 2x by each of a series of transposed 2D convolutions \n with kernel size 4 and channel sizes 128, 64, 16, and 1 respectively (upsampled beyond the 128x128 input to 256x256 target location selection). \n Those final logits are flattened and sampled (masking out invalid locations using `action_type`, such as those outside the camera for build \n actions) with temperature 0.8 to get the actual target position. \n '''\n #print(\"autoregressive_embedding.shape: \" + str(autoregressive_embedding.shape))\n # autoregressive_embedding.shape: (1, 1024)\n\n autoregressive_embedding_reshaped = tf.reshape(autoregressive_embedding, [16, 16, 4])\n autoregressive_embedding_reshaped = tf.expand_dims(autoregressive_embedding_reshaped, axis=0)\n #print(\"autoregressive_embedding_reshaped.shape: \" + str(autoregressive_embedding_reshaped.shape))\n #print(\"map_.shape: \" + str(map_.shape))\n map_concated = tf.concat((autoregressive_embedding_reshaped, map_), axis=3)\n #print(\"map_concated.shape: \" + str(map_concated.shape))\n # map_concated.shape: (1, 16, 16, 20)\n\n target_location_logits = self.model(map_concated, True)\n #print(\"target_location_logits.shape: \" + str(target_location_logits.shape))\n # target_location_logits.shape: (1, 16, 16, 20)\n target_location_logits = tf.keras.layers.Conv2DTranspose(10, 4, strides=2, padding='same', activation='relu', use_bias=False)(target_location_logits)\n #print(\"target_location_logits.shape: \" + str(target_location_logits.shape))\n # target_location_logits.shape: (1, 32, 32, 10)\n\n target_location_logits = tf.keras.layers.Conv2DTranspose(5, 4, strides=2, padding='same', activation='relu', use_bias=False)(target_location_logits)\n #print(\"target_location_logits.shape: \" + str(target_location_logits.shape))\n # target_location_logits.shape: (1, 64, 64, 5)\n\n target_location_logits = tf.keras.layers.Conv2DTranspose(1, 4, strides=2, padding='same', activation='relu', use_bias=False)(target_location_logits)\n #print(\"target_location_logits.shape: \" + str(target_location_logits.shape))\n # target_location_logits.shape: (1, 128, 128, 1)\n\n target_location_logits = tf.reshape(target_location_logits, [1, 128, 128])\n #print(\"target_location_logits.shape: \" + str(target_location_logits.shape))\n # target_location_logits.shape: (1, 128, 128)\n\n target_location_logits_flatten = tf.keras.layers.Flatten()(target_location_logits)\n #print(\"target_location_logits_flatten[0].shape: \" + str(target_location_logits_flatten[0].shape))\n #print(\"target_location_logits_flatten[0]: \" + str(target_location_logits_flatten[0]))\n target_location = sample(target_location_logits_flatten[0])\n #print(\"target_location: \" + str(target_location))\n\n x = int(target_location / 128)\n y = target_location % 128\n\n target_location_logits = target_location_logits_flatten[0]\n target_location = (x, y)\n #print(\"target_location: \" + str(target_location))\n\n return target_location_logits, target_location"
] |
[
[
"tensorflow.concat",
"tensorflow.zeros",
"tensorflow.keras.layers.Conv2DTranspose",
"numpy.exp",
"tensorflow.keras.layers.Conv2D",
"numpy.random.multinomial",
"tensorflow.keras.layers.Multiply",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.layers.experimental.preprocessing.Rescaling",
"tensorflow.matmul",
"numpy.log",
"tensorflow.keras.layers.ReLU",
"tensorflow.shape",
"tensorflow.keras.layers.Dense",
"tensorflow.one_hot",
"tensorflow.nn.relu",
"tensorflow.nn.softmax",
"tensorflow.math.sqrt",
"tensorflow.transpose",
"tensorflow.reduce_mean",
"tensorflow.keras.layers.Conv1D",
"tensorflow.reshape",
"tensorflow.expand_dims",
"tensorflow.keras.layers.LSTM",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.keras.layers.MaxPooling2D"
]
] |
gmuraru/PySyft
|
[
"ae25783f0ab36aeb1497eaa03a6b1c531caeec3d"
] |
[
"test/crypten/test_utils.py"
] |
[
"import pytest\nimport torch as th\nimport crypten\nfrom syft.frameworks.crypten import utils\nfrom syft.frameworks import crypten as syft_crypten\n\n\[email protected](\n \"tensors\",\n [\n # return tensor\n th.tensor([1, 2, 3, 4]),\n # return tensor1, tensor2, tensor3\n (th.tensor([1, 2, 4, 5]), th.tensor([1.0, 2.0, 3.0,]), th.tensor([5, 6, 7, 8])),\n ],\n)\ndef test_pack_tensors(tensors):\n packed = utils.pack_values(tensors)\n unpacked = utils.unpack_values(packed)\n\n if isinstance(unpacked, tuple): # return tensor1, tensor2 ...\n assert len(tensors) == len(unpacked)\n for unpacked_tensor, tensor in zip(unpacked, tensors):\n assert th.all(unpacked_tensor == tensor)\n\n else: # return tensor\n assert th.all(unpacked == tensors)\n\n\ndef test_pack_crypten_model():\n class ExampleNet(th.nn.Module):\n def __init__(self):\n super(ExampleNet, self).__init__()\n self.fc = th.nn.Linear(28 * 28, 2)\n\n def forward(self, x):\n out = self.fc(x)\n return out\n\n dummy_input = th.rand(1, 28 * 28)\n expected_crypten_model = crypten.nn.from_pytorch(ExampleNet(), dummy_input)\n expected_out = expected_crypten_model(dummy_input)\n\n packed = utils.pack_values(expected_crypten_model)\n\n # zero all model's parameters\n with th.no_grad():\n for p in expected_crypten_model.parameters():\n assert isinstance(p, th.Tensor)\n p.set_(th.zeros_like(p))\n\n crypten_model = utils.unpack_values(packed, model=expected_crypten_model)\n\n out = crypten_model(dummy_input)\n assert th.all(expected_out == out)\n\n\ndef test_serialize_models():\n class ExampleNet(th.nn.Module):\n def __init__(self):\n super(ExampleNet, self).__init__()\n self.fc1 = th.nn.Linear(1024, 100)\n self.fc2 = th.nn.Linear(\n 100, 2\n ) # For binary classification, final layer needs only 2 outputs\n\n def forward(self, x):\n out = self.fc1(x)\n out = th.nn.functional.relu(out)\n out = self.fc2(out)\n return out\n\n dummy_input = th.ones(1, 1024)\n example_net = ExampleNet()\n\n expected_output = example_net(dummy_input)\n\n onnx_bytes = utils.pytorch_to_onnx(example_net, dummy_input)\n crypten_model = utils.onnx_to_crypten(onnx_bytes)\n output = crypten_model(dummy_input)\n\n assert th.allclose(expected_output, output)\n"
] |
[
[
"torch.all",
"torch.ones",
"torch.zeros_like",
"torch.tensor",
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.no_grad",
"torch.rand",
"torch.allclose"
]
] |
ConduitDan/Python-Models
|
[
"fbd79ccce05201e00a64629ef5b28921a51640cd"
] |
[
"IFSDrawer.py"
] |
[
"\"\"\"\r\nThis class draws iterated function systems\r\n\"\"\"\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\n\r\nclass IFSGenerator:\r\n def __init__(self, IFS=None, depth=10, numPoints = None, overwrite=False):\r\n if IFS is None:\r\n raise \"Please supply an IFS\"\r\n self.IFS = IFS\r\n self.fileName = \"fractals/\" + IFS.name() + str(depth)\r\n\r\n self.overwrite = overwrite\r\n self.File = None\r\n self.functionList = self.IFS.getFunctionList()\r\n self.numOfFunctions = len(self.functionList)\r\n \r\n \r\n if numPoints is None:\r\n self.depth = depth \r\n self.numPoints = (self.numOfFunctions**(self.depth))\r\n \r\n else:\r\n self.numPoints = int(numPoints)\r\n self.depth = int(np.ceil(np.log(self.numPoints)/np.log(self.numOfFunctions)))\r\n \r\n \r\n self.x = [0.0]*self.numPoints\r\n self.y = [0.0]*self.numPoints\r\n self.color = [[0,0,0]]*self.numPoints\r\n\r\n def canReadFromFile(self):\r\n readable = False\r\n if not self.overwrite:\r\n try:\r\n self.File = open(self.fileName+\".out\", \"r\")\r\n readable = True\r\n self.File.close()\r\n except:\r\n FileNotFoundError\r\n return readable\r\n \r\n def readPointsFromFile(self):\r\n self.File = open(self.fileName+\".out\",\"r\")\r\n xline = self.File.readline().split(',')\r\n yline = self.File.readline().split(',')\r\n xline.pop() #remove /n\r\n yline.pop() #remove /n\r\n x = list(float(element) for element in xline)\r\n y = list(float(element) for element in yline) \r\n\r\n self.File.close()\r\n return (x,y)\r\n\r\n \r\n \r\n def generatePoints(self):\r\n if self.canReadFromFile():\r\n (self.x,self.y) = self.readPointsFromFile()\r\n else:\r\n fractionDone = .1\r\n numColors = 4\r\n for i in range(self.numPoints):\r\n #for each possible combination \r\n xi = 0.0\r\n yi = 0.0\r\n colorsi = [0,0,0]\r\n #currentMaxDepth = int(np.ceil(np.log(self.numPoints+1)/np.log(self.numOfFunctions)))-1\r\n for j in range(self.depth):\r\n # go through self.depth operations\r\n #funIndex = int(i/(self.numOfFunctions**(j))) % self.numOfFunctions\r\n \r\n #Create the function index by\r\n cumulitveP = 0\r\n funIndex = 0\r\n r = np.random.random()\r\n for p in self.IFS.getProbablities():\r\n cumulitveP += p\r\n if r > cumulitveP :\r\n funIndex += 1 \r\n else: \r\n break\r\n \r\n \r\n \r\n (xi,yi) = self.functionList[funIndex](xi,yi)\r\n# colorsi = [a + b/self.depth for a,b in zip(colorsi, self.IFS.getColors()[funIndex])]\r\n self.x[i] = xi\r\n self.y[i] = yi\r\n colorProportion = int(numColors*(i/self.numPoints))/numColors\r\n self.color[i] = [a*colorProportion + b*(1.0-colorProportion) for a,b in zip(self.IFS.getColors()[0], self.IFS.getColors()[1])]\r\n \r\n \r\n if i/self.numPoints > fractionDone:\r\n print(\"%\"+str(int(fractionDone*100)) + \" Done\")\r\n fractionDone = fractionDone+.1\r\n print('%100 Done')\r\n \r\n def plotFractal(self):\r\n fig = plt.figure()\r\n fig.patch.set_alpha(1)\r\n fig.set_size_inches(30,20)\r\n ax = fig.add_subplot(1,1,1)\r\n \r\n ax.scatter(self.x,self.y,s = 1000/np.sqrt(self.numPoints), marker = \".\",c = range(self.numPoints),cmap = 'hsv',edgecolors = None)\r\n ax.set_aspect('equal')\r\n ax.xaxis.set_ticks([])\r\n ax.yaxis.set_ticks([])\r\n\r\n plt.show()\r\n fig.savefig(self.fileName +'.png',transparent = True,dpi = 200)\r\n \r\n def saveData(self):\r\n if self.overwrite or not self.canReadFromFile():\r\n self.File = open(self.fileName+\".out\",'w')\r\n for xi in self.x:\r\n self.File.write(str(xi)+',')\r\n self.File.write('\\n')\r\n print(\"%50 Done\")\r\n for yi in self.y:\r\n self.File.write(str(yi)+',') \r\n self.File.write('\\n')\r\n self.File.close()\r\n \r\n def draw(self):\r\n print(\"Generatating Points ...\")\r\n self.generatePoints()\r\n print(\"Points Generated\")\r\n print(\"Saving ...\")\r\n self.saveData()\r\n print(\"Plotting ...\")\r\n self.plotFractal()\r\n\r\nclass IFSAbstract:\r\n def getColors(self):\r\n return self.colorArray\r\n \r\n def getFunctionList(self):\r\n return self.funArray\r\n def name(self):\r\n return self.myName\r\n def getProbablities(self):\r\n #by default use equal probablities\r\n return [1/len(self.funArray)]*len(self.funArray)\r\n\r\n \r\n\r\nclass IFSGoldenDragon(IFSAbstract):\r\n def __init__(self):\r\n \r\n self.myName = \"GoldenDragon\"\r\n \r\n phi = (1+np.sqrt(5))/2\r\n r = (1/phi)**(1/phi)\r\n theta = np.arccos((1+r**2 - r**4)/(2*r))\r\n theta2 = np.pi - np.arccos((1+r**4 - r**2)/(2*r**2))\r\n \r\n self.funArray = (afineTransfrom(theta, r),\r\n afineTransfrom(theta2, r**2, np.array([[1.0],[0.0]])))\r\n self.colorArray = ((0,0,0),(162.0/255,101.0/255,223.0/255))\r\n\r\n \r\n \r\nclass IFSCustomDragon(IFSAbstract):\r\n def __init__(self,theta = np.pi/5):\r\n \r\n self.myName = \"CustomDragon\"\r\n \r\n theta1 = theta\r\n theta2 = np.pi - theta1\r\n\r\n scale1 = 0.5/np.cos(theta1)\r\n scale2 = 0.5/np.cos(theta1)\r\n self.funArray = (afineTransfrom(theta = theta1, scale = scale1),\r\n afineTransfrom(theta = theta2, scale = scale2, translation=np.array([[1.0],[0.0]])))\r\n self.colorArray = ((0,0,0),(162.0/255,101.0/255,223.0/255))\r\n \r\n\r\nclass IFSFern(IFSAbstract):\r\n def __init__(self):\r\n self.myName = \"Fern\"\r\n f1 = afineTransfrom(R = np.array([[0,0],[0,0.16]]),translation = np.array([[0.0],[0.0]]))\r\n f2 = afineTransfrom(R = np.array([[.85,0.04],[-0.04,0.85]]),translation = np.array([[0.0],[1.60]]))\r\n f3 = afineTransfrom(R = np.array([[.2,-0.26],[0.23,0.22]]),translation = np.array([[0.0],[1.60]]))\r\n f4 = afineTransfrom(R = np.array([[-.15,.28],[.26,0.24]]),translation = np.array([[0.0],[0.44]]))\r\n self.funArray = (f1,f2,f3,f4)\r\n self.colorArray = ((0,128/255,0),(0,64/255,0),(0,128/255,0),(0,128/255,0))\r\n self.p = (.01,.85,.07,.07)\r\n def getProbablities(self):\r\n return self.p\r\n \r\n\r\nclass afineTransfrom:\r\n def __init__(self,theta = None, R = None,scale = 1,translation = np.array([[0.0],[0.0]])):\r\n if R is None:\r\n self.R = np.array([[np.cos(theta), -np.sin(theta)],[np.sin(theta),np.cos(theta)]]) * scale\r\n else:\r\n self.R = R\r\n \r\n self.t = translation\r\n\r\n\r\n def __call__(self,x,y):\r\n v = np.array([[x],[y]])\r\n v = np.matmul(self.R,v) + self.t\r\n return (v[0][0],v[1][0])\r\n\r\n \r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n #anIFS = IFSGoldenDragon()\r\n anIFS = IFSCustomDragon(theta =2* np.pi/3-.2)\r\n #anIFS = IFSFern()\r\n myDrawBot = IFSGenerator(IFS = anIFS,depth = 21,overwrite = False)\r\n myDrawBot.draw()\r\n \r\n\r\n \r\n\r\n\r\n\r\n \r\n \r\n"
] |
[
[
"numpy.log",
"numpy.random.random",
"numpy.sqrt",
"numpy.matmul",
"numpy.cos",
"numpy.arccos",
"numpy.sin",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
guochengqian/ASSANet
|
[
"f7a63d787df0ade975085acf0504b9b06f62c722"
] |
[
"models/segmentation/assanet_seg.py"
] |
[
"import torch.nn as nn\nfrom ..encoder.assanet_encoder import ASSANetEncoder\nfrom ..decoder.assanet_decoder import ASSANetDecoder\nfrom .segmentation_head import SceneSegHeadPointNet\n\n\nclass ASSANetSeg(nn.Module):\n def __init__(self, cfg):\n \"\"\"ASSA-Net implementation for paper:\n Anisotropic Separable Set Abstraction for Efficient Point Cloud Representation Learning\n\n Args:\n cfg (dict): configuration\n \"\"\"\n super().__init__()\n self.encoder = ASSANetEncoder(cfg)\n self.decoder = ASSANetDecoder(cfg)\n self.head = SceneSegHeadPointNet(cfg.data.num_classes, in_channles=cfg.model.fp_mlps[0][0])\n\n def init_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.Conv1d):\n nn.init.kaiming_normal_(m.weight)\n if m.bias is not None:\n nn.init.zeros_(m.bias)\n\n def forward(self, xyz, features):\n l_xyz, l_features = self.encoder(xyz, features)\n return self.head(self.decoder(l_xyz, l_features))\n\n"
] |
[
[
"torch.nn.init.zeros_",
"torch.nn.init.kaiming_normal_"
]
] |
prashantraina/PlaneNet
|
[
"51fa261f7e958191fce6077cf923539acadb707b"
] |
[
"evaluate.py"
] |
[
"import tensorflow as tf\nimport numpy as np\nnp.set_printoptions(precision=2, linewidth=200)\nimport cv2\nimport os\nimport time\nimport sys\n#import tf_nndistance\nimport argparse\nimport glob\nimport PIL\nimport scipy.ndimage as ndimage\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom utils import *\n#from plane_utils import *\nfrom modules import *\n\nfrom train_planenet import build_graph\n#from train_sample import build_graph as build_graph_sample\nfrom planenet import PlaneNet\nfrom RecordReaderAll import *\n#from SegmentationRefinement import *\nfrom crfasrnn.crfasrnn_layer import CrfRnnLayer\n\n#ALL_TITLES = ['planenet', 'pixelwise', 'pixelwise+RANSAC', 'depth observation+RANSAC', 'pixelwise+semantics+RANSAC', 'gt']\n#ALL_METHODS = [('bl2_ll1_bw0.5_pb_pp_sm0', ''), ('pb_pp', 'pixelwise_1'), ('pb_pp', 'pixelwise_2'), ('pb_pp', 'pixelwise_3'), ('pb_pp', 'semantics'), ('pb_pp', 'gt')]\n\nALL_TITLES = ['PlaneNet', 'Oracle NYU toolbox', 'NYU toolbox', 'Oracle Manhattan', 'Manhattan', 'Oracle Piecewise', 'Piecewise']\n#ALL_TITLES = ['PlaneNet', '[25] + depth', '[25]', '[9] + depth', '[9]', '[26] + depth', '[26]']\n#ALL_METHODS = [('bl0_dl0_bw0.5_pb_pp_ps_sm0', ''), ('ll1_pb_pp', ''), ('bl0_ll1_bw0.5_pb_pp_ps_sm0', ''), ('ll1_bw0.5_pb_pp_sm0', '')]\n#ALL_METHODS = [('bl0_dl0_ll1_bw0.5_pb_pp_sm0', ''), ('bl0_dl0_ll1_pb_pp_sm0', ''), ('bl0_dl0_ll1_pb_pp_ps', ''), ('bl0_dl0_ll1_ds0_pb_pp', '')]\n\n#ALL_METHODS = [('bl0_dl0_ll1_pb_pp_sm0', ''), ('bl0_dl0_ll1_pb_pp_sm0', 'pixelwise_2'), ('bl0_dl0_ll1_pb_pp_sm0', 'pixelwise_3'), ('bl0_dl0_ll1_pb_pp_sm0', 'pixelwise_6'), ('bl0_dl0_ll1_pb_pp_sm0', 'pixelwise_5')]\n#ALL_METHODS = [('bl0_dl0_ll1_pb_pp_sm0', ''), ('bl0_dl0_crfrnn10_sm0', ''), ('bl0_dl0_ll1_pp_sm0', ''), ('bl0_dl0_ll1_pb_pp_sm0', ''), ('bl0_dl0_ll1_pb_pp_sm0', '')]\n\n#ALL_METHODS = [('bl0_dl0_ll1_pb_pp_sm0', '', 0), ('bl0_dl0_ll1_pb_pp_sm0', 'crfrnn', 0), ('bl0_dl0_crfrnn10_sm0', '')]\n\n#ALL_METHODS = [['planenet_hybrid3_bl0_dl0_ll1_pb_pp_sm0', '', 0, 0], ['planenet_hybrid3_bl0_dl0_ll1_pb_pp_ps_sm0', 'pixelwise_2', 1, 0], ['', 'pixelwise_3', 1, 0], ['', 'pixelwise_4', 1, 0], ['', 'pixelwise_5', 1, 0], ['', 'pixelwise_6', 1, 0], ['', 'pixelwise_7', 1, 0]]\n#ALL_METHODS = [['planenet_hybrid3_bl0_dl0_ll1_pb_pp_sm0', '', 0, 0], ['planenet_hybrid3_bl0_dl0_ll1_pb_pp_ps_sm0', 'pixelwise_2', 1, 0], ['', 'pixelwise_3', 1, 0], ['', 'pixelwise_4', 1, 0], ['', 'pixelwise_5', 1, 0], ['', 'pixelwise_6', 1, 0], ['', 'pixelwise_7', 1, 0]]\nALL_METHODS = [['sample_np10_hybrid3_bl0_dl0_ds0_crfrnn5_sm0', '', 0, 0], ['planenet_hybrid3_bl0_dl0_ll1_pb_pp_ps_sm0', 'pixelwise_2', 1, 0], ['', 'pixelwise_3', 1, 0], ['', 'pixelwise_4', 1, 0], ['', 'pixelwise_5', 1, 0], ['', 'pixelwise_6', 1, 0], ['', 'pixelwise_7', 1, 0]]\n\n#ALL_METHODS = [('ll1_pb_pp', 'pixelwise_1'), ('crf1_pb_pp', 'pixelwise_2'), ('bl0_ll1_bw0.5_pb_pp_ps_sm0', 'pixelwise_3'), ('ll1_bw0.5_pb_pp_sm0', 'pixelwise_4')]\n\n\n#ALL_TITLES = ['planenet', 'pixelwise']\n#ALL_METHODS = [('bl0_ll1_bw0.5_pb_pp_ps_sm0', ''), ('bl0_ll1_bw0.5_pb_pp_ps_sm0', 'pixelwise_1')]\n#ALL_TITLES = ['crf', 'different matching']\n#ALL_METHODS = [('pb_pp_sm0', 'crf'), ('pb_pp_sm0', '')]\n\ndef writeHTML(options):\n from html import HTML\n\n titles = options.titles\n\n h = HTML('html')\n h.p('Results')\n h.br()\n path = '.'\n #methods = ['planenet', 'pixelwise', 'pixelwise+RANSAC', 'GT+RANSAC', 'planenet+crf', 'pixelwise+semantics+RANSAC']\n #methods = ['planenet', 'pixelwise', 'pixelwise+RANSAC', 'GT+RANSAC']\n\n for index in range(options.numImages):\n\n t = h.table(border='1')\n r_inp = t.tr()\n r_inp.td('input ' + str(index))\n r_inp.td().img(src=path + '/' + str(index) + '_image.png')\n r_inp.td().img(src=path + '/' + str(index) + '_depth_gt.png')\n r_inp.td().img(src=path + '/' + str(index) + '_segmentation_gt.png')\n r_inp.td().img(src=path + '/' + str(index) + '_semantics_gt.png') \n r_inp.td().img(src=path + '/' + str(index) + '_depth_gt_plane.png')\n r_inp.td().img(src=path + '/' + str(index) + '_depth_gt_diff.png') \n # r = t.tr()\n # r.td('PlaneNet prediction')\n # r.td().img(src=firstFolder + '/' + str(index) + '_segmentation_pred.png')\n # r.td().img(src=firstFolder + '/' + str(index) + '_depth_pred.png')\n\n r = t.tr()\n r.td('methods')\n for method_index, method in enumerate(titles):\n r.td(method)\n continue\n \n r = t.tr()\n r.td('segmentation')\n for method_index, method in enumerate(titles):\n r.td().img(src=path + '/' + str(index) + '_segmentation_pred_' + str(method_index) + '.png')\n continue\n\n r = t.tr()\n r.td('depth')\n for method_index, method in enumerate(titles):\n r.td().img(src=path + '/' + str(index) + '_depth_pred_' + str(method_index) + '.png')\n continue\n h.br()\n continue\n\n metric_titles = ['depth error 0.1', 'depth error 0.2', 'depth error 0.3', 'IOU 0.3', 'IOU 0.5', 'IOU 0.7']\n\n h.p('Curves on plane accuracy')\n for title in metric_titles:\n h.img(src='curve_plane_' + title.replace(' ', '_') + '.png')\n continue\n \n h.p('Curves on pixel coverage')\n for title in metric_titles:\n h.img(src='curve_pixel_' + title.replace(' ', '_') + '.png')\n continue\n \n \n html_file = open(options.test_dir + '/index.html', 'w')\n html_file.write(str(h))\n html_file.close()\n return\n\ndef evaluatePlanes(options):\n #writeHTML(options)\n #exit(1)\n if not os.path.exists(options.test_dir):\n os.system(\"mkdir -p %s\"%options.test_dir)\n pass\n \n results = getResults(options)\n \n gt_dict = results['gt']\n predictions = results['pred']\n\n\n saving = True\n if gt_dict['image'].shape[0] != options.numImages or options.useCache == 1:\n saving = False\n pass\n \n \n for key, value in gt_dict.items():\n if options.imageIndex >= 0:\n gt_dict[key] = value[options.imageIndex:options.imageIndex + 1]\n elif value.shape[0] > options.numImages:\n gt_dict[key] = value[:options.numImages]\n pass\n continue\n for pred_dict in predictions:\n for key, value in pred_dict.items():\n if options.imageIndex >= 0:\n pred_dict[key] = value[options.imageIndex:options.imageIndex + 1]\n elif value.shape[0] > options.numImages:\n pred_dict[key] = value[:options.numImages]\n pass\n continue\n continue\n\n #methods = ['planenet', 'pixelwise+RANSAC', 'GT+RANSAC']\n\n\n \n #predictions[2] = predictions[3]\n\n\n\n \n for image_index in range(options.visualizeImages):\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_image.png', gt_dict['image'][image_index])\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_gt.png', drawDepthImage(gt_dict['depth'][image_index]))\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_normal_gt.png', drawNormalImage(gt_dict['normal'][image_index])) \n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_segmentation_gt.png', drawSegmentationImage(np.concatenate([gt_dict['segmentation'][image_index], 1 - np.expand_dims(gt_dict['plane_mask'][image_index], -1)], axis=2), blackIndex=options.numOutputPlanes))\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_semantics_gt.png', drawSegmentationImage(gt_dict['semantics'][image_index], blackIndex=0))\n\n \n plane_depths = calcPlaneDepths(gt_dict['plane'][image_index], WIDTH, HEIGHT, gt_dict['info'][image_index])\n all_depths = np.concatenate([plane_depths, np.expand_dims(gt_dict['depth'][image_index], -1)], axis=2)\n depth = np.sum(all_depths * np.concatenate([gt_dict['segmentation'][image_index], 1 - np.expand_dims(gt_dict['plane_mask'][image_index], -1)], axis=2), axis=2)\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_gt_plane.png', drawDepthImage(depth))\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_gt_diff.png', drawMaskImage((depth - gt_dict['depth'][image_index]) * 5 + 0.5)) \n\n\n for method_index, pred_dict in enumerate(predictions):\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_pred_' + str(method_index) + '.png', drawDepthImage(pred_dict['depth'][image_index]))\n\n #if 'pixelwise' in options.methods[method_index][1]:\n #continue\n segmentation = pred_dict['segmentation'][image_index]\n #segmentation = np.concatenate([segmentation, pred_dict['np_mask'][image_index]], axis=2)\n numPlanes = options.numOutputPlanes\n if 'pixelwise' in options.methods[method_index][1]:\n numPlanes = pred_dict['plane'][image_index].shape[0]\n #print(numPlanes)\n pass\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_segmentation_pred_' + str(method_index) + '.png', drawSegmentationImage(segmentation, blackIndex=numPlanes))\n continue\n continue\n\n \n #post processing\n for method_index, method in enumerate(options.methods):\n if method[1] == '':\n continue\n if len(method) < 4 or method[3] == 0:\n continue\n if len(method) >= 3 and method[2] >= 0:\n pred_dict = predictions[method[2]]\n else:\n pred_dict = predictions[method_index]\n pass\n \n if method[1] == 'graphcut':\n #pred_dict = gt_dict\n predSegmentations = []\n predDepths = []\n for image_index in range(options.numImages):\n #if image_index != 3:\n #continue\n print(('graph cut ' + str(image_index)))\n\n segmentation = np.argmax(np.concatenate([pred_dict['segmentation'][image_index], 1 - np.expand_dims(pred_dict['plane_mask'][image_index], -1)], axis=2), axis=2)\n #pred_s = getSegmentationsGraphCut(pred_dict['plane'][image_index], gt_dict['image'][image_index], pred_dict['depth'][image_index], pred_dict['normal'][image_index], segmentation, pred_dict['semantics'][image_index], pred_dict['info'][image_index], gt_dict['num_planes'][image_index])\n\n pred_p, pred_s, numPlanes = removeSmallSegments(pred_dict['plane'][image_index], gt_dict['image'][image_index], pred_dict['depth'][image_index], pred_dict['normal'][image_index], segmentation, pred_dict['semantics'][image_index], pred_dict['info'][image_index], gt_dict['num_planes'][image_index])\n #pred_p, pred_s, numPlanes = pred_dict['plane'][image_index], segmentation, gt_dict['num_planes'][image_index]\n print((gt_dict['num_planes'][image_index], numPlanes))\n planeDepths = calcPlaneDepths(pred_p, WIDTH, HEIGHT, gt_dict['info'][image_index])\n allDepths = np.concatenate([planeDepths, np.expand_dims(pred_dict['depth'][image_index], -1)], axis=2)\n pred_d = allDepths.reshape(-1, options.numOutputPlanes + 1)[np.arange(WIDTH * HEIGHT), pred_s.reshape(-1)].reshape(HEIGHT, WIDTH)\n\n predSegmentations.append(pred_s)\n predDepths.append(pred_d)\n\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_pred_' + str(method_index) + '.png', drawDepthImage(pred_d)) \n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_segmentation_pred_' + str(method_index) + '.png', drawSegmentationImage(pred_s, blackIndex=options.numOutputPlanes))\n continue \n new_pred_dict = {}\n for key, value in pred_dict.items():\n new_pred_dict[key] = value\n continue\n new_pred_dict['segmentation'] = np.array(predSegmentations)\n if method_index < len(predictions):\n predictions[method_index] = new_pred_dict\n else:\n predictions.append(new_pred_dict)\n pass\n if method[1] == 'crf_tf':\n predSegmentations = []\n predDepths = []\n\n image_inp = tf.placeholder(tf.float32, shape=[1, HEIGHT, WIDTH, 3], name='image')\n segmentation_inp = tf.placeholder(tf.float32, shape=[1, HEIGHT, WIDTH, options.numOutputPlanes + 1], name='segmentation')\n plane_inp = tf.placeholder(tf.float32, shape=[1, options.numOutputPlanes, 3], name='plane')\n non_plane_depth_inp = tf.placeholder(tf.float32, shape=[1, HEIGHT, WIDTH, 1], name='non_plane_depth')\n info_inp = tf.placeholder(tf.float32, shape=[20], name='info')\n\n \n plane_parameters = tf.reshape(plane_inp, (-1, 3))\n plane_depths = planeDepthsModule(plane_parameters, WIDTH, HEIGHT, info_inp)\n plane_depths = tf.transpose(tf.reshape(plane_depths, [HEIGHT, WIDTH, -1, options.numOutputPlanes]), [2, 0, 1, 3])\n all_depths = tf.concat([plane_depths, non_plane_depth_inp], axis=3)\n\n planesY = plane_inp[:, :, 1]\n planesD = tf.maximum(tf.norm(plane_inp, axis=-1), 1e-4)\n planesY /= planesD\n planesY = tf.concat([planesY, tf.ones((1, 1))], axis=1)\n\n #refined_segmentation = crfModule(segmentation_inp, plane_inp, non_plane_depth_inp, info_inp, numOutputPlanes = options.numOutputPlanes, numIterations=5)\n\n imageDiff = calcImageDiff(image_inp)\n #refined_segmentation, debug_dict = segmentationRefinementModule(segmentation_inp, all_depths, planesY, imageDiff, numOutputPlanes = options.numOutputPlanes + 1, numIterations=5)\n refined_segmentation, debug_dict = meanfieldModule(segmentation_inp, all_depths, planesY, imageDiff, numOutputPlanes = options.numOutputPlanes + 1, maxDepthDiff=0.2, varDepthDiff=pow(0.2, 2))\n \n config=tf.ConfigProto()\n config.gpu_options.allow_growth=True\n config.allow_soft_placement=True\n\n init_op = tf.group(tf.global_variables_initializer(),\n tf.local_variables_initializer())\n with tf.Session(config=config) as sess:\n sess.run(init_op)\n for image_index in range(options.numImages):\n #if image_index != 1:\n #continue\n print(('crf tf ' + str(image_index)))\n allSegmentations = np.concatenate([pred_dict['segmentation'][image_index], pred_dict['np_mask'][image_index]], axis=2)\n allSegmentations = softmax(allSegmentations)\n pred_s, debug = sess.run([refined_segmentation, debug_dict], feed_dict={segmentation_inp: np.expand_dims(allSegmentations, 0), plane_inp: np.expand_dims(pred_dict['plane'][image_index], 0), non_plane_depth_inp: np.expand_dims(pred_dict['np_depth'][image_index], 0), info_inp: gt_dict['info'][image_index], image_inp: gt_dict['image'][image_index:image_index + 1]})\n\n pred_s = pred_s[0]\n planeDepths = calcPlaneDepths(pred_dict['plane'][image_index], WIDTH, HEIGHT, gt_dict['info'][image_index])\n allDepths = np.concatenate([planeDepths, pred_dict['np_depth'][image_index]], axis=2)\n pred_d = np.sum(allDepths * pred_s, axis=-1)\n \n predSegmentations.append(pred_s)\n predDepths.append(pred_d)\n \n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_pred_' + str(method_index) + '.png', drawDepthImage(pred_d)) \n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_segmentation_pred_' + str(method_index) + '.png', drawSegmentationImage(pred_s, blackIndex=options.numOutputPlanes))\n\n if 'diff' in debug:\n segmentation = np.argmax(allSegmentations, axis=-1)\n for planeIndex in range(options.numOutputPlanes + 1):\n cv2.imwrite('test/mask_' + str(planeIndex) + '.png', drawMaskImage(allSegmentations[:, :, planeIndex]))\n continue\n \n for planeIndex in range(debug['diff'].shape[-1]):\n cv2.imwrite('test/cost_mask_' + str(planeIndex) + '.png', drawMaskImage(debug['diff'][0, :, :, planeIndex] / 2))\n continue\n exit(1) \n pass\n continue\n pass\n new_pred_dict = {}\n for key, value in pred_dict.items():\n new_pred_dict[key] = value\n continue\n segmentations = np.array(predSegmentations)\n new_pred_dict['segmentation'] = segmentations[:, :, :, :options.numOutputPlanes]\n new_pred_dict['non_plane_mask'] = segmentations[:, :, :, options.numOutputPlanes:options.numOutputPlanes + 1]\n #new_pred_dict['non_plane_mask'] = segmentations[:, :, :, :options.numOutputPlanes]\n new_pred_dict['depth'] = np.array(predDepths)\n if method_index < len(predictions):\n predictions[method_index] = new_pred_dict\n else:\n predictions.append(new_pred_dict)\n pass\n pass\n \n if method[1] == 'crf':\n predSegmentations = []\n predDepths = []\n for image_index in range(options.numImages):\n print(('crf ' + str(image_index)))\n boundaries = pred_dict['boundary'][image_index]\n boundaries = sigmoid(boundaries)\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_boundary.png', drawMaskImage(np.concatenate([boundaries, np.zeros((HEIGHT, WIDTH, 1))], axis=2)))\n \n allSegmentations = np.concatenate([pred_dict['segmentation'][image_index], pred_dict['np_mask'][image_index]], axis=2)\n allSegmentations = softmax(allSegmentations)\n planeDepths = calcPlaneDepths(pred_dict['plane'][image_index], WIDTH, HEIGHT, gt_dict['info'][image_index])\n allDepths = np.concatenate([planeDepths, pred_dict['np_depth'][image_index]], axis=2)\n #boundaries = np.concatenate([np.ones((allSegmentations.shape[0], allSegmentations.shape[1], 1)), -np.ones((allSegmentations.shape[0], allSegmentations.shape[1], 1))], axis=2)\n #if options.imageIndex >= 0:\n #boundaries = cv2.imread(options.test_dir + '/' + str(options.imageIndex) + '_boundary.png') \n #else:\n #boundaries = cv2.imread(options.test_dir + '/' + str(image_index) + '_boundary.png')\n #pass\n #boundaries = (boundaries > 128).astype(np.float32)[:, :, :2]\n\n allDepths[:, :, options.numOutputPlanes] = 0\n pred_s = refineSegmentation(gt_dict['image'][image_index], allSegmentations, allDepths, boundaries, numOutputPlanes = 20, numIterations=20, numProposals=5)\n pred_d = allDepths.reshape(-1, options.numOutputPlanes + 1)[np.arange(WIDTH * HEIGHT), pred_s.reshape(-1)].reshape(HEIGHT, WIDTH)\n \n predSegmentations.append(pred_s)\n predDepths.append(pred_d)\n \n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_pred_' + str(method_index) + '.png', drawDepthImage(pred_d)) \n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_segmentation_pred_' + str(method_index) + '.png', drawSegmentationImage(pred_s, blackIndex=options.numOutputPlanes))\n\n #segmentation = np.argmax(allSegmentations, axis=-1)\n # for planeIndex in xrange(options.numOutputPlanes + 1):\n # cv2.imwrite('test/mask_' + str(planeIndex) + '.png', drawMaskImage(allSegmentations[:, :, planeIndex]))\n # continue\n #cv2.imwrite(options.test_dir + '/mask_' + str(21) + '.png', drawDepthImage(pred_dict['np_depth'][0]))\n #for plane_index in xrange(options.numOutputPlanes + 1):\n #cv2.imwrite(options.test_dir + '/mask_' + str(plane_index) + '.png', drawMaskImage(pred_s == plane_index))\n #continue\n #exit(1)\n continue\n \n new_pred_dict = {}\n for key, value in pred_dict.items():\n new_pred_dict[key] = value\n continue\n new_pred_dict['segmentation'] = np.array(predSegmentations)\n new_pred_dict['depth'] = np.array(predDepths)\n if method_index < len(predictions):\n predictions[method_index] = new_pred_dict\n else:\n predictions.append(new_pred_dict)\n pass\n pass\n \n\n if 'pixelwise' in method[1]:\n predPlanes = []\n predSegmentations = []\n predDepths = []\n predNumPlanes = []\n for image_index in range(options.numImages):\n pred_d = pred_dict['np_depth'][image_index].squeeze()\n pred_n = pred_dict['np_normal'][image_index].squeeze() \n if '_1' in method[1]:\n pred_s = np.zeros(pred_dict['segmentation'][image_index].shape)\n pred_p = np.zeros(pred_dict['plane'][image_index].shape)\n elif '_2' in method[1]:\n parameters = {'distanceCostThreshold': 0.1, 'smoothnessWeight': 0.05, 'semantics': True}\n pred_p, pred_s = fitPlanesNYU(gt_dict['image'], gt_dict['depth'][image_index].squeeze(), gt_dict['normal'][image_index], gt_dict['semantics'][image_index], gt_dict['info'][image_index], numOutputPlanes=options.numOutputPlanes, parameters=parameters)\n elif '_3' in method[1]:\n parameters = {'distanceCostThreshold': 0.1, 'smoothnessWeight': 0.03, 'semantics': True, 'distanceThreshold': 0.05}\n pred_p, pred_s = fitPlanesNYU(gt_dict['image'], pred_d, pred_n, pred_dict['semantics'][image_index], gt_dict['info'][image_index], numOutputPlanes=options.numOutputPlanes, parameters=parameters)\n elif '_4' in method[1]:\n parameters = {'numProposals': 5, 'distanceCostThreshold': 0.1, 'smoothnessWeight': 30, 'dominantLineThreshold': 3, 'offsetGap': 0.1}\n pred_p, pred_s = fitPlanesManhattan(gt_dict['image'][image_index], gt_dict['depth'][image_index].squeeze(), gt_dict['normal'][image_index], gt_dict['info'][image_index], numOutputPlanes=options.numOutputPlanes, parameters=parameters)\n pred_d = np.zeros((HEIGHT, WIDTH))\n elif '_5' in method[1]:\n parameters = {'numProposals': 5, 'distanceCostThreshold': 0.1, 'smoothnessWeight': 100, 'dominantLineThreshold': 3, 'offsetGap': 0.6}\n pred_p, pred_s = fitPlanesManhattan(gt_dict['image'][image_index], pred_d, pred_n, gt_dict['info'][image_index], numOutputPlanes=options.numOutputPlanes, parameters=parameters)\n pred_d = np.zeros((HEIGHT, WIDTH))\n elif '_6' in method[1]:\n parameters = {'distanceCostThreshold': 0.1, 'smoothnessWeight': 300, 'numProposals': 5, 'normalWeight': 1, 'meanshift': 0.2}\n pred_p, pred_s = fitPlanesPiecewise(gt_dict['image'][image_index], gt_dict['depth'][image_index].squeeze(), gt_dict['normal'][image_index], gt_dict['info'][image_index], numOutputPlanes=options.numOutputPlanes, parameters=parameters)\n pred_d = np.zeros((HEIGHT, WIDTH))\n elif '_7' in method[1]:\n parameters = {'numProposals': 5, 'distanceCostThreshold': 0.1, 'smoothnessWeight': 300, 'normalWeight': 1, 'meanshift': 0.2}\n pred_p, pred_s = fitPlanesPiecewise(gt_dict['image'][image_index], pred_d, pred_n, gt_dict['info'][image_index], numOutputPlanes=options.numOutputPlanes, parameters=parameters)\n pred_d = np.zeros((HEIGHT, WIDTH))\n pass\n predPlanes.append(pred_p) \n predSegmentations.append(pred_s)\n predDepths.append(pred_d)\n predNumPlanes.append(pred_p.shape[0]) \n\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_pred_' + str(method_index) + '.png', drawDepthImage(pred_d))\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_segmentation_pred_' + str(method_index) + '.png', drawSegmentationImage(pred_s, blackIndex=pred_p.shape[0]))\n #exit(1)\n continue\n new_pred_dict = {}\n for key, value in pred_dict.items():\n new_pred_dict[key] = value\n continue\n new_pred_dict['plane'] = np.array(predPlanes) \n new_pred_dict['segmentation'] = np.array(predSegmentations)\n new_pred_dict['depth'] = np.array(predDepths)\n new_pred_dict['num_planes'] = np.array(predNumPlanes)\n if method_index < len(predictions):\n predictions[method_index] = new_pred_dict\n else:\n predictions.append(new_pred_dict)\n pass\n #titles.append('pixelwise+semantics+RANSAC')\n pass\n\n if method[1] == 'crfrnn':\n predSegmentations = []\n predDepths = []\n\n image_inp = tf.placeholder(tf.float32, shape=[1, HEIGHT, WIDTH, 3], name='image')\n segmentation_inp = tf.placeholder(tf.float32, shape=[1, HEIGHT, WIDTH, options.numOutputPlanes + 1], name='segmentation')\n \n refined_segmentation = CrfRnnLayer(image_dims=(HEIGHT, WIDTH), num_classes=21, theta_alpha=120., theta_beta=3., theta_gamma=3., num_iterations=10, name='crfrnn')([segmentation_inp, image_inp])\n \n config=tf.ConfigProto()\n config.gpu_options.allow_growth=True\n config.allow_soft_placement=True\n\n init_op = tf.group(tf.global_variables_initializer(),\n tf.local_variables_initializer())\n with tf.Session(config=config) as sess:\n sess.run(init_op)\n for image_index in range(options.numImages):\n #if image_index != 1:\n #continue\n print(('crf rnn ' + str(image_index)))\n allSegmentations = np.concatenate([pred_dict['segmentation'][image_index], pred_dict['np_mask'][image_index]], axis=2)\n img = gt_dict['image'][image_index:image_index + 1].astype(np.float32) - 128\n\n \n pred_s = sess.run(refined_segmentation, feed_dict={segmentation_inp: np.expand_dims(allSegmentations, 0), image_inp: img})\n\n # print(pred_s.shape)\n # print(pred_s[0].max())\n # print(pred_s.sum(-1).max()) \n # exit(1)\n pred_s = pred_s[0]\n # print(allSegmentations.max())\n # print(pred_s.max())\n # print(img.max())\n # print(img.min()) \n # print(np.abs(pred_s - allSegmentations).max())\n # print(np.abs(np.argmax(pred_s, axis=-1) - np.argmax(allSegmentations, axis=-1)).max())\n pred_s = one_hot(np.argmax(pred_s, axis=-1), options.numOutputPlanes + 1)\n\n \n planeDepths = calcPlaneDepths(pred_dict['plane'][image_index], WIDTH, HEIGHT, gt_dict['info'][image_index])\n allDepths = np.concatenate([planeDepths, pred_dict['np_depth'][image_index]], axis=2)\n pred_d = np.sum(allDepths * pred_s, axis=-1)\n \n predSegmentations.append(pred_s)\n predDepths.append(pred_d)\n \n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_pred_' + str(method_index) + '.png', drawDepthImage(pred_d)) \n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_segmentation_pred_' + str(method_index) + '.png', drawSegmentationImage(pred_s, blackIndex=options.numOutputPlanes))\n\n continue\n pass\n new_pred_dict = {}\n for key, value in pred_dict.items():\n new_pred_dict[key] = value\n continue\n segmentations = np.array(predSegmentations)\n new_pred_dict['segmentation'] = segmentations[:, :, :, :options.numOutputPlanes]\n new_pred_dict['non_plane_mask'] = segmentations[:, :, :, options.numOutputPlanes:options.numOutputPlanes + 1]\n #new_pred_dict['non_plane_mask'] = segmentations[:, :, :, :options.numOutputPlanes]\n new_pred_dict['depth'] = np.array(predDepths)\n if method_index < len(predictions):\n predictions[method_index] = new_pred_dict\n else:\n predictions.append(new_pred_dict)\n pass\n pass\n if saving:\n np.save(options.result_filename, {'gt': gt_dict, 'pred': predictions})\n pass\n continue\n \n #exit(1)\n \n #print(results)\n\n # depth = gt_dict['depth'][4]\n # cv2.imwrite(options.test_dir + '/test_depth_gt.png', drawDepthImage(depth))\n # pred_p, pred_s, pred_d = fitPlanes(depth, getSUNCGCamera(), numPlanes=20, planeAreaThreshold=3*4, numIterations=100, distanceThreshold=0.05, local=0.2)\n # cv2.imwrite(options.test_dir + '/test_depth.png', drawDepthImage(pred_d))\n # cv2.imwrite(options.test_dir + '/test_segmentation.png', drawSegmentationImage(pred_s))\n # exit(1)\n \n \n #plotResults(gt_dict, predictions, options)\n if options.numImages > gt_dict['image'].shape[0]:\n plotAll(options)\n else:\n plotResults(gt_dict, predictions, options)\n pass\n writeHTML(options)\n return\n\ndef plotAll(options):\n result_filenames = glob.glob(options.test_dir + '/results_*.npy')\n assert(len(result_filenames) > 0)\n results = np.load(result_filenames[0])\n results = results[()]\n gt_dict = results['gt']\n predictions = results['pred']\n\n for index in range(1, len(result_filenames)):\n other_results = np.load(result_filenames[index])\n other_results = other_results[()]\n other_gt_dict = other_results['gt']\n other_predictions = other_results['pred']\n for k, v in other_gt_dict.items():\n gt_dict[k] = np.concatenate([gt_dict[k], v], axis=0)\n continue\n for methodIndex, other_pred_dict in enumerate(other_predictions):\n if methodIndex == 1:\n continue\n for k, v in other_pred_dict.items():\n print((methodIndex, k))\n print((predictions[methodIndex][k].shape))\n print((v.shape))\n predictions[methodIndex][k] = np.concatenate([predictions[methodIndex][k], v], axis=0)\n continue\n continue\n continue\n \n plotResults(gt_dict, predictions, options)\n return\n\n\ndef plotResults(gt_dict, predictions, options):\n titles = options.titles \n\n pixel_metric_curves = []\n plane_metric_curves = []\n for method_index, pred_dict in enumerate(predictions):\n if titles[method_index] == 'pixelwise':\n continue\n segmentations = pred_dict['segmentation']\n #if method_index == 0:\n #segmentations = softmax(segmentations)\n #pass\n #pixel_curves, plane_curves = evaluatePlaneSegmentation(pred_dict['plane'], segmentations, gt_dict['plane'], gt_dict['segmentation'], gt_dict['num_planes'], numOutputPlanes = options.numOutputPlanes)\n\n pixel_curves = np.zeros((6, 13))\n plane_curves = np.zeros((6, 13, 3))\n numImages = segmentations.shape[0]\n for image_index in range(numImages):\n gtDepths = calcPlaneDepths(gt_dict['plane'][image_index], WIDTH, HEIGHT, gt_dict['info'][image_index])\n predDepths = calcPlaneDepths(pred_dict['plane'][image_index], WIDTH, HEIGHT, gt_dict['info'][image_index])\n if 'num_planes' in pred_dict:\n predNumPlanes = pred_dict['num_planes'][image_index]\n else:\n predNumPlanes = options.numOutputPlanes\n pass\n\n #if image_index != 2:\n #continue\n \n pixelStatistics, planeStatistics = evaluatePlanePrediction(predDepths, segmentations[image_index], predNumPlanes, gtDepths, gt_dict['segmentation'][image_index], gt_dict['num_planes'][image_index])\n\n # for planeIndex in xrange(options.numOutputPlanes):\n # cv2.imwrite('test/mask_' + str(planeIndex) + '.png', drawMaskImage(gt_dict['segmentation'][image_index][:, :, planeIndex]))\n # continue\n \n # mask_1 = segmentations[image_index] == 8\n # mask_2 = gt_dict['segmentation'][image_index][:, :, 3]\n # print(mask_1.sum())\n # print(mask_2.sum())\n # cv2.imwrite('test/mask_pred.png', drawMaskImage(mask_1))\n # cv2.imwrite('test/mask_gt.png', drawMaskImage(mask_2))\n # cv2.imwrite('test/mask_intersection.png', drawMaskImage(mask_2 * mask_1 > 0.5))\n # cv2.imwrite('test/mask_union.png', drawMaskImage((mask_2 + mask_1) > 0.5))\n # print((mask_2 * mask_1 > 0.5).sum())\n # print(((mask_2 + mask_1) > 0.5).sum())\n #print(image_index, planeStatistics[4][5])\n #exit(1)\n # print(pred_dict['plane'][image_index])\n # for planeIndex in xrange(options.numOutputPlanes):\n # print((segmentations[image_index] == planeIndex).sum())\n # continue\n #exit(1)\n pixel_curves += np.array(pixelStatistics)\n plane_curves += np.array(planeStatistics)\n continue\n\n\n if len(pixel_metric_curves) == 0:\n for metric_index, pixel_curve in enumerate(pixel_curves):\n pixel_metric_curves.append([])\n plane_metric_curves.append([])\n continue\n pass\n \n for metric_index, pixel_curve in enumerate(pixel_curves):\n pixel_metric_curves[metric_index].append(pixel_curve / numImages)\n continue\n for metric_index, plane_curve in enumerate(plane_curves):\n #planeScore = plane_curve[:, 0] / plane_curve[:, 1]\n plane_metric_curves[metric_index].append(plane_curve)\n continue\n continue\n\n \n #np.save(options.test_dir + '/pixel_curves.npy', np.array(pixel_metric_curves))\n #np.save(options.test_dir + '/plane_curves.npy', np.array(plane_metric_curves)) \n\n \n xs = []\n xs.append((np.arange(13) * 0.1).tolist())\n xs.append((np.arange(13) * 0.1).tolist())\n xs.append((np.arange(13) * 0.1).tolist()) \n xs.append((np.arange(13) * 0.05).tolist())\n xs.append((np.arange(13) * 0.05).tolist())\n xs.append((np.arange(13) * 0.05).tolist())\n xlabels = ['IOU threshold', 'IOU threshold', 'IOU threshold', 'depth threshold', 'depth threshold', 'depth threshold']\n curve_titles = ['depth threshold 0.1', 'depth threshold 0.2', 'depth threshold 0.3', 'IOU 0.3', 'IOU 0.5', 'IOU 0.7']\n curve_labels = [title for title in titles if title != 'pixelwise']\n\n\n # metric_index = 4\n # filename = options.test_dir + '/curves'\n # pixel_curves = pixel_metric_curves[metric_index]\n # plane_curves = plane_metric_curves[metric_index]\n # plane_curves = [plane_curve[:, 0] / plane_curve[:, 1] for plane_curve in plane_curves]\n # plotCurvesSubplot(xs[metric_index], [plane_curves, pixel_curves], filenames = [filename + '.png', filename + '_oracle.png'], xlabel=xlabels[metric_index], ylabels=['Per-plane recall', 'Per-pixel recall'], labels=curve_labels)\n # return\n \n for metric_index, curves in enumerate(pixel_metric_curves):\n if metric_index not in [4]:\n continue\n #filename = options.test_dir + '/curve_pixel_' + curve_titles[metric_index].replace(' ', '_') + '.png'\n #plotCurves(xs[metric_index], curves, filename = filename, xlabel=xlabels[metric_index], ylabel='pixel coverage', title=curve_titles[metric_index], labels=curve_labels)\n\n filename = options.test_dir + '/curve_pixel_' + curve_titles[metric_index].replace(' ', '_').replace('.', '')\n plotCurvesSplit(xs[metric_index], curves, filenames = [filename + '.png', filename + '_oracle.png'], xlabel=xlabels[metric_index], ylabel='Per-pixel recall', title=curve_titles[metric_index], labels=curve_labels)\n\n #plotCurvesSubplot(xs[metric_index], curves, filename = filename + '.png', xlabel=xlabels[metric_index], ylabel='Per-pixel recall', title=curve_titles[metric_index], labels=curve_labels)\n \n continue\n for metric_index, curves in enumerate(plane_metric_curves):\n if metric_index not in [4]:\n continue\n \n curves = [curve[:, 0] / curve[:, 1] for curve in curves]\n\n #filename = options.test_dir + '/curve_plane_' + curve_titles[metric_index].replace(' ', '_') + '.png' \n #plotCurves(xs[metric_index], curves, filename = filename, xlabel=xlabels[metric_index], ylabel='Per-plane recall', title=curve_titles[metric_index], labels=curve_labels)\n\n filename = options.test_dir + '/curve_plane_' + curve_titles[metric_index].replace(' ', '_').replace('.', '')\n plotCurvesSplit(xs[metric_index], curves, filenames = [filename + '.png', filename + '_oracle.png'], xlabel=xlabels[metric_index], ylabel='Per-plane recall', title=curve_titles[metric_index], labels=curve_labels)\n continue\n\n \ndef gridSearch(options):\n #writeHTML(options)\n #exit(1)\n\n if os.path.exists(options.result_filename):\n results = np.load(options.result_filename)\n results = results[()]\n else:\n assert(False)\n pass\n \n gt_dict = results['gt']\n predictions = results['pred']\n\n for key, value in gt_dict.items():\n if options.imageIndex >= 0:\n gt_dict[key] = value[options.imageIndex:options.imageIndex + 1]\n elif value.shape[0] > options.numImages:\n gt_dict[key] = value[:options.numImages]\n pass\n continue\n for pred_dict in predictions:\n for key, value in pred_dict.items():\n if options.imageIndex >= 0:\n pred_dict[key] = value[options.imageIndex:options.imageIndex + 1]\n elif value.shape[0] > options.numImages:\n pred_dict[key] = value[:options.numImages]\n pass\n continue\n continue\n\n #methods = ['planenet', 'pixelwise+RANSAC', 'GT+RANSAC']\n titles = options.titles\n\n\n \n for image_index in range(options.visualizeImages):\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_image.png', gt_dict['image'][image_index])\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_gt.png', drawDepthImage(gt_dict['depth'][image_index]))\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_normal_gt.png', drawNormalImage(gt_dict['normal'][image_index])) \n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_segmentation_gt.png', drawSegmentationImage(np.concatenate([gt_dict['segmentation'][image_index], 1 - np.expand_dims(gt_dict['plane_mask'][image_index], -1)], axis=2), blackIndex=options.numOutputPlanes))\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_semantics_gt.png', drawSegmentationImage(gt_dict['semantics'][image_index], blackIndex=0))\n \n plane_depths = calcPlaneDepths(gt_dict['plane'][image_index], WIDTH, HEIGHT, gt_dict['info'][image_index])\n all_depths = np.concatenate([plane_depths, np.expand_dims(gt_dict['depth'][image_index], -1)], axis=2)\n depth = np.sum(all_depths * np.concatenate([gt_dict['segmentation'][image_index], 1 - np.expand_dims(gt_dict['plane_mask'][image_index], -1)], axis=2), axis=2)\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_gt_plane.png', drawDepthImage(depth))\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_gt_diff.png', drawMaskImage((depth - gt_dict['depth'][image_index]) * 5 + 0.5)) \n \n for method_index, pred_dict in enumerate(predictions):\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_pred_' + str(method_index) + '.png', drawDepthImage(pred_dict['depth'][image_index]))\n\n if 'pixelwise' in options.methods[method_index][1]:\n continue\n segmentation = pred_dict['segmentation'][image_index]\n segmentation = np.concatenate([segmentation, pred_dict['np_mask'][image_index]], axis=2)\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_segmentation_pred_' + str(method_index) + '.png', drawSegmentationImage(segmentation, blackIndex=options.numOutputPlanes))\n continue\n continue\n\n\n #post processing\n for method_index, method in enumerate(options.methods):\n if len(method) == 3:\n pred_dict = predictions[method[2]]\n else:\n pred_dict = predictions[method_index]\n pass\n\n if 'pixelwise_2' in method[1] or 'pixelwise_3' in method[1]:\n bestScore = 0\n configurationIndex = 0\n for distanceCostThreshold in [0.3]:\n for smoothnessWeight in [0.01, 0.03, 0.05]:\n for distanceThreshold in [0.2]:\n parameters = {'distanceCostThreshold': distanceCostThreshold, 'smoothnessWeight': smoothnessWeight, 'distanceThreshold': distanceThreshold, 'semantics': True}\n score = 0\n for image_index in range(options.numImages):\n #cv2.imwrite('test/normal.png', drawNormalImage(gt_dict['normal'][image_index]))\n if '_2' in method[1]:\n pred_p, pred_s = fitPlanesNYU(gt_dict['image'][image_index], gt_dict['depth'][image_index].squeeze(), gt_dict['normal'][image_index], gt_dict['semantics'][image_index], gt_dict['info'][image_index], numOutputPlanes=options.numOutputPlanes, parameters=parameters)\n else:\n pred_d = pred_dict['np_depth'][image_index].squeeze()\n pred_n = pred_dict['np_normal'][image_index].squeeze()\n pred_p, pred_s = fitPlanesNYU(gt_dict['image'][image_index], pred_d, pred_n, pred_dict['semantics'][image_index], gt_dict['info'][image_index], numOutputPlanes=options.numOutputPlanes, parameters=parameters)\n pass\n\n predNumPlanes = pred_p.shape[0]\n gtDepths = calcPlaneDepths(gt_dict['plane'][image_index], WIDTH, HEIGHT, gt_dict['info'][image_index])\n planeDepths = calcPlaneDepths(pred_p, WIDTH, HEIGHT, gt_dict['info'][image_index])\n pixelStatistics, planeStatistics = evaluatePlanePrediction(planeDepths, pred_s, predNumPlanes, gtDepths, gt_dict['segmentation'][image_index], gt_dict['num_planes'][image_index])\n #print(pixelStatistics)\n #exit(1)\n #planeStatistics = np.array(planeStatistics)[1]\n #accuracy = (planeStatistics[3:8, 0].astype(np.float32) / np.maximum(planeStatistics[3:8, 1], 1e-4)).mean()\n\n pixelStatistics = np.array(pixelStatistics)[1]\n accuracy = pixelStatistics[3:8].mean()\n score += accuracy\n\n #cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_pred_' + str(method_index) + '.png', drawDepthImage(pred_d)) \n cv2.imwrite('test/segmentation_pred_' + str(image_index) + '.png', drawSegmentationImage(pred_s, blackIndex=options.numOutputPlanes))\n #exit(1)\n continue\n score /= options.numImages\n print((score, parameters))\n configurationIndex += 1 \n #exit(1)\n if score > bestScore:\n bestScore = score\n bestParameters = parameters\n pass\n continue\n continue\n continue\n print(bestScore)\n print(bestParameters)\n exit(1)\n \n if 'pixelwise_4' in method[1] or 'pixelwise_5' in method[1]:\n bestScore = 0\n configurationIndex = 0\n for distanceCostThreshold in [0.05]:\n for smoothnessWeight in [30]:\n for offsetGap in [-0.1]:\n parameters = {'distanceCostThreshold': distanceCostThreshold, 'smoothnessWeight': smoothnessWeight, 'offsetGap': abs(offsetGap), 'meanshift': offsetGap}\n\n score = 0\n for image_index in range(options.numImages):\n if '_4' in method[1]:\n pred_p, pred_s = fitPlanesManhattan(gt_dict['image'][image_index], gt_dict['depth'][image_index].squeeze(), gt_dict['normal'][image_index], gt_dict['info'][image_index], numOutputPlanes=options.numOutputPlanes, parameters=parameters)\n else:\n pred_d = pred_dict['np_depth'][image_index].squeeze()\n pred_n = pred_dict['np_normal'][image_index].squeeze()\n pred_p, pred_s = fitPlanesManhattan(gt_dict['image'][image_index], pred_d, pred_n, gt_dict['info'][image_index], numOutputPlanes=options.numOutputPlanes, parameters=parameters)\n pass\n\n predNumPlanes = pred_p.shape[0]\n gtDepths = calcPlaneDepths(gt_dict['plane'][image_index], WIDTH, HEIGHT, gt_dict['info'][image_index])\n planeDepths = calcPlaneDepths(pred_p, WIDTH, HEIGHT, gt_dict['info'][image_index])\n pixelStatistics, planeStatistics = evaluatePlanePrediction(planeDepths, pred_s, predNumPlanes, gtDepths, gt_dict['segmentation'][image_index], gt_dict['num_planes'][image_index])\n #print(pixelStatistics)\n #exit(1)\n #planeStatistics = np.array(planeStatistics)[1]\n #accuracy = (planeStatistics[3:8, 0].astype(np.float32) / np.maximum(planeStatistics[3:8, 1], 1e-4)).mean()\n\n pixelStatistics = np.array(pixelStatistics)[1]\n accuracy = pixelStatistics[3:8].mean()\n score += accuracy\n\n #cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_pred_' + str(method_index) + '.png', drawDepthImage(pred_d)) \n #cv2.imwrite(options.test_dir + '/' + str(image_index) + '_segmentation_pred_' + str(method_index) + '.png', drawSegmentationImage(pred_s, blackIndex=options.numOutputPlanes))\n #exit(1)\n continue\n score /= options.numImages\n print((score, parameters))\n configurationIndex += 1 \n #exit(1)\n if score > bestScore:\n bestScore = score\n bestParameters = parameters\n pass\n continue\n continue\n continue\n print(bestScore)\n print(bestParameters)\n exit(1)\n\n if 'pixelwise_6' in method[1] or 'pixelwise_7' in method[1]:\n bestScore = 0\n configurationIndex = 0 \n for distanceCostThreshold in [0.1]:\n for smoothnessWeight in [300]:\n for normalWeight in [1]:\n for offset in [0.2]:\n parameters = {'distanceCostThreshold': distanceCostThreshold, 'smoothnessWeight': smoothnessWeight, 'numProposals': 5, 'normalWeight': normalWeight, 'offsetGap': abs(offset), 'meanshift': offset}\n\n score = 0\n for image_index in range(options.numImages):\n if '_6' in method[1]:\n pred_p, pred_s = fitPlanesPiecewise(gt_dict['image'][image_index], gt_dict['depth'][image_index].squeeze(), gt_dict['normal'][image_index], gt_dict['info'][image_index], numOutputPlanes=options.numOutputPlanes, parameters=parameters)\n else:\n pred_d = pred_dict['np_depth'][image_index].squeeze() \n pred_n = pred_dict['np_normal'][image_index].squeeze() \n pred_p, pred_s = fitPlanesPiecewise(gt_dict['image'][image_index], pred_d, pred_n, gt_dict['info'][image_index], numOutputPlanes=options.numOutputPlanes, parameters=parameters)\n pass\n\n predNumPlanes = pred_p.shape[0]\n gtDepths = calcPlaneDepths(gt_dict['plane'][image_index], WIDTH, HEIGHT, gt_dict['info'][image_index])\n planeDepths = calcPlaneDepths(pred_p, WIDTH, HEIGHT, gt_dict['info'][image_index])\n pixelStatistics, planeStatistics = evaluatePlanePrediction(planeDepths, pred_s, predNumPlanes, gtDepths, gt_dict['segmentation'][image_index], gt_dict['num_planes'][image_index])\n #print(pixelStatistics)\n #exit(1)\n #planeStatistics = np.array(planeStatistics)[1]\n #accuracy = (planeStatistics[3:8, 0].astype(np.float32) / np.maximum(planeStatistics[3:8, 1], 1e-4)).mean()\n\n pixelStatistics = np.array(pixelStatistics)[1]\n accuracy = pixelStatistics[3:8].mean()\n score += accuracy\n\n #cv2.imwrite('test/depth_pred_' + str(configurationIndex) + '.png', drawDepthImage(pred_d))\n cv2.imwrite('test/segmentation_pred_' + str(image_index) + '.png', drawSegmentationImage(pred_s, blackIndex=options.numOutputPlanes))\n #exit(1)\n continue\n score /= options.numImages\n print((score, parameters))\n configurationIndex += 1\n\n #exit(1)\n if score > bestScore:\n bestScore = score\n bestParameters = parameters\n pass\n continue\n continue\n continue\n continue\n print(bestScore)\n print(bestParameters)\n exit(1) \n\n if method[1] == 'crfrnn':\n\n parameterConfigurations = []\n for alpha in [15]:\n for beta in [10]:\n for gamma in [3]:\n parameterConfigurations.append((alpha, beta, gamma))\n continue\n continue\n continue\n print(parameterConfigurations)\n\n bestScore = 0\n for parameters in parameterConfigurations:\n tf.reset_default_graph()\n image_inp = tf.placeholder(tf.float32, shape=[1, HEIGHT, WIDTH, 3], name='image')\n segmentation_inp = tf.placeholder(tf.float32, shape=[1, HEIGHT, WIDTH, options.numOutputPlanes + 1], name='segmentation')\n \n refined_segmentation = CrfRnnLayer(image_dims=(HEIGHT, WIDTH), num_classes=21, theta_alpha=parameters[0], theta_beta=parameters[1], theta_gamma=parameters[2], num_iterations=10, name='crfrnn')([segmentation_inp, image_inp])\n \n config=tf.ConfigProto()\n config.gpu_options.allow_growth=True\n config.allow_soft_placement=True\n\n init_op = tf.group(tf.global_variables_initializer(),\n tf.local_variables_initializer())\n with tf.Session(config=config) as sess:\n sess.run(init_op)\n\n score = 0.\n for image_index in range(options.numImages):\n #if image_index != 1:\n #continue\n print(('crf as rnn', image_index))\n allSegmentations = np.concatenate([pred_dict['segmentation'][image_index], pred_dict['np_mask'][image_index]], axis=2)\n img = gt_dict['image'][image_index:image_index + 1].astype(np.float32) - 128\n\n pred_s = sess.run(refined_segmentation, feed_dict={segmentation_inp: np.expand_dims(allSegmentations, 0), image_inp: img})\n pred_s = pred_s[0]\n\n #pred_s = allSegmentations\n \n pred_s = one_hot(np.argmax(pred_s, axis=-1), options.numOutputPlanes + 1)\n\n\n planeDepths = calcPlaneDepths(pred_dict['plane'][image_index], WIDTH, HEIGHT, gt_dict['info'][image_index])\n allDepths = np.concatenate([planeDepths, pred_dict['np_depth'][image_index]], axis=2)\n pred_d = np.sum(allDepths * pred_s, axis=-1)\n\n\n # for planeIndex in xrange(options.numOutputPlanes):\n # cv2.imwrite('test/mask_' + str(planeIndex) + '.png', drawMaskImage(pred_s[:, :, planeIndex]))\n # cv2.imwrite('test/gt_mask_' + str(planeIndex) + '.png', drawMaskImage(gt_dict['segmentation'][image_index][:, :, planeIndex]))\n # continue\n # cv2.imwrite('test/depth_pred.png', drawDepthImage(pred_d))\n # cv2.imwrite('test/depth_gt.png', drawDepthImage(gt_dict['depth'][image_index])) \n # cv2.imwrite('test/depth_diff.png', drawMaskImage(np.abs(pred_d - gt_dict['depth'][image_index]) * 5))\n # exit(1)\n predNumPlanes = options.numOutputPlanes\n gtDepths = calcPlaneDepths(gt_dict['plane'][image_index], WIDTH, HEIGHT, gt_dict['info'][image_index])\n pixelStatistics, planeStatistics = evaluatePlanePrediction(planeDepths, pred_s[:, :, :options.numOutputPlanes], predNumPlanes, gtDepths, gt_dict['segmentation'][image_index], gt_dict['num_planes'][image_index])\n #print(pixelStatistics)\n #exit(1)\n #planeStatistics = np.array(planeStatistics)[1]\n #accuracy = (planeStatistics[3:8, 0].astype(np.float32) / np.maximum(planeStatistics[3:8, 1], 1e-4)).mean()\n pixelStatistics = np.array(pixelStatistics)[1]\n # print(pixelStatistics)\n # pixelStatistics[3:8].mean()\n # exit(1)\n accuracy = pixelStatistics[3:8].mean()\n score += accuracy\n \n #cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_pred_' + str(method_index) + '.png', drawDepthImage(pred_d)) \n #cv2.imwrite(options.test_dir + '/' + str(image_index) + '_segmentation_pred_' + str(method_index) + '.png', drawSegmentationImage(pred_s, blackIndex=options.numOutputPlanes))\n #exit(1)\n continue\n score /= options.numImages\n print((score, parameters))\n #exit(1)\n if score > bestScore:\n bestScore = score\n bestParameters = parameters\n pass\n pass\n continue\n print((bestScore, bestParameters))\n pass\n continue\n return\n\n\ndef evaluateDepthPrediction(options):\n\n if not os.path.exists(options.test_dir):\n os.system(\"mkdir -p %s\"%options.test_dir)\n pass\n\n if options.useCache == 1 and os.path.exists(options.result_filename):\n results = np.load(options.result_filename)\n results = results[()]\n else:\n results = getResults(options)\n if options.useCache != -2:\n np.save(options.result_filename, results)\n pass\n pass\n \n gt_dict = results['gt']\n predictions = results['pred']\n\n for key, value in gt_dict.items():\n if options.imageIndex >= 0:\n gt_dict[key] = value[options.imageIndex:options.imageIndex + 1]\n elif value.shape[0] > options.numImages:\n gt_dict[key] = value[:options.numImages]\n pass\n continue\n for pred_dict in predictions:\n for key, value in pred_dict.items():\n if options.imageIndex >= 0:\n pred_dict[key] = value[options.imageIndex:options.imageIndex + 1]\n elif value.shape[0] > options.numImages:\n pred_dict[key] = value[:options.numImages]\n pass\n continue\n continue\n\n titles = options.titles\n\n\n for image_index in range(options.visualizeImages):\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_image.png', gt_dict['image'][image_index])\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_gt.png', drawDepthImage(gt_dict['depth'][image_index]))\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_segmentation_gt.png', drawSegmentationImage(np.concatenate([gt_dict['segmentation'][image_index], 1 - np.expand_dims(gt_dict['plane_mask'][image_index], -1)], axis=2), blackIndex=options.numOutputPlanes))\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_semantics_gt.png', drawSegmentationImage(gt_dict['semantics'][image_index], blackIndex=0))\n\n \n # plane_depths = calcPlaneDepths(gt_dict['plane'][image_index], WIDTH, HEIGHT, gt_dict['info'][image_index])\n # all_depths = np.concatenate([plane_depths, np.expand_dims(gt_dict['depth'][image_index], -1)], axis=2)\n # depth = np.sum(all_depths * np.concatenate([gt_dict['segmentation'][image_index], 1 - np.expand_dims(gt_dict['plane_mask'][image_index], -1)], axis=2), axis=2)\n # cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_gt_plane.png', drawDepthImage(depth))\n \n for method_index, pred_dict in enumerate(predictions):\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_pred_' + str(method_index) + '.png', drawDepthImage(pred_dict['depth'][image_index]))\n\n if titles[method_index] == 'pixelwise':\n continue\n segmentation = pred_dict['segmentation'][image_index]\n segmentation = np.concatenate([segmentation, pred_dict['np_mask'][image_index]], axis=2)\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_segmentation_pred_' + str(method_index) + '.png', drawSegmentationImage(segmentation, blackIndex=options.numOutputPlanes))\n continue\n continue\n \n\n #post processing\n for method_index, method in enumerate(options.methods):\n if method[1] == 'graphcut':\n pred_dict = gt_dict\n predSegmentations = []\n predDepths = []\n for image_index in range(options.numImages):\n #if image_index != 3:\n #continue\n print(('graph cut ' + str(image_index)))\n\n segmentation = np.argmax(np.concatenate([pred_dict['segmentation'][image_index], 1 - np.expand_dims(pred_dict['plane_mask'][image_index], -1)], axis=2), axis=2)\n #pred_s = getSegmentationsGraphCut(pred_dict['plane'][image_index], gt_dict['image'][image_index], pred_dict['depth'][image_index], pred_dict['normal'][image_index], segmentation, pred_dict['semantics'][image_index], pred_dict['info'][image_index], gt_dict['num_planes'][image_index])\n\n pred_p, pred_s, numPlanes = removeSmallSegments(pred_dict['plane'][image_index], gt_dict['image'][image_index], pred_dict['depth'][image_index], pred_dict['normal'][image_index], segmentation, pred_dict['semantics'][image_index], pred_dict['info'][image_index], gt_dict['num_planes'][image_index])\n #pred_p, pred_s, numPlanes = pred_dict['plane'][image_index], segmentation, gt_dict['num_planes'][image_index]\n print((gt_dict['num_planes'][image_index], numPlanes))\n planeDepths = calcPlaneDepths(pred_p, WIDTH, HEIGHT, gt_dict['info'][image_index])\n allDepths = np.concatenate([planeDepths, np.expand_dims(pred_dict['depth'][image_index], -1)], axis=2)\n pred_d = allDepths.reshape(-1, options.numOutputPlanes + 1)[np.arange(WIDTH * HEIGHT), pred_s.reshape(-1)].reshape(HEIGHT, WIDTH)\n\n predSegmentations.append(pred_s)\n predDepths.append(pred_d)\n\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_pred_' + str(method_index) + '.png', drawDepthImage(pred_d)) \n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_segmentation_pred_' + str(method_index) + '.png', drawSegmentationImage(pred_s, blackIndex=options.numOutputPlanes))\n continue \n new_pred_dict = {}\n for key, value in pred_dict.items():\n new_pred_dict[key] = value\n continue\n new_pred_dict['segmentation'] = np.array(predSegmentations)\n predictions[method_index] = new_pred_dict\n if method[1] == 'crf_tf':\n pred_dict = predictions[method_index]\n predSegmentations = []\n predDepths = []\n\n image_inp = tf.placeholder(tf.float32, shape=[1, HEIGHT, WIDTH, 3], name='image')\n segmentation_inp = tf.placeholder(tf.float32, shape=[1, HEIGHT, WIDTH, options.numOutputPlanes + 1], name='segmentation')\n plane_inp = tf.placeholder(tf.float32, shape=[1, options.numOutputPlanes, 3], name='plane')\n non_plane_depth_inp = tf.placeholder(tf.float32, shape=[1, HEIGHT, WIDTH, 1], name='non_plane_depth')\n info_inp = tf.placeholder(tf.float32, shape=[20], name='info')\n\n \n plane_parameters = tf.reshape(plane_inp, (-1, 3))\n plane_depths = planeDepthsModule(plane_parameters, WIDTH, HEIGHT, info_inp)\n plane_depths = tf.transpose(tf.reshape(plane_depths, [HEIGHT, WIDTH, -1, options.numOutputPlanes]), [2, 0, 1, 3])\n all_depths = tf.concat([plane_depths, non_plane_depth_inp], axis=3)\n\n planesY = plane_inp[:, :, 1]\n planesD = tf.maximum(tf.norm(plane_inp, axis=-1), 1e-4)\n planesY /= planesD\n planesY = tf.concat([planesY, tf.ones((1, 1))], axis=1)\n\n #refined_segmentation = crfModule(segmentation_inp, plane_inp, non_plane_depth_inp, info_inp, numOutputPlanes = options.numOutputPlanes, numIterations=5)\n\n imageDiff = calcImageDiff(image_inp)\n #refined_segmentation, debug_dict = segmentationRefinementModule(segmentation_inp, all_depths, planesY, imageDiff, numOutputPlanes = options.numOutputPlanes + 1, numIterations=5)\n refined_segmentation, debug_dict = meanfieldModule(segmentation_inp, all_depths, planesY, imageDiff, numOutputPlanes = options.numOutputPlanes + 1, maxDepthDiff=0.2, varDepthDiff=pow(0.2, 2))\n \n config=tf.ConfigProto()\n config.gpu_options.allow_growth=True\n config.allow_soft_placement=True\n\n init_op = tf.group(tf.global_variables_initializer(),\n tf.local_variables_initializer())\n with tf.Session(config=config) as sess:\n sess.run(init_op)\n for image_index in range(options.numImages):\n #if image_index != 1:\n #continue\n print(('crf tf ' + str(image_index)))\n allSegmentations = np.concatenate([pred_dict['segmentation'][image_index], pred_dict['np_mask'][image_index]], axis=2)\n allSegmentations = softmax(allSegmentations)\n pred_s, debug = sess.run([refined_segmentation, debug_dict], feed_dict={segmentation_inp: np.expand_dims(allSegmentations, 0), plane_inp: np.expand_dims(pred_dict['plane'][image_index], 0), non_plane_depth_inp: np.expand_dims(pred_dict['np_depth'][image_index], 0), info_inp: gt_dict['info'][image_index], image_inp: gt_dict['image'][image_index:image_index + 1]})\n\n pred_s = pred_s[0]\n planeDepths = calcPlaneDepths(pred_dict['plane'][image_index], WIDTH, HEIGHT, gt_dict['info'][image_index])\n allDepths = np.concatenate([planeDepths, pred_dict['np_depth'][image_index]], axis=2)\n pred_d = np.sum(allDepths * pred_s, axis=-1)\n \n predSegmentations.append(pred_s)\n predDepths.append(pred_d)\n \n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_pred_' + str(method_index) + '.png', drawDepthImage(pred_d)) \n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_segmentation_pred_' + str(method_index) + '.png', drawSegmentationImage(pred_s, blackIndex=options.numOutputPlanes))\n\n if 'diff' in debug:\n segmentation = np.argmax(allSegmentations, axis=-1)\n for planeIndex in range(options.numOutputPlanes + 1):\n cv2.imwrite('test/mask_' + str(planeIndex) + '.png', drawMaskImage(allSegmentations[:, :, planeIndex]))\n continue\n \n for planeIndex in range(debug['diff'].shape[-1]):\n cv2.imwrite('test/cost_mask_' + str(planeIndex) + '.png', drawMaskImage(debug['diff'][0, :, :, planeIndex] / 2))\n continue\n exit(1) \n pass\n continue\n pass\n new_pred_dict = {}\n for key, value in pred_dict.items():\n new_pred_dict[key] = value\n continue\n segmentations = np.array(predSegmentations)\n new_pred_dict['segmentation'] = segmentations[:, :, :, :options.numOutputPlanes]\n new_pred_dict['non_plane_mask'] = segmentations[:, :, :, options.numOutputPlanes:options.numOutputPlanes + 1]\n #new_pred_dict['non_plane_mask'] = segmentations[:, :, :, :options.numOutputPlanes]\n new_pred_dict['depth'] = np.array(predDepths)\n predictions[method_index] = new_pred_dict\n pass\n \n if method[1] == 'crf':\n pred_dict = predictions[method_index]\n predSegmentations = []\n predDepths = []\n for image_index in range(options.numImages):\n print(('crf ' + str(image_index)))\n boundaries = pred_dict['boundary'][image_index]\n boundaries = sigmoid(boundaries)\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_boundary.png', drawMaskImage(np.concatenate([boundaries, np.zeros((HEIGHT, WIDTH, 1))], axis=2)))\n \n allSegmentations = np.concatenate([pred_dict['segmentation'][image_index], pred_dict['np_mask'][image_index]], axis=2)\n allSegmentations = softmax(allSegmentations)\n planeDepths = calcPlaneDepths(pred_dict['plane'][image_index], WIDTH, HEIGHT, gt_dict['info'][image_index])\n allDepths = np.concatenate([planeDepths, pred_dict['np_depth'][image_index]], axis=2)\n #boundaries = np.concatenate([np.ones((allSegmentations.shape[0], allSegmentations.shape[1], 1)), -np.ones((allSegmentations.shape[0], allSegmentations.shape[1], 1))], axis=2)\n #if options.imageIndex >= 0:\n #boundaries = cv2.imread(options.test_dir + '/' + str(options.imageIndex) + '_boundary.png') \n #else:\n #boundaries = cv2.imread(options.test_dir + '/' + str(image_index) + '_boundary.png')\n #pass\n #boundaries = (boundaries > 128).astype(np.float32)[:, :, :2]\n\n allDepths[:, :, options.numOutputPlanes] = 0\n pred_s = refineSegmentation(gt_dict['image'][image_index], allSegmentations, allDepths, boundaries, numOutputPlanes = options.numOutputPlanes, numIterations=20, numProposals=5)\n pred_d = allDepths.reshape(-1, options.numOutputPlanes + 1)[np.arange(WIDTH * HEIGHT), pred_s.reshape(-1)].reshape(HEIGHT, WIDTH)\n \n predSegmentations.append(pred_s)\n predDepths.append(pred_d)\n \n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_pred_' + str(method_index) + '.png', drawDepthImage(pred_d)) \n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_segmentation_pred_' + str(method_index) + '.png', drawSegmentationImage(pred_s, blackIndex=options.numOutputPlanes))\n\n #segmentation = np.argmax(allSegmentations, axis=-1)\n for planeIndex in range(options.numOutputPlanes + 1):\n cv2.imwrite('test/mask_' + str(planeIndex) + '.png', drawMaskImage(allSegmentations[:, :, planeIndex]))\n continue\n #cv2.imwrite(options.test_dir + '/mask_' + str(21) + '.png', drawDepthImage(pred_dict['np_depth'][0]))\n #for plane_index in xrange(options.numOutputPlanes + 1):\n #cv2.imwrite(options.test_dir + '/mask_' + str(plane_index) + '.png', drawMaskImage(pred_s == plane_index))\n #continue\n #exit(1)\n continue\n \n new_pred_dict = {}\n for key, value in pred_dict.items():\n new_pred_dict[key] = value\n continue\n new_pred_dict['segmentation'] = np.array(predSegmentations)\n new_pred_dict['depth'] = np.array(predDepths)\n predictions[method_index] = new_pred_dict\n pass\n \n\n if 'pixelwise' in method[1]:\n pred_dict = predictions[method_index]\n predPlanes = []\n predSegmentations = []\n predDepths = [] \n for image_index in range(options.numImages):\n pred_d = pred_dict['np_depth'][image_index].squeeze()\n if '_1' in method[1]:\n pred_s = np.zeros(pred_dict['segmentation'][image_index].shape)\n pred_p = np.zeros(pred_dict['plane'][image_index].shape) \n elif '_2' in methods[1]:\n pred_p, pred_s, pred_d = fitPlanes(pred_d, gt_dict['info'][image_index], numPlanes=options.numOutputPlanes, planeAreaThreshold=3*4, numIterations=100, distanceThreshold=0.05, local=0.2)\n elif '_3' in methods[1]:\n pred_p, pred_s, pred_d = fitPlanes(pred_d, gt_dict['info'][image_index], numPlanes=options.numOutputPlanes, planeAreaThreshold=3*4, numIterations=100, distanceThreshold=0.05, local=0.2)\n elif '_4' in methods[1]:\n pred_p, pred_s, pred_d = fitPlanesSegmentation(pred_d, pred_dict['semantics'][image_index], gt_dict['info'][image_index], numPlanes=options.numOutputPlanes, planeAreaThreshold=3*4, numIterations=100, distanceThreshold=0.05, local=0.2)\n pass\n predPlanes.append(pred_p) \n predSegmentations.append(pred_s)\n predDepths.append(pred_d)\n\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_pred_' + str(method_index) + '.png', drawDepthImage(pred_d))\n cv2.imwrite(options.test_dir + '/' + str(image_index) + '_segmentation_pred_' + str(method_index) + '.png', drawSegmentationImage(pred_s))\n continue\n new_pred_dict = {}\n for key, value in pred_dict.items():\n new_pred_dict[key] = value\n continue\n new_pred_dict['plane'] = np.array(predPlanes) \n new_pred_dict['segmentation'] = np.array(predSegmentations)\n new_pred_dict['depth'] = np.array(predDepths)\n predictions[method_index] = new_pred_dict\n #titles.append('pixelwise+semantics+RANSAC')\n pass\n continue\n\n\n \n for method_index, pred_dict in enumerate(predictions):\n print((titles[method_index]))\n evaluateDepths(pred_dict['depth'], gt_dict['depth'], np.ones(gt_dict['depth'].shape))\n continue\n return\n\ndef getResults(options):\n checkpoint_prefix = 'checkpoint/'\n\n methods = options.methods\n predictions = []\n\n if os.path.exists(options.result_filename):\n if options.useCache == 1:\n results = np.load(options.result_filename)\n results = results[()]\n return results\n elif options.useCache == 2:\n results = np.load(options.result_filename)\n results = results[()]\n gt_dict = results['gt']\n predictions = results['pred']\n else:\n gt_dict = getGroundTruth(options)\n pass\n else:\n gt_dict = getGroundTruth(options)\n pass\n \n \n\n for method_index, method in enumerate(methods):\n if len(method) < 4 or method[3] < 2:\n continue\n if method[0] == '':\n continue\n\n\n method_options = copy.deepcopy(options)\n if 'ds0' not in method[0]:\n method_options.deepSupervisionLayers = ['res4b22_relu', ]\n else:\n method_options.deepSupervisionLayers = []\n pass\n method_options.predictConfidence = 0\n method_options.predictLocal = 0\n method_options.predictPixelwise = 1\n method_options.predictBoundary = int('pb' in method[0])\n method_options.anchorPlanes = 0\n if 'ps' in method[0]:\n method_options.predictSemantics = 1\n else:\n method_options.predictSemantics = 0\n pass\n if 'crfrnn' in method[0]:\n method_options.crfrnn = int(method[0].split('crfrnn')[1].split('_')[0])\n else:\n method_options.crfrnn = 0\n pass\n if 'ap1' in method[0]:\n method_options.anchorPlanes = 1 \n pass\n\n method_options.numOutputPlanes = 20\n if 'np10' in method[0]:\n method_options.numOutputPlanes = 10\n elif 'np15' in method[0]:\n method_options.numOutputPlanes = 15\n pass\n\n \n method_options.checkpoint_dir = checkpoint_prefix + method[0]\n print((method_options.checkpoint_dir))\n \n method_options.suffix = method[1]\n\n method_names = [previous_method[0] for previous_method in methods[:method_index]]\n\n if method[0] in method_names:\n pred_dict = predictions[method_names.index(method[0])]\n elif method[0] == 'gt':\n pred_dict = gt_dict\n else:\n pred_dict = getPrediction(method_options)\n pass\n\n # for image_index in xrange(options.visualizeImages):\n # cv2.imwrite(options.test_dir + '/' + str(image_index) + '_depth_pred_' + str(method_index) + '.png', drawDepthImage(pred_dict['depth'][image_index]))\n # cv2.imwrite(options.test_dir + '/' + str(image_index) + '_segmentation_pred_' + str(method_index) + '.png', drawSegmentationImage())\n # continue\n\n if len(method) >= 4 and method[3] == 3:\n predictions.insert(0, pred_dict)\n else:\n if method_index < len(predictions):\n predictions[method_index] = pred_dict\n else:\n predictions.append(pred_dict)\n pass\n pass\n continue\n #np.save(options.test_dir + '/curves.npy', curves)\n results = {'gt': gt_dict, 'pred': predictions}\n\n if options.useCache != -1:\n np.save(options.result_filename, results)\n pass\n pass\n \n return results\n\ndef getPrediction(options):\n tf.reset_default_graph()\n \n options.batchSize = 1\n min_after_dequeue = 1000\n\n reader = RecordReaderAll()\n if options.dataset == 'SUNCG':\n filename_queue = tf.train.string_input_producer([options.dataFolder + '/planes_SUNCG_val.tfrecords'], num_epochs=10000)\n elif options.dataset == 'NYU_RGBD':\n filename_queue = tf.train.string_input_producer([options.dataFolder + '/planes_nyu_rgbd_val.tfrecords'], num_epochs=1)\n options.deepSupervision = 0\n options.predictLocal = 0\n elif options.dataset == 'matterport':\n filename_queue = tf.train.string_input_producer([options.dataFolder + '/planes_matterport_val.tfrecords'], num_epochs=1)\n else:\n filename_queue = tf.train.string_input_producer([options.dataFolder + '/planes_scannet_val.tfrecords'], num_epochs=1)\n pass\n\n img_inp, global_gt_dict, local_gt_dict = reader.getBatch(filename_queue, numOutputPlanes=options.numOutputPlanes, batchSize=options.batchSize, min_after_dequeue=min_after_dequeue, getLocal=True, random=False)\n \n\n \n training_flag = tf.constant(False, tf.bool)\n\n options.gpu_id = 0\n # if 'sample' not in options.checkpoint_dir:\n # global_pred_dict, _, _ = build_graph(img_inp, img_inp, training_flag, options)\n # else:\n # global_pred_dict, _, _ = build_graph_sample(img_inp, img_inp, training_flag, options)\n global_pred_dict, _, _ = build_graph(img_inp, img_inp, training_flag, options)\n \n var_to_restore = tf.global_variables()\n\n\n config=tf.ConfigProto()\n config.gpu_options.allow_growth=True\n config.allow_soft_placement=True\n init_op = tf.group(tf.global_variables_initializer(),\n tf.local_variables_initializer())\n\n \n pred_dict = {}\n with tf.Session(config=config) as sess:\n sess.run(init_op)\n #var_to_restore = [v for v in var_to_restore if 'res4b22_relu_non_plane' not in v.name]\n loader = tf.train.Saver(var_to_restore)\n loader.restore(sess, \"%s/checkpoint.ckpt\"%(options.checkpoint_dir))\n #loader.restore(sess, options.fineTuningCheckpoint)\n \n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n \n \n try:\n predDepths = []\n predPlanes = []\n predSegmentations = []\n predSemantics = [] \n predNonPlaneDepths = []\n predNonPlaneNormals = [] \n predNonPlaneMasks = []\n predBoundaries = [] \n for index in range(options.startIndex + options.numImages):\n if index % 10 == 0:\n print(('image', index))\n pass\n t0=time.time()\n\n img, global_gt, global_pred = sess.run([img_inp, global_gt_dict, global_pred_dict])\n\n if index < options.startIndex:\n continue \n\n\n pred_p = global_pred['plane'][0]\n pred_s = global_pred['segmentation'][0]\n \n pred_np_m = global_pred['non_plane_mask'][0]\n pred_np_d = global_pred['non_plane_depth'][0]\n pred_np_n = global_pred['non_plane_normal'][0]\n \n if global_gt['info'][0][19] > 1 and global_gt['info'][0][19] < 4 and False:\n pred_np_n = calcNormal(pred_np_d.squeeze(), global_gt['info'][0])\n pass\n\n\n pred_b = global_pred['boundary'][0]\n predNonPlaneMasks.append(pred_np_m) \n predNonPlaneDepths.append(pred_np_d)\n predNonPlaneNormals.append(pred_np_n)\n predBoundaries.append(pred_b)\n \n all_segmentations = np.concatenate([pred_s, pred_np_m], axis=2)\n plane_depths = calcPlaneDepths(pred_p, WIDTH, HEIGHT, global_gt['info'][0])\n all_depths = np.concatenate([plane_depths, pred_np_d], axis=2)\n\n segmentation = np.argmax(all_segmentations, 2)\n pred_d = all_depths.reshape(-1, options.numOutputPlanes + 1)[np.arange(WIDTH * HEIGHT), segmentation.reshape(-1)].reshape(HEIGHT, WIDTH)\n\n if 'semantics' in global_pred:\n #cv2.imwrite('test/semantics.png', drawSegmentationImage(np.argmax(global_pred['semantics'][0], axis=-1)))\n #exit(1)\n predSemantics.append(np.argmax(global_pred['semantics'][0], axis=-1))\n else:\n predSemantics.append(np.zeros((HEIGHT, WIDTH)))\n pass\n \n predDepths.append(pred_d)\n predPlanes.append(pred_p)\n #predSegmentations.append(pred_s)\n predSegmentations.append(segmentation)\n \n continue\n pred_dict['plane'] = np.array(predPlanes)\n pred_dict['segmentation'] = np.array(predSegmentations)\n pred_dict['semantics'] = np.array(predSemantics) \n pred_dict['depth'] = np.array(predDepths)\n pred_dict['np_depth'] = np.array(predNonPlaneDepths)\n pred_dict['np_normal'] = np.array(predNonPlaneNormals)\n pred_dict['np_mask'] = np.array(predNonPlaneMasks)\n pred_dict['boundary'] = np.array(predBoundaries)\n pass\n except tf.errors.OutOfRangeError:\n print('Done training -- epoch limit reached')\n finally:\n # When done, ask the threads to stop.\n coord.request_stop()\n pass\n \n # Wait for threads to finish.\n coord.join(threads)\n sess.close()\n pass\n return pred_dict\n\ndef getGroundTruth(options): \n options.batchSize = 1\n min_after_dequeue = 1000\n\n reader = RecordReaderAll()\n if options.dataset == 'SUNCG':\n filename_queue = tf.train.string_input_producer([options.dataFolder + '/planes_SUNCG_val.tfrecords'], num_epochs=1)\n elif options.dataset == 'NYU_RGBD':\n filename_queue = tf.train.string_input_producer([options.dataFolder + '/planes_nyu_rgbd_val.tfrecords'], num_epochs=1)\n options.deepSupervision = 0\n options.predictLocal = 0\n elif options.dataset == 'matterport':\n filename_queue = tf.train.string_input_producer([options.dataFolder + '/planes_matterport_val.tfrecords'], num_epochs=1)\n else:\n filename_queue = tf.train.string_input_producer([options.dataFolder + '/planes_scannet_val.tfrecords'], num_epochs=1)\n pass\n\n\n img_inp, global_gt_dict, local_gt_dict = reader.getBatch(filename_queue, numOutputPlanes=options.numOutputPlanes, batchSize=options.batchSize, min_after_dequeue=min_after_dequeue, getLocal=True, random=False)\n \n\n training_flag = tf.constant(False, tf.bool)\n\n # if options.dataset == 'NYU_RGBD':\n # global_gt_dict['segmentation'], global_gt_dict['plane_mask'] = tf.ones((options.batchSize, HEIGHT, WIDTH, options.numOutputPlanes)), tf.ones((options.batchSize, HEIGHT, WIDTH, 1))\n # elif options.dataset == 'SUNCG':\n # normalDotThreshold = np.cos(np.deg2rad(5))\n # distanceThreshold = 0.05 \n # global_gt_dict['segmentation'], global_gt_dict['plane_mask'] = fitPlaneMasksModule(global_gt_dict['plane'], global_gt_dict['depth'], global_gt_dict['normal'], width=WIDTH, height=HEIGHT, normalDotThreshold=normalDotThreshold, distanceThreshold=distanceThreshold, closing=True, one_hot=True)\n # else:\n # global_gt_dict['plane_mask'] = 1 - global_gt_dict['non_plane_mask']\n # pass\n\n config=tf.ConfigProto()\n config.gpu_options.allow_growth=True\n config.allow_soft_placement=True\n\n init_op = tf.group(tf.global_variables_initializer(),\n tf.local_variables_initializer())\n\n gt_dict = {}\n \n with tf.Session(config=config) as sess:\n sess.run(init_op)\n \n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord) \n \n try:\n gtDepths = []\n gtNormals = [] \n planeMasks = []\n #predMasks = []\n gtPlanes = []\n gtSegmentations = []\n gtSemantics = [] \n gtInfo = []\n gtNumPlanes = [] \n images = []\n\n for index in range(options.startIndex + options.numImages):\n print(('image', index))\n t0=time.time()\n\n img, global_gt = sess.run([img_inp, global_gt_dict])\n\n if index < options.startIndex:\n continue\n\n \n # print(global_gt['path'])\n # if index == 11:\n # cv2.imwrite('test/mask.png', drawMaskImage(global_gt['non_plane_mask'].squeeze()))\n # exit(1)\n image = ((img[0] + 0.5) * 255).astype(np.uint8)\n images.append(image)\n\n #cv2.imwrite(options.test_dir + '/' + str(index) + '_boundary.png', drawMaskImage(np.concatenate([global_gt['boundary'][0], np.zeros((HEIGHT, WIDTH, 1))], axis=2)))\n \n gt_d = global_gt['depth'].squeeze()\n gtDepths.append(gt_d)\n\n if global_gt['info'][0][19] == 3:\n gt_n = calcNormal(gt_d, global_gt['info'][0])\n #cv2.imwrite('test/normal.png', drawNormalImage(gt_n))\n #exit(1)\n else:\n gt_n = global_gt['normal'][0]\n pass \n gtNormals.append(gt_n)\n \n planeMask = np.squeeze(1 - global_gt['non_plane_mask'])\n planeMasks.append(planeMask)\n \n gt_p = global_gt['plane'][0]\n gtPlanes.append(gt_p)\n gt_s = global_gt['segmentation'][0]\n gtSegmentations.append(gt_s)\n gt_semantics = global_gt['semantics'][0]\n gtSemantics.append(gt_semantics)\n gt_num_p = global_gt['num_planes'][0]\n gtNumPlanes.append(gt_num_p)\n \n gtInfo.append(global_gt['info'][0])\n continue\n\n gt_dict['image'] = np.array(images)\n gt_dict['depth'] = np.array(gtDepths)\n gt_dict['normal'] = np.array(gtNormals)\n gt_dict['plane_mask'] = np.array(planeMasks)\n gt_dict['plane'] = np.array(gtPlanes)\n gt_dict['segmentation'] = np.array(gtSegmentations)\n gt_dict['semantics'] = np.array(gtSemantics)\n gt_dict['num_planes'] = np.array(gtNumPlanes)\n gt_dict['info'] = np.array(gtInfo)\n\n except tf.errors.OutOfRangeError:\n print('Done training -- epoch limit reached')\n finally:\n # When done, ask the threads to stop.\n coord.request_stop()\n pass\n \n # Wait for threads to finish.\n coord.join(threads)\n sess.close()\n pass\n return gt_dict\n\n\nif __name__=='__main__':\n \"\"\"\n Parse input arguments\n \"\"\"\n parser = argparse.ArgumentParser(description='Planenet')\n parser.add_argument('--task', dest='task',\n help='task type',\n default='plane', type=str)\n parser.add_argument('--numOutputPlanes', dest='numOutputPlanes',\n help='the number of output planes',\n default=20, type=int)\n parser.add_argument('--dataset', dest='dataset',\n help='dataset name',\n default='ScanNet', type=str)\n parser.add_argument('--hybrid', dest='hybrid',\n help='hybrid',\n default='3', type=str)\n parser.add_argument('--visualizeImages', dest='visualizeImages',\n help='visualize image',\n default=30, type=int) \n parser.add_argument('--numImages', dest='numImages',\n help='the number of images',\n default=30, type=int)\n parser.add_argument('--startIndex', dest='startIndex',\n help='start index',\n default=0, type=int) \n parser.add_argument('--useCache', dest='useCache',\n help='use cache',\n default=-1, type=int)\n # parser.add_argument('--useCRF', dest='useCRF',\n # help='use crf',\n # default=0, type=int)\n # parser.add_argument('--useSemantics', dest='useSemantics',\n # help='use semantics',\n # default=0, type=int)\n parser.add_argument('--useNonPlaneDepth', dest='useNonPlaneDepth',\n help='use non-plane depth',\n default=0, type=int)\n parser.add_argument('--imageIndex', dest='imageIndex',\n help='image index',\n default=-1, type=int)\n parser.add_argument('--methods', dest='methods',\n help='methods',\n default='2000000', type=str)\n parser.add_argument('--dataFolder', dest='dataFolder',\n help='data folder',\n default='/mnt/vision/PlaneNet/', type=str)\n \n args = parser.parse_args()\n #args.hybrid = 'hybrid' + args.hybrid\n args.test_dir = 'evaluate/'\n args.visualizeImages = min(args.visualizeImages, args.numImages)\n if args.imageIndex >= 0:\n args.visualizeImages = 1\n args.numImages = 1 \n pass\n\n #args.titles = [ALL_TITLES[int(method)] for method in args.methods]\n #args.methods = [ALL_METHODS[int(method)] for method in args.methods]\n args.titles = ALL_TITLES\n methods = ALL_METHODS\n for methodIndex, flag in enumerate(args.methods):\n methods[methodIndex][3] = int(flag)\n pass\n args.methods = methods\n \n args.result_filename = args.test_dir + '/results_' + str(args.startIndex) + '.npy'\n print((args.titles))\n \n if args.task == 'plane':\n evaluatePlanes(args)\n elif args.task == 'depth':\n evaluateDepthPrediction(args)\n elif args.task == 'search':\n gridSearch(args)\n pass\n"
] |
[
[
"numpy.expand_dims",
"tensorflow.concat",
"numpy.squeeze",
"tensorflow.global_variables",
"numpy.concatenate",
"numpy.arange",
"numpy.save",
"tensorflow.ConfigProto",
"tensorflow.reset_default_graph",
"numpy.argmax",
"tensorflow.Session",
"tensorflow.train.Saver",
"numpy.load",
"numpy.zeros",
"tensorflow.norm",
"tensorflow.train.Coordinator",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.train.string_input_producer",
"numpy.array",
"numpy.sum",
"tensorflow.constant",
"tensorflow.local_variables_initializer",
"tensorflow.train.start_queue_runners",
"numpy.set_printoptions",
"tensorflow.reshape",
"tensorflow.ones",
"numpy.ones"
]
] |
rick-kline/cnaa-434-etf
|
[
"5e5c2de8c8851109075eed50e1f9a2846c5b4884"
] |
[
"build_etf_model/main.py"
] |
[
"\nfrom datetime import datetime, timedelta\nfrom dateutil.relativedelta import relativedelta\nfrom pytz import timezone\nfrom google.cloud import bigquery\nimport pandas as pd\nimport google.auth\nimport json\nimport base64\nimport logging\nfrom google.cloud import pubsub_v1\n\n# Triggered from a message on a Cloud Pub/Sub topic.\ndef build_etf_model(event, context):\n # consume and manipulate data from Pub/Sub message\n if 'data' in event:\n name = base64.b64decode(event['data']).decode('utf-8')\n name_dict = json.loads(name)\n\n project = name_dict.get('data').get('project')\n region = name_dict.get('data').get('region')\n\n # Set dates for data\n now = datetime.now(timezone('US/Eastern'))\n roll_one_yr = relativedelta(days=-365)\n train_end = relativedelta(days=-1)\n\n train_start_date = now + roll_one_yr\n train_start_notm = pd.to_datetime(train_start_date).date()\n train_end_date = now + train_end\n train_end_notm = pd.to_datetime(train_end_date).date()\n\n train_strt_str = train_start_notm.strftime(\"%Y-%m-%d\")\n train_end_str = train_end_notm.strftime(\"%Y-%m-%d\")\n\n credentials, project = google.auth.default(\n scopes=['https://www.googleapis.com/auth/bigquery']\n )\n\n client = bigquery.Client(\n project = project,\n credentials=credentials\n )\n \n # Build model\n train_query = \"\"\"\n CREATE OR REPLACE MODEL \"\"\" + \"`\"+ project + \"`\"+ \"\"\".etf_models.etf_price_forecast\n OPTIONS(model_type='ARIMA',\n time_series_data_col='close_trade_price',\n time_series_timestamp_col='close_date',\n time_series_id_col='etf_symbol') AS\n SELECT etf_symbol\n , CAST(close_date AS TIMESTAMP) AS close_date\n , close_trade_price\n FROM \"\"\" + \"`\"+ project + \"`\"+ \"\"\".etf_dataset.etf_ytd_daily_summary\n WHERE close_date BETWEEN \"\"\" + \"'\" + train_strt_str + \"'\" + \"\"\" AND \"\"\" + \"'\" + train_end_str +\"'\" +\"\"\"\n ORDER BY close_date \"\"\"\n\n client.query(train_query)\n\n\n\n\n\n\n\n"
] |
[
[
"pandas.to_datetime"
]
] |
open-risk/Academy-Course-DAT31018
|
[
"551e9128ef2c07302552ad3fa554ebee69aa8f14"
] |
[
"Step_5b_outlier_report.py"
] |
[
"# (c) 2019 Open Risk (https://www.openriskmanagement.com)\n#\n# This code is licensed under the Apache 2.0 license a copy of which is included\n# in the source distribution of the course. This is notwithstanding any licenses of\n# third-party software included in this distribution. You may not use this file except in\n# compliance with the License.\n#\n# Unless required by applicable law or agreed to in writing, software distributed under\n# the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n# either express or implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport pandas as pd\n\n# Load the data from hdf file\ndf = pd.read_hdf('german_credit.h5', 'df')\n\n# select numerical type variables\nnum_df = df.select_dtypes(include='int64')\nnum_list = list(num_df.columns)\nprint(num_list)\n\n# Select the z-score multiple that defines an outlier\nalpha = 5\n\nprint(80*'=')\nprint(\"Data Outliers\")\nprint(80*'=')\nfor attr in num_list:\n avg = num_df[attr].mean()\n vol = num_df[attr].std()\n lb = avg - alpha * vol\n rb = avg + alpha * vol\n # Right boundary outliers\n right_outlier_no = len(num_df[attr].pipe(lambda x: x[x > rb]))\n # Left boundary outliers\n left_outlier_no = len(num_df[attr].pipe(lambda x: x[x < lb]))\n print(attr, left_outlier_no, right_outlier_no)\n if right_outlier_no > 0:\n print('Right Boundary Outliers ', num_df[attr].pipe(lambda x: x[x > rb]).values)\n print(80 * '.')\n if left_outlier_no > 0:\n print('Left Boundary Outliers ', num_df[attr].pipe(lambda x: x[x < lb]).values)\n print(80 * '.')\n\n\n\n"
] |
[
[
"pandas.read_hdf"
]
] |
us4useu/arrus
|
[
"10487b09f556e327ddb1bec28fbaccf3b8b08064"
] |
[
"api/python/arrus/devices/probe.py"
] |
[
"import dataclasses\nimport numpy as np\nimport math\n\n\[email protected](frozen=True)\nclass ProbeModelId:\n manufacturer: str\n name: str\n\n\[email protected](frozen=True)\nclass ProbeModel:\n model_id: ProbeModelId\n n_elements: int\n pitch: float\n curvature_radius: float\n\n def __post_init__(self):\n element_pos_x, element_pos_z, element_angle = self._compute_element_position()\n super().__setattr__(\"element_pos_x\", element_pos_x)\n super().__setattr__(\"element_pos_z\", element_pos_z)\n super().__setattr__(\"element_angle\", element_angle)\n\n def _compute_element_position(self):\n # element position along the surface\n element_position = np.arange(-(self.n_elements - 1) / 2,\n self.n_elements / 2)\n element_position = element_position * self.pitch\n\n if not self.is_convex_array():\n x_pos = element_position\n z_pos = np.zeros((1, self.n_elements))\n angle = np.zeros(self.n_elements)\n else:\n angle = element_position / self.curvature_radius\n x_pos = self.curvature_radius * np.sin(angle)\n z_pos = self.curvature_radius * np.cos(angle)\n z_pos = z_pos - np.min(z_pos)\n return x_pos, z_pos, angle\n\n def is_convex_array(self):\n return not (math.isnan(self.curvature_radius)\n or self.curvature_radius == 0.0)\n\n\[email protected](frozen=True)\nclass ProbeDTO:\n model: ProbeModel\n\n def get_id(self):\n return \"Probe:0\""
] |
[
[
"numpy.min",
"numpy.arange",
"numpy.cos",
"numpy.sin",
"numpy.zeros"
]
] |
guimarais/dapc
|
[
"5b99fd511325d91c0cb05d9e29aeaf238f128c13"
] |
[
"my_utils/utils.py"
] |
[
"import numpy as np\n\ndef testf(xmin=-5.0, xmax=5.0, dstep=0.01, noise=0.0):\n \"\"\"Returns a simple sin function to test several examples\n \n Parameters:\n -----------\n xmin: Lowest x axis value\n xmax: Highest x axis value\n dstep: Step for x-axis\n noise: Amplitude of the noise to add to the signal, which is a Standard Normal distribution\n \n Returns\n -------\n x: Equally spaced x values between \"xmin\" and \"xmax\" with a step fot \"dstep\"\n y: The sin of x\n \"\"\"\n x = np.arange(xmin, xmax, dstep)\n y = np.sin(x) + noise*np.random.randn(len(x))\n return x, y\n\ndef mov_avg(x, N=5):\n \"\"\"Calculates the moving average through a simple convolution\n \n Parameters:\n -----------\n x: The data for smoothing\n N: Number of points used in the smoothing (convulution)\n \n Returns\n -------\n smt_x: x convolved with a len(N) array where every entry is 1/N \n \"\"\"\n smt_x = np.convolve(x, np.ones((N,))/N)[(N-1):] \n return smt_x"
] |
[
[
"numpy.arange",
"numpy.ones",
"numpy.sin"
]
] |
Napam/MayhemPacman
|
[
"cbcb3b4a2c83ed920e32748a8aaadb29b19ab5bf",
"cbcb3b4a2c83ed920e32748a8aaadb29b19ab5bf"
] |
[
"states/game_state_online.py",
"classes/planet.py"
] |
[
"'''\r\nModule containing the online game class called mayhem\r\n\r\nWritten by Naphat Amundsen\r\n'''\r\nimport pygame as pg\r\nimport numpy as np \r\nimport pickle\r\nimport time\r\nimport itertools\r\nfrom multiprocessing import Pipe, Process\r\nfrom importlib import reload\r\n\r\nimport user_settings as cng\r\nfrom states import state_config as state_cng\r\nfrom instances import instance_config as game_cng\r\n\r\nfrom states import state\r\nfrom states import game_state\r\n\r\nfrom classes import spaceship\r\nfrom classes import projectile\r\nfrom classes import maps\r\n\r\nfrom images import images as imgs\r\nfrom instances import game_instances as game_i\r\nfrom instances import ui_instances as ui_i\r\n\r\nfrom server import network as net \r\n\r\nFRAME_TIME = 1/cng.fps\r\nCOLORS = pg.colordict.THECOLORS\r\n\r\ndef handshake(bridge, ship):\r\n '''\r\n Initialize handshake with server\r\n This function returns the client_id (int)\r\n '''\r\n out_data = pickle.dumps(ship)\r\n bridge.send(out_data)\r\n \r\n client_id = pickle.loads(bridge.recv(state_cng.recv_size))\r\n \r\n return client_id\r\n\r\ndef server_comm_protocol(bridge, pipe, ship, bullets):\r\n '''\r\n Stands for server communication protocoll. This function handles the \r\n client-server communication, and is meant to be run by a parallell process to\r\n reduce in-game stuttering.\r\n '''\r\n # TODO: Contemplate buffersize, should at least be 16kb\r\n recv_size = 1024*32\r\n bridge.client_socket.settimeout(5.0)\r\n while True:\r\n try:\r\n kill_signal, ship, bullets = pipe.recv()\r\n if(kill_signal):\r\n pipe.close()\r\n return\r\n data_to_send = pickle.dumps([ship, bullets])\r\n bridge.send(data_to_send)\r\n \r\n try:\r\n all_ships, all_bullets, planets, asteroids = pickle.loads(bridge.recv(state_cng.recv_size))\r\n except:\r\n pass\r\n\r\n all_bullets = list(itertools.chain.from_iterable(all_bullets))\r\n \r\n pipe.send([all_ships, all_bullets, planets, asteroids])\r\n except:\r\n print(\"Client comm process terminated\")\r\n pipe.send([0,0,0,0])\r\n pipe.close()\r\n return\r\n\r\nclass mayhem(game_state.mayhem):\r\n '''\r\n Multiplayer (LAN) mayhem class, inherits the single-player mayhem class\r\n and is meant to be a part of a state machine.\r\n '''\r\n def __init__(self, MANAGER, WINDOW):\r\n super().__init__(MANAGER, WINDOW)\r\n\r\n def init_attributes(self):\r\n '''Helper method for initializing attributes, used for soft-reloading'''\r\n self.planets = []\r\n self.asteroids = []\r\n self.all_ships = []\r\n self.bullets = []\r\n \r\n self.ship = game_i.ship\r\n self.camera = np.array([self.w_shape[0], self.w_shape[1]])/2 - self.ship.pos\r\n self.show_refuel = False\r\n self.show_loading_ammo = False\r\n \r\n def update_graphics(self):\r\n '''\r\n Blits and flips\r\n\r\n The objects does not contain any surface objects to be blitted and therefore\r\n needs to be given which image to blit. This is because the the objects should \r\n be lightweight (and you can't pickle surfaces anyways) in order to be sent\r\n to a server during an online session.\r\n '''\r\n self.WINDOW.fill(self.bg_color)\r\n\r\n self.WINDOW.blit(\r\n imgs.bg_img,\r\n self.camera\r\n )\r\n\r\n self.planets[0].draw(self.WINDOW, self.camera, imgs.earth_img)\r\n self.planets[1].draw(self.WINDOW, self.camera, imgs.venus_img)\r\n game_i.sun.draw(self.WINDOW, self.camera, imgs.sun_img)\r\n\r\n for ship in self.all_ships:\r\n ship.draw(self.WINDOW, self.camera, imgs.enemyship_img)\r\n\r\n for asteroid, img in zip(self.asteroids, imgs.asteroid_imgs):\r\n asteroid.draw(self.WINDOW, self.camera, img)\r\n \r\n for bullet in self.all_bullets:\r\n bullet.draw(self.WINDOW, self.camera, imgs.bullet_img)\r\n\r\n self.ship.draw(\r\n self.WINDOW,\r\n self.camera,\r\n imgs.ship_img\r\n )\r\n\r\n self.minimap.draw(\r\n WINDOW=self.WINDOW,\r\n colors=game_i.minimap_colors_online,\r\n sizes=game_i.minimap_sizes_online,\r\n bullets=self.all_bullets,\r\n sun=[game_i.sun],\r\n celestials=self.planets,\r\n asteroids=self.asteroids,\r\n others=self.all_ships,\r\n )\r\n\r\n self.minimap.draw_player(\r\n self.WINDOW,\r\n game_i.ship, \r\n 2\r\n )\r\n\r\n for text in ui_i.indicators:\r\n text.draw(self.WINDOW)\r\n pg.display.update()\r\n \r\n def logic(self):\r\n '''\r\n Method for handling logic \r\n '''\r\n self.ship.update(self)\r\n \r\n for bullet in self.bullets:\r\n bullet.update(self)\r\n bullet.interact_ship(self.all_ships, self.bullets)\r\n\r\n def parallell_comm_protocol(self, pipe):\r\n '''\r\n Stands for parallell communication protocoll, and is the \r\n function that is meant to be called from the main process to communicate\r\n with the parallell process via a pipe.\r\n '''\r\n self.all_ships, self.all_bullets, self.planets, self.asteroids = pipe.recv()\r\n if self.all_ships == 0:\r\n return 0\r\n del(self.all_ships[self.client_id])\r\n self.all_ships = list(self.all_ships.values())\r\n return 1\r\n\r\n def run(self):\r\n '''\r\n The \"main\" loop \r\n '''\r\n self.socket = net.Network()\r\n\r\n # If socket fails to connect to server\r\n if not self.socket.connect():\r\n self._active = False\r\n return self.MANAGER.get_state('main_menu')\r\n \r\n state_pipe, comm_pipe = Pipe()\r\n\r\n self.client_id = handshake(self.socket, self.ship)\r\n print(f\"Client id = {self.client_id}\")\r\n\r\n # Run server communication protocol in separate process\r\n p = Process(target=server_comm_protocol, args=(self.socket, comm_pipe, self.ship, self.bullets))\r\n p.start()\r\n\r\n while(self._active):\r\n state_pipe.send((0, self.ship, self.bullets)) \r\n if not self.parallell_comm_protocol(state_pipe):\r\n self._active = False\r\n self.next_state = self.MANAGER.get_state('main_menu')\r\n break\r\n self.dt = self.clock.tick(cng.fps)\r\n\r\n # TODO: Check if this works properly for high fps\r\n self.lag_correction = self.dt/self.target_timestep \r\n \r\n self.update_graphics()\r\n self.update_user_input()\r\n self.logic()\r\n\r\n # This needs to be below update graphics for some reason\r\n self.animations()\r\n \r\n # Terminate parallell process by telling it to kill itself\r\n state_pipe.send((1, None, None))\r\n self.socket.client_socket.close()\r\n \r\n p.join()\r\n # p.close happens automatically during garbage collection, and using p.close raises attribute error for some computers\r\n # p.close()\r\n \r\n return self.next_state\r\n\r\n \r\n",
"'''\r\nModule containing classes for celestial bodies (planets)\r\n\r\nWritten by Naphat Amundsen\r\n'''\r\nimport pygame as pg \r\nimport numpy as np\r\n\r\nfrom classes import template_classes\r\n\r\nclass planet(template_classes.game_object):\r\n '''\r\n Class for a planet object. The planet object feels a force pulling the object \r\n towards the state's map's center. \r\n\r\n Inherits the template object 'game_object'. \r\n '''\r\n def __init__(self, pos, init_vel, init_dir, rforce):\r\n super().__init__(pos, init_dir, init_vel) \r\n self.f_radial_const = rforce\r\n \r\n def draw(self, WINDOW, camera, img):\r\n '''Blits given image at position offset by camera'''\r\n self.pos = self.pos.astype('int')\r\n centered_pos = img.get_rect(center=self.pos)\r\n\r\n WINDOW.blit(\r\n img,\r\n [centered_pos.x, centered_pos.y]+camera\r\n )\r\n\r\n def draw_rotate(self, WINDOW, camera, img, degrees):\r\n '''\r\n Blits given image at position offset by camera, takes in additional \r\n argumet degrees for blitting a rotated version of the image\r\n '''\r\n rot_img = pg.transform.rotate(img, degrees)\r\n rot_img_rect = rot_img.get_rect(center=self.pos)\r\n\r\n WINDOW.blit(\r\n rot_img,\r\n (rot_img_rect.x + camera[0], rot_img_rect.y + camera[1])\r\n )\r\n\r\n def radial_force(self, state):\r\n '''\r\n Method to make planets feel the gravitational pull towards the given state's map object's center\r\n '''\r\n dir_to_middle = state.map.center-self.pos\r\n dist_to_middle = np.linalg.norm(dir_to_middle)\r\n dir_to_middle = dir_to_middle/dist_to_middle\r\n\r\n self.vel = self.vel + (self.f_radial_const/dist_to_middle**2)*dir_to_middle\r\n\r\n def motion(self):\r\n '''\r\n Method for integration velocity into position. Motion is not \r\n lag corrected (haven't bothered calculating the required adjustment\r\n in the numerator of GMm/r^2 to conserve the trajectory with a lag \r\n correction scalar)\r\n '''\r\n self.pos = self.pos + self.vel\r\n \r\n def update(self, state):\r\n '''Updates planet behavior'''\r\n self.radial_force(state)\r\n self.motion()\r\n \r\n\r\nclass rotating_planet(planet):\r\n '''\r\n Inherits planet and simply has an angle and anglespeed. The additional attributes \r\n are used for drawing a rotating planet. The attributes gets updated when the\r\n planet moves. \r\n\r\n This class if used for asteroids as well. \r\n '''\r\n def __init__(self, pos, init_vel, init_dir, r_force, omega):\r\n super().__init__(pos, init_vel, init_dir, r_force)\r\n self.theta = 0\r\n self.omega = omega\r\n \r\n def motion(self):\r\n '''\r\n Method for integration velocity into position. Motion is not \r\n lag corrected (haven't bothered calculating the required adjustment\r\n in the numerator of GMm/r^2 to conserve the trajectory with a lag \r\n correction scalar)\r\n '''\r\n self.pos = self.pos + self.vel\r\n self.theta = (self.theta+self.omega) % 360\r\n\r\n def draw(self, WINDOW, camera, img):\r\n '''This exists (even though draw_rotate already is in scope) to ensure compitability in the state'''\r\n rot_img = pg.transform.rotate(img, self.theta)\r\n rot_img_rect = rot_img.get_rect(center=self.pos)\r\n\r\n WINDOW.blit(\r\n rot_img,\r\n (rot_img_rect.x + camera[0], rot_img_rect.y + camera[1])\r\n )\r\n\r\n\r\n"
] |
[
[
"numpy.array"
],
[
"numpy.linalg.norm"
]
] |
Jhsmit/PyHDX-paper
|
[
"50b756c47488365e5f43eadc373f2943c0cee5b3"
] |
[
"anal_chem/fig_2fg_rainbowclouds.py"
] |
[
"from functions.logging import write_log\nfrom functions.base import *\nfrom functions.rainbows import label_axes, kdeplot, boxplot, stripplot\nfrom functions.formatting import *\nimport proplot as pplt\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom pyhdx.fileIO import csv_to_protein\n\n# Rainclouds:\n# Allen M, Poggiali D, Whitaker K et al. Raincloud plots: a multi-platform tool for robust data visualization [version 1; peer review: 2 approved]. Wellcome Open Res 2019, 4:63. DOI: 10.12688/wellcomeopenres.15191.1\n\nwrite_log(__file__)\n\noutput = 'save'\noutput_dir = current_dir / 'figures' / 'Fig_2'\noutput_dir.mkdir(parents=True, exist_ok=True)\nfname = 'Fig_2fg_rainbow_proteins'\n\n\nreg = 1\nplt.rcParams[\"image.composite_image\"] = False\n\nf_states = [\n 'TF_monomer_4C',\n 'SecA_monomer',\n 'MBP_wt',\n 'PPiA_WT',\n 'PPiB_WT',\n 'ecSecB',\n 'hPREP_default',\n 'bcl2',\n 'EscV'\n]\n\nf_labels = [\n '$\\it{ec}$TF',\n '$\\it{ec}$SecA',\n '$\\it{ec}$MBP',\n '$\\it{ec}$PpiA',\n '$\\it{ec}$PpiB',\n '$\\it{ec}$SecB',\n '$\\it{h}$PREP',\n '$\\it{h}$Bcl-2',\n '$\\it{ec}$SctV'\n]\n\nf_labels = np.array(f_labels)\n\n# Load data\nfit_dir = 'single_fits'\nreg_dir = f\"r1_{reg}\"\nfiles = [fitresults_dir / fit_dir / state / reg_dir / 'fit_result.csv' for state in f_states]\n\n# List of deltaG values as numpy arrays\ndeltaGs = np.array([csv_to_protein(f)['deltaG'].dropna().to_numpy()*1e-3 for f in files], dtype=object)\n\n# Sort by mean deltaG\nidx = np.argsort([np.mean(arr) for arr in deltaGs])\nf_data = deltaGs[idx]\nf_labels = f_labels[idx]\n\ng_states = ['TF_dimer_4C', 'SecA_1-901_wt_apo']\ng_labels = np.array(['$\\it{ec}$TF$_{2}$', '$\\it{ec}$SecA$_{2}$'])\n\nfiles = [fitresults_dir / fit_dir / state / reg_dir / 'fit_result.csv' for state in g_states]\ndeltaGs = np.array([csv_to_protein(f)['deltaG'].dropna().to_numpy()*1e-3 for f in files], dtype=object)\n\nidx = np.argsort([np.mean(arr) for arr in deltaGs])\ng_data = deltaGs[idx]\ng_labels = g_labels[idx]\n\n#%%\n\nboxplot_width = 0.1\norientation = 'vertical'\n\nstrip_kwargs = dict(offset=0.0, orientation=orientation, s=2, colors='k', jitter=0.2, alpha=0.25)\nkde_kwargs = dict(linecolor='k', offset=0.15, orientation=orientation, fillcolor=False, fill_cmap=rgb_cmap,\n fill_norm=rgb_norm, y_scale=5, y_norm=None, linewidth=1)\nboxplot_kwargs = dict(offset=0.2, sym='', linewidth=1., linecolor='k', orientation=orientation, widths=boxplot_width)\n\nfig, axes = pplt.subplots(ncols=2, width=page_width/25.4, aspect=5, ref=1, wratios=[4, 1], sharey=False)\nax = axes[0]\nstripplot(f_data, ax=ax, **strip_kwargs)\nkdeplot(f_data, ax=ax, **kde_kwargs)\nboxplot(f_data, ax=ax, **boxplot_kwargs)\nlabel_axes(f_labels, ax=ax, rotation=0)\nax.format(xlim=(-0.75, len(f_data) - 0.5), ylabel=dG_ylabel, yticklabelloc='left', ytickloc='left',\n ylim=ax.get_ylim()[::-1])\n\n\nax = axes[1]\nstripplot(g_data, ax=ax, **strip_kwargs)\nkdeplot(g_data, ax=ax, **kde_kwargs)\nboxplot(g_data, ax=ax, **boxplot_kwargs)\n#\nlabel_axes(g_labels, ax=ax, rotation=0)\nax.format(xlim=(-0.5, len(g_data) - 0.5), yticklabelloc='right', ytickloc='right', ylabel='',\n ylim=axes[0].get_ylim())\n#\ntick_labels = [0, 20, 40]\nadd_colorbar(fig, ax, rgb_cmap, rgb_norm, tick_labels=tick_labels)\n\nif output == 'show':\n plt.show()\nelif output == 'save':\n plt.savefig(output_dir / f'{fname}.png')\n plt.savefig(output_dir / f'{fname}.pdf')\n\n"
] |
[
[
"numpy.array",
"numpy.mean",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.show"
]
] |
sum-coderepo/seaborn
|
[
"069d53a3dd29a965987705c823883a93700bbe5e"
] |
[
"seaborn/distributions.py"
] |
[
"\"\"\"Plotting functions for visualizing distributions.\"\"\"\nfrom numbers import Number\nfrom functools import partial\nimport math\nimport warnings\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.transforms as tx\nfrom matplotlib.colors import to_rgba\nfrom matplotlib.collections import LineCollection\n\nfrom ._core import (\n VectorPlotter,\n)\nfrom ._statistics import (\n KDE,\n Histogram,\n ECDF,\n)\nfrom .axisgrid import (\n FacetGrid,\n _facet_docs,\n)\nfrom .utils import (\n remove_na,\n _kde_support,\n _normalize_kwargs,\n _check_argument,\n _assign_default_kwargs,\n _default_color,\n)\nfrom .palettes import color_palette\nfrom .external import husl\nfrom .external.kde import gaussian_kde\nfrom ._decorators import _deprecate_positional_args\nfrom ._docstrings import (\n DocstringComponents,\n _core_docs,\n)\n\n\n__all__ = [\"displot\", \"histplot\", \"kdeplot\", \"ecdfplot\", \"rugplot\", \"distplot\"]\n\n# ==================================================================================== #\n# Module documentation\n# ==================================================================================== #\n\n_dist_params = dict(\n\n multiple=\"\"\"\nmultiple : {{\"layer\", \"stack\", \"fill\"}}\n Method for drawing multiple elements when semantic mapping creates subsets.\n Only relevant with univariate data.\n \"\"\",\n log_scale=\"\"\"\nlog_scale : bool or number, or pair of bools or numbers\n Set axis scale(s) to log. A single value sets the data axis for univariate\n distributions and both axes for bivariate distributions. A pair of values\n sets each axis independently. Numeric values are interpreted as the desired\n base (default 10). If `False`, defer to the existing Axes scale.\n \"\"\",\n legend=\"\"\"\nlegend : bool\n If False, suppress the legend for semantic variables.\n \"\"\",\n cbar=\"\"\"\ncbar : bool\n If True, add a colorbar to annotate the color mapping in a bivariate plot.\n Note: Does not currently support plots with a ``hue`` variable well.\n \"\"\",\n cbar_ax=\"\"\"\ncbar_ax : :class:`matplotlib.axes.Axes`\n Pre-existing axes for the colorbar.\n \"\"\",\n cbar_kws=\"\"\"\ncbar_kws : dict\n Additional parameters passed to :meth:`matplotlib.figure.Figure.colorbar`.\n \"\"\",\n)\n\n_param_docs = DocstringComponents.from_nested_components(\n core=_core_docs[\"params\"],\n facets=DocstringComponents(_facet_docs),\n dist=DocstringComponents(_dist_params),\n kde=DocstringComponents.from_function_params(KDE.__init__),\n hist=DocstringComponents.from_function_params(Histogram.__init__),\n ecdf=DocstringComponents.from_function_params(ECDF.__init__),\n)\n\n\n# ==================================================================================== #\n# Internal API\n# ==================================================================================== #\n\n\nclass _DistributionPlotter(VectorPlotter):\n\n semantics = \"x\", \"y\", \"hue\", \"weights\"\n\n wide_structure = {\"x\": \"@values\", \"hue\": \"@columns\"}\n flat_structure = {\"x\": \"@values\"}\n\n def __init__(\n self,\n data=None,\n variables={},\n ):\n\n super().__init__(data=data, variables=variables)\n\n @property\n def univariate(self):\n \"\"\"Return True if only x or y are used.\"\"\"\n # TODO this could go down to core, but putting it here now.\n # We'd want to be conceptually clear that univariate only applies\n # to x/y and not to other semantics, which can exist.\n # We haven't settled on a good conceptual name for x/y.\n return bool({\"x\", \"y\"} - set(self.variables))\n\n @property\n def data_variable(self):\n \"\"\"Return the variable with data for univariate plots.\"\"\"\n # TODO This could also be in core, but it should have a better name.\n if not self.univariate:\n raise AttributeError(\"This is not a univariate plot\")\n return {\"x\", \"y\"}.intersection(self.variables).pop()\n\n @property\n def has_xy_data(self):\n \"\"\"Return True at least one of x or y is defined.\"\"\"\n # TODO see above points about where this should go\n return bool({\"x\", \"y\"} & set(self.variables))\n\n def _add_legend(\n self,\n ax_obj, artist, fill, element, multiple, alpha, artist_kws, legend_kws,\n ):\n \"\"\"Add artists that reflect semantic mappings and put then in a legend.\"\"\"\n # TODO note that this doesn't handle numeric mappings like the relational plots\n handles = []\n labels = []\n for level in self._hue_map.levels:\n color = self._hue_map(level)\n\n kws = self._artist_kws(\n artist_kws, fill, element, multiple, color, alpha\n )\n\n # color gets added to the kws to workaround an issue with barplot's color\n # cycle integration but it causes problems in this context where we are\n # setting artist properties directly, so pop it off here\n if \"facecolor\" in kws:\n kws.pop(\"color\", None)\n\n handles.append(artist(**kws))\n labels.append(level)\n\n if isinstance(ax_obj, mpl.axes.Axes):\n ax_obj.legend(handles, labels, title=self.variables[\"hue\"], **legend_kws)\n else: # i.e. a FacetGrid. TODO make this better\n legend_data = dict(zip(labels, handles))\n ax_obj.add_legend(\n legend_data,\n title=self.variables[\"hue\"],\n label_order=self.var_levels[\"hue\"],\n **legend_kws\n )\n\n def _artist_kws(self, kws, fill, element, multiple, color, alpha):\n \"\"\"Handle differences between artists in filled/unfilled plots.\"\"\"\n kws = kws.copy()\n if fill:\n kws = _normalize_kwargs(kws, mpl.collections.PolyCollection)\n kws.setdefault(\"facecolor\", to_rgba(color, alpha))\n\n if element == \"bars\":\n # Make bar() interface with property cycle correctly\n # https://github.com/matplotlib/matplotlib/issues/19385\n kws[\"color\"] = \"none\"\n\n if multiple in [\"stack\", \"fill\"] or element == \"bars\":\n kws.setdefault(\"edgecolor\", mpl.rcParams[\"patch.edgecolor\"])\n else:\n kws.setdefault(\"edgecolor\", to_rgba(color, 1))\n elif element == \"bars\":\n kws[\"facecolor\"] = \"none\"\n kws[\"edgecolor\"] = to_rgba(color, alpha)\n else:\n kws[\"color\"] = to_rgba(color, alpha)\n return kws\n\n def _quantile_to_level(self, data, quantile):\n \"\"\"Return data levels corresponding to quantile cuts of mass.\"\"\"\n isoprop = np.asarray(quantile)\n values = np.ravel(data)\n sorted_values = np.sort(values)[::-1]\n normalized_values = np.cumsum(sorted_values) / values.sum()\n idx = np.searchsorted(normalized_values, 1 - isoprop)\n levels = np.take(sorted_values, idx, mode=\"clip\")\n return levels\n\n def _cmap_from_color(self, color):\n \"\"\"Return a sequential colormap given a color seed.\"\"\"\n # Like so much else here, this is broadly useful, but keeping it\n # in this class to signify that I haven't thought overly hard about it...\n r, g, b, _ = to_rgba(color)\n h, s, _ = husl.rgb_to_husl(r, g, b)\n xx = np.linspace(-1, 1, int(1.15 * 256))[:256]\n ramp = np.zeros((256, 3))\n ramp[:, 0] = h\n ramp[:, 1] = s * np.cos(xx)\n ramp[:, 2] = np.linspace(35, 80, 256)\n colors = np.clip([husl.husl_to_rgb(*hsl) for hsl in ramp], 0, 1)\n return mpl.colors.ListedColormap(colors[::-1])\n\n def _default_discrete(self):\n \"\"\"Find default values for discrete hist estimation based on variable type.\"\"\"\n if self.univariate:\n discrete = self.var_types[self.data_variable] == \"categorical\"\n else:\n discrete_x = self.var_types[\"x\"] == \"categorical\"\n discrete_y = self.var_types[\"y\"] == \"categorical\"\n discrete = discrete_x, discrete_y\n return discrete\n\n def _resolve_multiple(self, curves, multiple):\n \"\"\"Modify the density data structure to handle multiple densities.\"\"\"\n\n # Default baselines have all densities starting at 0\n baselines = {k: np.zeros_like(v) for k, v in curves.items()}\n\n # TODO we should have some central clearinghouse for checking if any\n # \"grouping\" (terminnology?) semantics have been assigned\n if \"hue\" not in self.variables:\n return curves, baselines\n\n if multiple in (\"stack\", \"fill\"):\n\n # Setting stack or fill means that the curves share a\n # support grid / set of bin edges, so we can make a dataframe\n # Reverse the column order to plot from top to bottom\n curves = pd.DataFrame(curves).iloc[:, ::-1]\n\n # Find column groups that are nested within col/row variables\n column_groups = {}\n for i, keyd in enumerate(map(dict, curves.columns.tolist())):\n facet_key = keyd.get(\"col\", None), keyd.get(\"row\", None)\n column_groups.setdefault(facet_key, [])\n column_groups[facet_key].append(i)\n\n baselines = curves.copy()\n for cols in column_groups.values():\n\n norm_constant = curves.iloc[:, cols].sum(axis=\"columns\")\n\n # Take the cumulative sum to stack\n curves.iloc[:, cols] = curves.iloc[:, cols].cumsum(axis=\"columns\")\n\n # Normalize by row sum to fill\n if multiple == \"fill\":\n curves.iloc[:, cols] = (curves\n .iloc[:, cols]\n .div(norm_constant, axis=\"index\"))\n\n # Define where each segment starts\n baselines.iloc[:, cols] = (curves\n .iloc[:, cols]\n .shift(1, axis=1)\n .fillna(0))\n\n if multiple == \"dodge\":\n\n # Account for the unique semantic (non-faceting) levels\n # This will require rethiniking if we add other semantics!\n hue_levels = self.var_levels[\"hue\"]\n n = len(hue_levels)\n for key in curves:\n level = dict(key)[\"hue\"]\n hist = curves[key].reset_index(name=\"heights\")\n hist[\"widths\"] /= n\n hist[\"edges\"] += hue_levels.index(level) * hist[\"widths\"]\n\n curves[key] = hist.set_index([\"edges\", \"widths\"])[\"heights\"]\n\n return curves, baselines\n\n # -------------------------------------------------------------------------------- #\n # Computation\n # -------------------------------------------------------------------------------- #\n\n def _compute_univariate_density(\n self,\n data_variable,\n common_norm,\n common_grid,\n estimate_kws,\n log_scale,\n warn_singular=True,\n ):\n\n # Initialize the estimator object\n estimator = KDE(**estimate_kws)\n\n all_data = self.plot_data.dropna()\n\n if set(self.variables) - {\"x\", \"y\"}:\n if common_grid:\n all_observations = self.comp_data.dropna()\n estimator.define_support(all_observations[data_variable])\n else:\n common_norm = False\n\n densities = {}\n\n for sub_vars, sub_data in self.iter_data(\"hue\", from_comp_data=True):\n\n # Extract the data points from this sub set and remove nulls\n observations = sub_data[data_variable]\n\n observation_variance = observations.var()\n if math.isclose(observation_variance, 0) or np.isnan(observation_variance):\n msg = (\n \"Dataset has 0 variance; skipping density estimate. \"\n \"Pass `warn_singular=False` to disable this warning.\"\n )\n if warn_singular:\n warnings.warn(msg, UserWarning)\n continue\n\n # Extract the weights for this subset of observations\n if \"weights\" in self.variables:\n weights = sub_data[\"weights\"]\n else:\n weights = None\n\n # Estimate the density of observations at this level\n density, support = estimator(observations, weights=weights)\n\n if log_scale:\n support = np.power(10, support)\n\n # Apply a scaling factor so that the integral over all subsets is 1\n if common_norm:\n density *= len(sub_data) / len(all_data)\n\n # Store the density for this level\n key = tuple(sub_vars.items())\n densities[key] = pd.Series(density, index=support)\n\n return densities\n\n # -------------------------------------------------------------------------------- #\n # Plotting\n # -------------------------------------------------------------------------------- #\n\n def plot_univariate_histogram(\n self,\n multiple,\n element,\n fill,\n common_norm,\n common_bins,\n shrink,\n kde,\n kde_kws,\n color,\n legend,\n line_kws,\n estimate_kws,\n **plot_kws,\n ):\n\n # -- Default keyword dicts\n kde_kws = {} if kde_kws is None else kde_kws.copy()\n line_kws = {} if line_kws is None else line_kws.copy()\n estimate_kws = {} if estimate_kws is None else estimate_kws.copy()\n\n # -- Input checking\n _check_argument(\"multiple\", [\"layer\", \"stack\", \"fill\", \"dodge\"], multiple)\n _check_argument(\"element\", [\"bars\", \"step\", \"poly\"], element)\n\n if estimate_kws[\"discrete\"] and element != \"bars\":\n raise ValueError(\"`element` must be 'bars' when `discrete` is True\")\n\n auto_bins_with_weights = (\n \"weights\" in self.variables\n and estimate_kws[\"bins\"] == \"auto\"\n and estimate_kws[\"binwidth\"] is None\n and not estimate_kws[\"discrete\"]\n )\n if auto_bins_with_weights:\n msg = (\n \"`bins` cannot be 'auto' when using weights. \"\n \"Setting `bins=10`, but you will likely want to adjust.\"\n )\n warnings.warn(msg, UserWarning)\n estimate_kws[\"bins\"] = 10\n\n # Simplify downstream code if we are not normalizing\n if estimate_kws[\"stat\"] == \"count\":\n common_norm = False\n\n # Now initialize the Histogram estimator\n estimator = Histogram(**estimate_kws)\n histograms = {}\n\n # Do pre-compute housekeeping related to multiple groups\n # TODO best way to account for facet/semantic?\n if set(self.variables) - {\"x\", \"y\"}:\n\n all_data = self.comp_data.dropna()\n\n if common_bins:\n all_observations = all_data[self.data_variable]\n estimator.define_bin_params(\n all_observations,\n weights=all_data.get(\"weights\", None),\n )\n\n else:\n common_norm = False\n\n # Estimate the smoothed kernel densities, for use later\n if kde:\n # TODO alternatively, clip at min/max bins?\n kde_kws.setdefault(\"cut\", 0)\n kde_kws[\"cumulative\"] = estimate_kws[\"cumulative\"]\n log_scale = self._log_scaled(self.data_variable)\n densities = self._compute_univariate_density(\n self.data_variable,\n common_norm,\n common_bins,\n kde_kws,\n log_scale,\n warn_singular=False,\n )\n\n # First pass through the data to compute the histograms\n for sub_vars, sub_data in self.iter_data(\"hue\", from_comp_data=True):\n\n # Prepare the relevant data\n key = tuple(sub_vars.items())\n observations = sub_data[self.data_variable]\n\n if \"weights\" in self.variables:\n weights = sub_data[\"weights\"]\n else:\n weights = None\n\n # Do the histogram computation\n heights, edges = estimator(observations, weights=weights)\n\n # Rescale the smoothed curve to match the histogram\n if kde and key in densities:\n density = densities[key]\n if estimator.cumulative:\n hist_norm = heights.max()\n else:\n hist_norm = (heights * np.diff(edges)).sum()\n densities[key] *= hist_norm\n\n # Convert edges back to original units for plotting\n if self._log_scaled(self.data_variable):\n edges = np.power(10, edges)\n\n # Pack the histogram data and metadata together\n orig_widths = np.diff(edges)\n widths = shrink * orig_widths\n edges = edges[:-1] + (1 - shrink) / 2 * orig_widths\n index = pd.MultiIndex.from_arrays([\n pd.Index(edges, name=\"edges\"),\n pd.Index(widths, name=\"widths\"),\n ])\n hist = pd.Series(heights, index=index, name=\"heights\")\n\n # Apply scaling to normalize across groups\n if common_norm:\n hist *= len(sub_data) / len(all_data)\n\n # Store the finalized histogram data for future plotting\n histograms[key] = hist\n\n # Modify the histogram and density data to resolve multiple groups\n histograms, baselines = self._resolve_multiple(histograms, multiple)\n if kde:\n densities, _ = self._resolve_multiple(\n densities, None if multiple == \"dodge\" else multiple\n )\n\n # Set autoscaling-related meta\n sticky_stat = (0, 1) if multiple == \"fill\" else (0, np.inf)\n if multiple == \"fill\":\n # Filled plots should not have any margins\n bin_vals = histograms.index.to_frame()\n edges = bin_vals[\"edges\"]\n widths = bin_vals[\"widths\"]\n sticky_data = (\n edges.min(),\n edges.max() + widths.loc[edges.idxmax()]\n )\n else:\n sticky_data = []\n\n # --- Handle default visual attributes\n\n # Note: default linewidth is determined after plotting\n\n # Default alpha should depend on other parameters\n if fill:\n # Note: will need to account for other grouping semantics if added\n if \"hue\" in self.variables and multiple == \"layer\":\n default_alpha = .5 if element == \"bars\" else .25\n elif kde:\n default_alpha = .5\n else:\n default_alpha = .75\n else:\n default_alpha = 1\n alpha = plot_kws.pop(\"alpha\", default_alpha) # TODO make parameter?\n\n hist_artists = []\n\n # Go back through the dataset and draw the plots\n for sub_vars, _ in self.iter_data(\"hue\", reverse=True):\n\n key = tuple(sub_vars.items())\n hist = histograms[key].rename(\"heights\").reset_index()\n bottom = np.asarray(baselines[key])\n\n ax = self._get_axes(sub_vars)\n\n # Define the matplotlib attributes that depend on semantic mapping\n if \"hue\" in self.variables:\n sub_color = self._hue_map(sub_vars[\"hue\"])\n else:\n sub_color = color\n\n artist_kws = self._artist_kws(\n plot_kws, fill, element, multiple, sub_color, alpha\n )\n\n if element == \"bars\":\n\n # Use matplotlib bar plotting\n\n plot_func = ax.bar if self.data_variable == \"x\" else ax.barh\n artists = plot_func(\n hist[\"edges\"],\n hist[\"heights\"] - bottom,\n hist[\"widths\"],\n bottom,\n align=\"edge\",\n **artist_kws,\n )\n\n for bar in artists:\n if self.data_variable == \"x\":\n bar.sticky_edges.x[:] = sticky_data\n bar.sticky_edges.y[:] = sticky_stat\n else:\n bar.sticky_edges.x[:] = sticky_stat\n bar.sticky_edges.y[:] = sticky_data\n\n hist_artists.extend(artists)\n\n else:\n\n # Use either fill_between or plot to draw hull of histogram\n if element == \"step\":\n\n final = hist.iloc[-1]\n x = np.append(hist[\"edges\"], final[\"edges\"] + final[\"widths\"])\n y = np.append(hist[\"heights\"], final[\"heights\"])\n b = np.append(bottom, bottom[-1])\n\n if self.data_variable == \"x\":\n step = \"post\"\n drawstyle = \"steps-post\"\n else:\n step = \"post\" # fillbetweenx handles mapping internally\n drawstyle = \"steps-pre\"\n\n elif element == \"poly\":\n\n x = hist[\"edges\"] + hist[\"widths\"] / 2\n y = hist[\"heights\"]\n b = bottom\n\n step = None\n drawstyle = None\n\n if self.data_variable == \"x\":\n if fill:\n artist = ax.fill_between(x, b, y, step=step, **artist_kws)\n else:\n artist, = ax.plot(x, y, drawstyle=drawstyle, **artist_kws)\n artist.sticky_edges.x[:] = sticky_data\n artist.sticky_edges.y[:] = sticky_stat\n else:\n if fill:\n artist = ax.fill_betweenx(x, b, y, step=step, **artist_kws)\n else:\n artist, = ax.plot(y, x, drawstyle=drawstyle, **artist_kws)\n artist.sticky_edges.x[:] = sticky_stat\n artist.sticky_edges.y[:] = sticky_data\n\n hist_artists.append(artist)\n\n if kde:\n\n # Add in the density curves\n\n try:\n density = densities[key]\n except KeyError:\n continue\n support = density.index\n\n if \"x\" in self.variables:\n line_args = support, density\n sticky_x, sticky_y = None, (0, np.inf)\n else:\n line_args = density, support\n sticky_x, sticky_y = (0, np.inf), None\n\n line_kws[\"color\"] = to_rgba(sub_color, 1)\n line, = ax.plot(\n *line_args, **line_kws,\n )\n\n if sticky_x is not None:\n line.sticky_edges.x[:] = sticky_x\n if sticky_y is not None:\n line.sticky_edges.y[:] = sticky_y\n\n if element == \"bars\" and \"linewidth\" not in plot_kws:\n\n # Now we handle linewidth, which depends on the scaling of the plot\n\n # We will base everything on the minimum bin width\n hist_metadata = pd.concat([\n # Use .items for generality over dict or df\n h.index.to_frame() for _, h in histograms.items()\n ]).reset_index(drop=True)\n thin_bar_idx = hist_metadata[\"widths\"].idxmin()\n binwidth = hist_metadata.loc[thin_bar_idx, \"widths\"]\n left_edge = hist_metadata.loc[thin_bar_idx, \"edges\"]\n\n # Set initial value\n default_linewidth = math.inf\n\n # Loop through subsets based only on facet variables\n for sub_vars, _ in self.iter_data():\n\n ax = self._get_axes(sub_vars)\n\n # Needed in some cases to get valid transforms.\n # Innocuous in other cases?\n ax.autoscale_view()\n\n # Convert binwidth from data coordinates to pixels\n pts_x, pts_y = 72 / ax.figure.dpi * abs(\n ax.transData.transform([left_edge + binwidth] * 2)\n - ax.transData.transform([left_edge] * 2)\n )\n if self.data_variable == \"x\":\n binwidth_points = pts_x\n else:\n binwidth_points = pts_y\n\n # The relative size of the lines depends on the appearance\n # This is a provisional value and may need more tweaking\n default_linewidth = min(.1 * binwidth_points, default_linewidth)\n\n # Set the attributes\n for bar in hist_artists:\n\n # Don't let the lines get too thick\n max_linewidth = bar.get_linewidth()\n if not fill:\n max_linewidth *= 1.5\n\n linewidth = min(default_linewidth, max_linewidth)\n\n # If not filling, don't let lines disappear\n if not fill:\n min_linewidth = .5\n linewidth = max(linewidth, min_linewidth)\n\n bar.set_linewidth(linewidth)\n\n # --- Finalize the plot ----\n\n # Axis labels\n ax = self.ax if self.ax is not None else self.facets.axes.flat[0]\n default_x = default_y = \"\"\n if self.data_variable == \"x\":\n default_y = estimator.stat.capitalize()\n if self.data_variable == \"y\":\n default_x = estimator.stat.capitalize()\n self._add_axis_labels(ax, default_x, default_y)\n\n # Legend for semantic variables\n if \"hue\" in self.variables and legend:\n\n if fill or element == \"bars\":\n artist = partial(mpl.patches.Patch)\n else:\n artist = partial(mpl.lines.Line2D, [], [])\n\n ax_obj = self.ax if self.ax is not None else self.facets\n self._add_legend(\n ax_obj, artist, fill, element, multiple, alpha, plot_kws, {},\n )\n\n def plot_bivariate_histogram(\n self,\n common_bins, common_norm,\n thresh, pthresh, pmax,\n color, legend,\n cbar, cbar_ax, cbar_kws,\n estimate_kws,\n **plot_kws,\n ):\n\n # Default keyword dicts\n cbar_kws = {} if cbar_kws is None else cbar_kws.copy()\n\n # Now initialize the Histogram estimator\n estimator = Histogram(**estimate_kws)\n\n # Do pre-compute housekeeping related to multiple groups\n if set(self.variables) - {\"x\", \"y\"}:\n all_data = self.comp_data.dropna()\n if common_bins:\n estimator.define_bin_params(\n all_data[\"x\"],\n all_data[\"y\"],\n all_data.get(\"weights\", None),\n )\n else:\n common_norm = False\n\n # -- Determine colormap threshold and norm based on the full data\n\n full_heights = []\n for _, sub_data in self.iter_data(from_comp_data=True):\n sub_heights, _ = estimator(\n sub_data[\"x\"], sub_data[\"y\"], sub_data.get(\"weights\", None)\n )\n full_heights.append(sub_heights)\n\n common_color_norm = not set(self.variables) - {\"x\", \"y\"} or common_norm\n\n if pthresh is not None and common_color_norm:\n thresh = self._quantile_to_level(full_heights, pthresh)\n\n plot_kws.setdefault(\"vmin\", 0)\n if common_color_norm:\n if pmax is not None:\n vmax = self._quantile_to_level(full_heights, pmax)\n else:\n vmax = plot_kws.pop(\"vmax\", max(map(np.max, full_heights)))\n else:\n vmax = None\n\n # Get a default color\n # (We won't follow the color cycle here, as multiple plots are unlikely)\n if color is None:\n color = \"C0\"\n\n # --- Loop over data (subsets) and draw the histograms\n for sub_vars, sub_data in self.iter_data(\"hue\", from_comp_data=True):\n\n if sub_data.empty:\n continue\n\n # Do the histogram computation\n heights, (x_edges, y_edges) = estimator(\n sub_data[\"x\"],\n sub_data[\"y\"],\n weights=sub_data.get(\"weights\", None),\n )\n\n # Check for log scaling on the data axis\n if self._log_scaled(\"x\"):\n x_edges = np.power(10, x_edges)\n if self._log_scaled(\"y\"):\n y_edges = np.power(10, y_edges)\n\n # Apply scaling to normalize across groups\n if estimator.stat != \"count\" and common_norm:\n heights *= len(sub_data) / len(all_data)\n\n # Define the specific kwargs for this artist\n artist_kws = plot_kws.copy()\n if \"hue\" in self.variables:\n color = self._hue_map(sub_vars[\"hue\"])\n cmap = self._cmap_from_color(color)\n artist_kws[\"cmap\"] = cmap\n else:\n cmap = artist_kws.pop(\"cmap\", None)\n if isinstance(cmap, str):\n cmap = color_palette(cmap, as_cmap=True)\n elif cmap is None:\n cmap = self._cmap_from_color(color)\n artist_kws[\"cmap\"] = cmap\n\n # Set the upper norm on the colormap\n if not common_color_norm and pmax is not None:\n vmax = self._quantile_to_level(heights, pmax)\n if vmax is not None:\n artist_kws[\"vmax\"] = vmax\n\n # Make cells at or below the threshold transparent\n if not common_color_norm and pthresh:\n thresh = self._quantile_to_level(heights, pthresh)\n if thresh is not None:\n heights = np.ma.masked_less_equal(heights, thresh)\n\n # Get the axes for this plot\n ax = self._get_axes(sub_vars)\n\n # pcolormesh is going to turn the grid off, but we want to keep it\n # I'm not sure if there's a better way to get the grid state\n x_grid = any([l.get_visible() for l in ax.xaxis.get_gridlines()])\n y_grid = any([l.get_visible() for l in ax.yaxis.get_gridlines()])\n\n mesh = ax.pcolormesh(\n x_edges,\n y_edges,\n heights.T,\n **artist_kws,\n )\n\n # pcolormesh sets sticky edges, but we only want them if not thresholding\n if thresh is not None:\n mesh.sticky_edges.x[:] = []\n mesh.sticky_edges.y[:] = []\n\n # Add an optional colorbar\n # Note, we want to improve this. When hue is used, it will stack\n # multiple colorbars with redundant ticks in an ugly way.\n # But it's going to take some work to have multiple colorbars that\n # share ticks nicely.\n if cbar:\n ax.figure.colorbar(mesh, cbar_ax, ax, **cbar_kws)\n\n # Reset the grid state\n if x_grid:\n ax.grid(True, axis=\"x\")\n if y_grid:\n ax.grid(True, axis=\"y\")\n\n # --- Finalize the plot\n\n ax = self.ax if self.ax is not None else self.facets.axes.flat[0]\n self._add_axis_labels(ax)\n\n if \"hue\" in self.variables and legend:\n\n # TODO if possible, I would like to move the contour\n # intensity information into the legend too and label the\n # iso proportions rather than the raw density values\n\n artist_kws = {}\n artist = partial(mpl.patches.Patch)\n ax_obj = self.ax if self.ax is not None else self.facets\n self._add_legend(\n ax_obj, artist, True, False, \"layer\", 1, artist_kws, {},\n )\n\n def plot_univariate_density(\n self,\n multiple,\n common_norm,\n common_grid,\n warn_singular,\n fill,\n color,\n legend,\n estimate_kws,\n **plot_kws,\n ):\n\n # Handle conditional defaults\n if fill is None:\n fill = multiple in (\"stack\", \"fill\")\n\n # Preprocess the matplotlib keyword dictionaries\n if fill:\n artist = mpl.collections.PolyCollection\n else:\n artist = mpl.lines.Line2D\n plot_kws = _normalize_kwargs(plot_kws, artist)\n\n # Input checking\n _check_argument(\"multiple\", [\"layer\", \"stack\", \"fill\"], multiple)\n\n # Always share the evaluation grid when stacking\n subsets = bool(set(self.variables) - {\"x\", \"y\"})\n if subsets and multiple in (\"stack\", \"fill\"):\n common_grid = True\n\n # Check if the data axis is log scaled\n log_scale = self._log_scaled(self.data_variable)\n\n # Do the computation\n densities = self._compute_univariate_density(\n self.data_variable,\n common_norm,\n common_grid,\n estimate_kws,\n log_scale,\n warn_singular,\n )\n\n # Adjust densities based on the `multiple` rule\n densities, baselines = self._resolve_multiple(densities, multiple)\n\n # Control the interaction with autoscaling by defining sticky_edges\n # i.e. we don't want autoscale margins below the density curve\n sticky_density = (0, 1) if multiple == \"fill\" else (0, np.inf)\n\n if multiple == \"fill\":\n # Filled plots should not have any margins\n sticky_support = densities.index.min(), densities.index.max()\n else:\n sticky_support = []\n\n if fill:\n if multiple == \"layer\":\n default_alpha = .25\n else:\n default_alpha = .75\n else:\n default_alpha = 1\n alpha = plot_kws.pop(\"alpha\", default_alpha) # TODO make parameter?\n\n # Now iterate through the subsets and draw the densities\n # We go backwards so stacked densities read from top-to-bottom\n for sub_vars, _ in self.iter_data(\"hue\", reverse=True):\n\n # Extract the support grid and density curve for this level\n key = tuple(sub_vars.items())\n try:\n density = densities[key]\n except KeyError:\n continue\n support = density.index\n fill_from = baselines[key]\n\n ax = self._get_axes(sub_vars)\n\n if \"hue\" in self.variables:\n sub_color = self._hue_map(sub_vars[\"hue\"])\n else:\n sub_color = color\n\n artist_kws = self._artist_kws(\n plot_kws, fill, False, multiple, sub_color, alpha\n )\n\n # Either plot a curve with observation values on the x axis\n if \"x\" in self.variables:\n\n if fill:\n artist = ax.fill_between(support, fill_from, density, **artist_kws)\n\n else:\n artist, = ax.plot(support, density, **artist_kws)\n\n artist.sticky_edges.x[:] = sticky_support\n artist.sticky_edges.y[:] = sticky_density\n\n # Or plot a curve with observation values on the y axis\n else:\n if fill:\n artist = ax.fill_betweenx(support, fill_from, density, **artist_kws)\n else:\n artist, = ax.plot(density, support, **artist_kws)\n\n artist.sticky_edges.x[:] = sticky_density\n artist.sticky_edges.y[:] = sticky_support\n\n # --- Finalize the plot ----\n\n ax = self.ax if self.ax is not None else self.facets.axes.flat[0]\n default_x = default_y = \"\"\n if self.data_variable == \"x\":\n default_y = \"Density\"\n if self.data_variable == \"y\":\n default_x = \"Density\"\n self._add_axis_labels(ax, default_x, default_y)\n\n if \"hue\" in self.variables and legend:\n\n if fill:\n artist = partial(mpl.patches.Patch)\n else:\n artist = partial(mpl.lines.Line2D, [], [])\n\n ax_obj = self.ax if self.ax is not None else self.facets\n self._add_legend(\n ax_obj, artist, fill, False, multiple, alpha, plot_kws, {},\n )\n\n def plot_bivariate_density(\n self,\n common_norm,\n fill,\n levels,\n thresh,\n color,\n legend,\n cbar,\n warn_singular,\n cbar_ax,\n cbar_kws,\n estimate_kws,\n **contour_kws,\n ):\n\n contour_kws = contour_kws.copy()\n\n estimator = KDE(**estimate_kws)\n\n if not set(self.variables) - {\"x\", \"y\"}:\n common_norm = False\n\n all_data = self.plot_data.dropna()\n\n # Loop through the subsets and estimate the KDEs\n densities, supports = {}, {}\n\n for sub_vars, sub_data in self.iter_data(\"hue\", from_comp_data=True):\n\n # Extract the data points from this sub set and remove nulls\n observations = sub_data[[\"x\", \"y\"]]\n\n # Extract the weights for this subset of observations\n if \"weights\" in self.variables:\n weights = sub_data[\"weights\"]\n else:\n weights = None\n\n # Check that KDE will not error out\n variance = observations[[\"x\", \"y\"]].var()\n if any(math.isclose(x, 0) for x in variance) or variance.isna().any():\n msg = (\n \"Dataset has 0 variance; skipping density estimate. \"\n \"Pass `warn_singular=False` to disable this warning.\"\n )\n if warn_singular:\n warnings.warn(msg, UserWarning)\n continue\n\n # Estimate the density of observations at this level\n observations = observations[\"x\"], observations[\"y\"]\n density, support = estimator(*observations, weights=weights)\n\n # Transform the support grid back to the original scale\n xx, yy = support\n if self._log_scaled(\"x\"):\n xx = np.power(10, xx)\n if self._log_scaled(\"y\"):\n yy = np.power(10, yy)\n support = xx, yy\n\n # Apply a scaling factor so that the integral over all subsets is 1\n if common_norm:\n density *= len(sub_data) / len(all_data)\n\n key = tuple(sub_vars.items())\n densities[key] = density\n supports[key] = support\n\n # Define a grid of iso-proportion levels\n if thresh is None:\n thresh = 0\n if isinstance(levels, Number):\n levels = np.linspace(thresh, 1, levels)\n else:\n if min(levels) < 0 or max(levels) > 1:\n raise ValueError(\"levels must be in [0, 1]\")\n\n # Transform from iso-proportions to iso-densities\n if common_norm:\n common_levels = self._quantile_to_level(\n list(densities.values()), levels,\n )\n draw_levels = {k: common_levels for k in densities}\n else:\n draw_levels = {\n k: self._quantile_to_level(d, levels)\n for k, d in densities.items()\n }\n\n # Get a default single color from the attribute cycle\n if self.ax is None:\n default_color = \"C0\" if color is None else color\n else:\n scout, = self.ax.plot([], color=color)\n default_color = scout.get_color()\n scout.remove()\n\n # Define the coloring of the contours\n if \"hue\" in self.variables:\n for param in [\"cmap\", \"colors\"]:\n if param in contour_kws:\n msg = f\"{param} parameter ignored when using hue mapping.\"\n warnings.warn(msg, UserWarning)\n contour_kws.pop(param)\n else:\n\n # Work out a default coloring of the contours\n coloring_given = set(contour_kws) & {\"cmap\", \"colors\"}\n if fill and not coloring_given:\n cmap = self._cmap_from_color(default_color)\n contour_kws[\"cmap\"] = cmap\n if not fill and not coloring_given:\n contour_kws[\"colors\"] = [default_color]\n\n # Use our internal colormap lookup\n cmap = contour_kws.pop(\"cmap\", None)\n if isinstance(cmap, str):\n cmap = color_palette(cmap, as_cmap=True)\n if cmap is not None:\n contour_kws[\"cmap\"] = cmap\n\n # Loop through the subsets again and plot the data\n for sub_vars, _ in self.iter_data(\"hue\"):\n\n if \"hue\" in sub_vars:\n color = self._hue_map(sub_vars[\"hue\"])\n if fill:\n contour_kws[\"cmap\"] = self._cmap_from_color(color)\n else:\n contour_kws[\"colors\"] = [color]\n\n ax = self._get_axes(sub_vars)\n\n # Choose the function to plot with\n # TODO could add a pcolormesh based option as well\n # Which would look something like element=\"raster\"\n if fill:\n contour_func = ax.contourf\n else:\n contour_func = ax.contour\n\n key = tuple(sub_vars.items())\n if key not in densities:\n continue\n density = densities[key]\n xx, yy = supports[key]\n\n label = contour_kws.pop(\"label\", None)\n\n cset = contour_func(\n xx, yy, density,\n levels=draw_levels[key],\n **contour_kws,\n )\n\n if \"hue\" not in self.variables:\n cset.collections[0].set_label(label)\n\n # Add a color bar representing the contour heights\n # Note: this shows iso densities, not iso proportions\n # See more notes in histplot about how this could be improved\n if cbar:\n cbar_kws = {} if cbar_kws is None else cbar_kws\n ax.figure.colorbar(cset, cbar_ax, ax, **cbar_kws)\n\n # --- Finalize the plot\n ax = self.ax if self.ax is not None else self.facets.axes.flat[0]\n self._add_axis_labels(ax)\n\n if \"hue\" in self.variables and legend:\n\n # TODO if possible, I would like to move the contour\n # intensity information into the legend too and label the\n # iso proportions rather than the raw density values\n\n artist_kws = {}\n if fill:\n artist = partial(mpl.patches.Patch)\n else:\n artist = partial(mpl.lines.Line2D, [], [])\n\n ax_obj = self.ax if self.ax is not None else self.facets\n self._add_legend(\n ax_obj, artist, fill, False, \"layer\", 1, artist_kws, {},\n )\n\n def plot_univariate_ecdf(self, estimate_kws, legend, **plot_kws):\n\n estimator = ECDF(**estimate_kws)\n\n # Set the draw style to step the right way for the data variable\n drawstyles = dict(x=\"steps-post\", y=\"steps-pre\")\n plot_kws[\"drawstyle\"] = drawstyles[self.data_variable]\n\n # Loop through the subsets, transform and plot the data\n for sub_vars, sub_data in self.iter_data(\n \"hue\", reverse=True, from_comp_data=True,\n ):\n\n # Compute the ECDF\n if sub_data.empty:\n continue\n\n observations = sub_data[self.data_variable]\n weights = sub_data.get(\"weights\", None)\n stat, vals = estimator(observations, weights=weights)\n\n # Assign attributes based on semantic mapping\n artist_kws = plot_kws.copy()\n if \"hue\" in self.variables:\n artist_kws[\"color\"] = self._hue_map(sub_vars[\"hue\"])\n\n # Return the data variable to the linear domain\n # This needs an automatic solution; see GH2409\n if self._log_scaled(self.data_variable):\n vals = np.power(10, vals)\n vals[0] = -np.inf\n\n # Work out the orientation of the plot\n if self.data_variable == \"x\":\n plot_args = vals, stat\n stat_variable = \"y\"\n else:\n plot_args = stat, vals\n stat_variable = \"x\"\n\n if estimator.stat == \"count\":\n top_edge = len(observations)\n else:\n top_edge = 1\n\n # Draw the line for this subset\n ax = self._get_axes(sub_vars)\n artist, = ax.plot(*plot_args, **artist_kws)\n sticky_edges = getattr(artist.sticky_edges, stat_variable)\n sticky_edges[:] = 0, top_edge\n\n # --- Finalize the plot ----\n ax = self.ax if self.ax is not None else self.facets.axes.flat[0]\n stat = estimator.stat.capitalize()\n default_x = default_y = \"\"\n if self.data_variable == \"x\":\n default_y = stat\n if self.data_variable == \"y\":\n default_x = stat\n self._add_axis_labels(ax, default_x, default_y)\n\n if \"hue\" in self.variables and legend:\n artist = partial(mpl.lines.Line2D, [], [])\n alpha = plot_kws.get(\"alpha\", 1)\n ax_obj = self.ax if self.ax is not None else self.facets\n self._add_legend(\n ax_obj, artist, False, False, None, alpha, plot_kws, {},\n )\n\n def plot_rug(self, height, expand_margins, legend, **kws):\n\n for sub_vars, sub_data, in self.iter_data(from_comp_data=True):\n\n ax = self._get_axes(sub_vars)\n\n kws.setdefault(\"linewidth\", 1)\n\n if expand_margins:\n xmarg, ymarg = ax.margins()\n if \"x\" in self.variables:\n ymarg += height * 2\n if \"y\" in self.variables:\n xmarg += height * 2\n ax.margins(x=xmarg, y=ymarg)\n\n if \"hue\" in self.variables:\n kws.pop(\"c\", None)\n kws.pop(\"color\", None)\n\n if \"x\" in self.variables:\n self._plot_single_rug(sub_data, \"x\", height, ax, kws)\n if \"y\" in self.variables:\n self._plot_single_rug(sub_data, \"y\", height, ax, kws)\n\n # --- Finalize the plot\n self._add_axis_labels(ax)\n if \"hue\" in self.variables and legend:\n # TODO ideally i'd like the legend artist to look like a rug\n legend_artist = partial(mpl.lines.Line2D, [], [])\n self._add_legend(\n ax, legend_artist, False, False, None, 1, {}, {},\n )\n\n def _plot_single_rug(self, sub_data, var, height, ax, kws):\n \"\"\"Draw a rugplot along one axis of the plot.\"\"\"\n vector = sub_data[var]\n n = len(vector)\n\n # Return data to linear domain\n # This needs an automatic solution; see GH2409\n if self._log_scaled(var):\n vector = np.power(10, vector)\n\n # We'll always add a single collection with varying colors\n if \"hue\" in self.variables:\n colors = self._hue_map(sub_data[\"hue\"])\n else:\n colors = None\n\n # Build the array of values for the LineCollection\n if var == \"x\":\n\n trans = tx.blended_transform_factory(ax.transData, ax.transAxes)\n xy_pairs = np.column_stack([\n np.repeat(vector, 2), np.tile([0, height], n)\n ])\n\n if var == \"y\":\n\n trans = tx.blended_transform_factory(ax.transAxes, ax.transData)\n xy_pairs = np.column_stack([\n np.tile([0, height], n), np.repeat(vector, 2)\n ])\n\n # Draw the lines on the plot\n line_segs = xy_pairs.reshape([n, 2, 2])\n ax.add_collection(LineCollection(\n line_segs, transform=trans, colors=colors, **kws\n ))\n\n ax.autoscale_view(scalex=var == \"x\", scaley=var == \"y\")\n\n\nclass _DistributionFacetPlotter(_DistributionPlotter):\n\n semantics = _DistributionPlotter.semantics + (\"col\", \"row\")\n\n\n# ==================================================================================== #\n# External API\n# ==================================================================================== #\n\ndef histplot(\n data=None, *,\n # Vector variables\n x=None, y=None, hue=None, weights=None,\n # Histogram computation parameters\n stat=\"count\", bins=\"auto\", binwidth=None, binrange=None,\n discrete=None, cumulative=False, common_bins=True, common_norm=True,\n # Histogram appearance parameters\n multiple=\"layer\", element=\"bars\", fill=True, shrink=1,\n # Histogram smoothing with a kernel density estimate\n kde=False, kde_kws=None, line_kws=None,\n # Bivariate histogram parameters\n thresh=0, pthresh=None, pmax=None, cbar=False, cbar_ax=None, cbar_kws=None,\n # Hue mapping parameters\n palette=None, hue_order=None, hue_norm=None, color=None,\n # Axes information\n log_scale=None, legend=True, ax=None,\n # Other appearance keywords\n **kwargs,\n):\n\n p = _DistributionPlotter(\n data=data,\n variables=_DistributionPlotter.get_semantics(locals())\n )\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n\n if ax is None:\n ax = plt.gca()\n\n p._attach(ax, log_scale=log_scale)\n\n if p.univariate: # Note, bivariate plots won't cycle\n if fill:\n method = ax.bar if element == \"bars\" else ax.fill_between\n else:\n method = ax.plot\n color = _default_color(method, hue, color, kwargs)\n\n if not p.has_xy_data:\n return ax\n\n # Default to discrete bins for categorical variables\n if discrete is None:\n discrete = p._default_discrete()\n\n estimate_kws = dict(\n stat=stat,\n bins=bins,\n binwidth=binwidth,\n binrange=binrange,\n discrete=discrete,\n cumulative=cumulative,\n )\n\n if p.univariate:\n\n p.plot_univariate_histogram(\n multiple=multiple,\n element=element,\n fill=fill,\n shrink=shrink,\n common_norm=common_norm,\n common_bins=common_bins,\n kde=kde,\n kde_kws=kde_kws,\n color=color,\n legend=legend,\n estimate_kws=estimate_kws,\n line_kws=line_kws,\n **kwargs,\n )\n\n else:\n\n p.plot_bivariate_histogram(\n common_bins=common_bins,\n common_norm=common_norm,\n thresh=thresh,\n pthresh=pthresh,\n pmax=pmax,\n color=color,\n legend=legend,\n cbar=cbar,\n cbar_ax=cbar_ax,\n cbar_kws=cbar_kws,\n estimate_kws=estimate_kws,\n **kwargs,\n )\n\n return ax\n\n\nhistplot.__doc__ = \"\"\"\\\nPlot univariate or bivariate histograms to show distributions of datasets.\n\nA histogram is a classic visualization tool that represents the distribution\nof one or more variables by counting the number of observations that fall within\ndiscrete bins.\n\nThis function can normalize the statistic computed within each bin to estimate\nfrequency, density or probability mass, and it can add a smooth curve obtained\nusing a kernel density estimate, similar to :func:`kdeplot`.\n\nMore information is provided in the :ref:`user guide <tutorial_hist>`.\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\n{params.core.hue}\nweights : vector or key in ``data``\n If provided, weight the contribution of the corresponding data points\n towards the count in each bin by these factors.\n{params.hist.stat}\n{params.hist.bins}\n{params.hist.binwidth}\n{params.hist.binrange}\ndiscrete : bool\n If True, default to ``binwidth=1`` and draw the bars so that they are\n centered on their corresponding data points. This avoids \"gaps\" that may\n otherwise appear when using discrete (integer) data.\ncumulative : bool\n If True, plot the cumulative counts as bins increase.\ncommon_bins : bool\n If True, use the same bins when semantic variables produce multiple\n plots. If using a reference rule to determine the bins, it will be computed\n with the full dataset.\ncommon_norm : bool\n If True and using a normalized statistic, the normalization will apply over\n the full dataset. Otherwise, normalize each histogram independently.\nmultiple : {{\"layer\", \"dodge\", \"stack\", \"fill\"}}\n Approach to resolving multiple elements when semantic mapping creates subsets.\n Only relevant with univariate data.\nelement : {{\"bars\", \"step\", \"poly\"}}\n Visual representation of the histogram statistic.\n Only relevant with univariate data.\nfill : bool\n If True, fill in the space under the histogram.\n Only relevant with univariate data.\nshrink : number\n Scale the width of each bar relative to the binwidth by this factor.\n Only relevant with univariate data.\nkde : bool\n If True, compute a kernel density estimate to smooth the distribution\n and show on the plot as (one or more) line(s).\n Only relevant with univariate data.\nkde_kws : dict\n Parameters that control the KDE computation, as in :func:`kdeplot`.\nline_kws : dict\n Parameters that control the KDE visualization, passed to\n :meth:`matplotlib.axes.Axes.plot`.\nthresh : number or None\n Cells with a statistic less than or equal to this value will be transparent.\n Only relevant with bivariate data.\npthresh : number or None\n Like ``thresh``, but a value in [0, 1] such that cells with aggregate counts\n (or other statistics, when used) up to this proportion of the total will be\n transparent.\npmax : number or None\n A value in [0, 1] that sets that saturation point for the colormap at a value\n such that cells below is constistute this proportion of the total count (or\n other statistic, when used).\n{params.dist.cbar}\n{params.dist.cbar_ax}\n{params.dist.cbar_kws}\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n{params.core.color}\n{params.dist.log_scale}\n{params.dist.legend}\n{params.core.ax}\nkwargs\n Other keyword arguments are passed to one of the following matplotlib\n functions:\n\n - :meth:`matplotlib.axes.Axes.bar` (univariate, element=\"bars\")\n - :meth:`matplotlib.axes.Axes.fill_between` (univariate, other element, fill=True)\n - :meth:`matplotlib.axes.Axes.plot` (univariate, other element, fill=False)\n - :meth:`matplotlib.axes.Axes.pcolormesh` (bivariate)\n\nReturns\n-------\n{returns.ax}\n\nSee Also\n--------\n{seealso.displot}\n{seealso.kdeplot}\n{seealso.rugplot}\n{seealso.ecdfplot}\n{seealso.jointplot}\n\nNotes\n-----\n\nThe choice of bins for computing and plotting a histogram can exert\nsubstantial influence on the insights that one is able to draw from the\nvisualization. If the bins are too large, they may erase important features.\nOn the other hand, bins that are too small may be dominated by random\nvariability, obscuring the shape of the true underlying distribution. The\ndefault bin size is determined using a reference rule that depends on the\nsample size and variance. This works well in many cases, (i.e., with\n\"well-behaved\" data) but it fails in others. It is always a good to try\ndifferent bin sizes to be sure that you are not missing something important.\nThis function allows you to specify bins in several different ways, such as\nby setting the total number of bins to use, the width of each bin, or the\nspecific locations where the bins should break.\n\nExamples\n--------\n\n.. include:: ../docstrings/histplot.rst\n\n\"\"\".format(\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\n\n@_deprecate_positional_args\ndef kdeplot(\n x=None, # Allow positional x, because behavior will not change with reorg\n *,\n y=None,\n shade=None, # Note \"soft\" deprecation, explained below\n vertical=False, # Deprecated\n kernel=None, # Deprecated\n bw=None, # Deprecated\n gridsize=200, # TODO maybe depend on uni/bivariate?\n cut=3, clip=None, legend=True, cumulative=False,\n shade_lowest=None, # Deprecated, controlled with levels now\n cbar=False, cbar_ax=None, cbar_kws=None,\n ax=None,\n\n # New params\n weights=None, # TODO note that weights is grouped with semantics\n hue=None, palette=None, hue_order=None, hue_norm=None,\n multiple=\"layer\", common_norm=True, common_grid=False,\n levels=10, thresh=.05,\n bw_method=\"scott\", bw_adjust=1, log_scale=None,\n color=None, fill=None,\n\n # Renamed params\n data=None, data2=None,\n\n # New in v0.12\n warn_singular=True,\n\n **kwargs,\n):\n\n # Handle deprecation of `data2` as name for y variable\n if data2 is not None:\n\n y = data2\n\n # If `data2` is present, we need to check for the `data` kwarg being\n # used to pass a vector for `x`. We'll reassign the vectors and warn.\n # We need this check because just passing a vector to `data` is now\n # technically valid.\n\n x_passed_as_data = (\n x is None\n and data is not None\n and np.ndim(data) == 1\n )\n\n if x_passed_as_data:\n msg = \"Use `x` and `y` rather than `data` `and `data2`\"\n x = data\n else:\n msg = \"The `data2` param is now named `y`; please update your code\"\n\n warnings.warn(msg, FutureWarning)\n\n # Handle deprecation of `vertical`\n if vertical:\n msg = (\n \"The `vertical` parameter is deprecated and will be removed in a \"\n \"future version. Assign the data to the `y` variable instead.\"\n )\n warnings.warn(msg, FutureWarning)\n x, y = y, x\n\n # Handle deprecation of `bw`\n if bw is not None:\n msg = (\n \"The `bw` parameter is deprecated in favor of `bw_method` and \"\n f\"`bw_adjust`. Using {bw} for `bw_method`, but please \"\n \"see the docs for the new parameters and update your code.\"\n )\n warnings.warn(msg, FutureWarning)\n bw_method = bw\n\n # Handle deprecation of `kernel`\n if kernel is not None:\n msg = (\n \"Support for alternate kernels has been removed. \"\n \"Using Gaussian kernel.\"\n )\n warnings.warn(msg, UserWarning)\n\n # Handle deprecation of shade_lowest\n if shade_lowest is not None:\n if shade_lowest:\n thresh = 0\n msg = (\n \"`shade_lowest` is now deprecated in favor of `thresh`. \"\n f\"Setting `thresh={thresh}`, but please update your code.\"\n )\n warnings.warn(msg, UserWarning)\n\n # Handle `n_levels`\n # This was never in the formal API but it was processed, and appeared in an\n # example. We can treat as an alias for `levels` now and deprecate later.\n levels = kwargs.pop(\"n_levels\", levels)\n\n # Handle \"soft\" deprecation of shade `shade` is not really the right\n # terminology here, but unlike some of the other deprecated parameters it\n # is probably very commonly used and much hard to remove. This is therefore\n # going to be a longer process where, first, `fill` will be introduced and\n # be used throughout the documentation. In 0.12, when kwarg-only\n # enforcement hits, we can remove the shade/shade_lowest out of the\n # function signature all together and pull them out of the kwargs. Then we\n # can actually fire a FutureWarning, and eventually remove.\n if shade is not None:\n fill = shade\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #\n\n p = _DistributionPlotter(\n data=data,\n variables=_DistributionPlotter.get_semantics(locals()),\n )\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n\n if ax is None:\n ax = plt.gca()\n\n p._attach(ax, allowed_types=[\"numeric\", \"datetime\"], log_scale=log_scale)\n\n method = ax.fill_between if fill else ax.plot\n color = _default_color(method, hue, color, kwargs)\n\n if not p.has_xy_data:\n return ax\n\n # Pack the kwargs for statistics.KDE\n estimate_kws = dict(\n bw_method=bw_method,\n bw_adjust=bw_adjust,\n gridsize=gridsize,\n cut=cut,\n clip=clip,\n cumulative=cumulative,\n )\n\n if p.univariate:\n\n plot_kws = kwargs.copy()\n\n p.plot_univariate_density(\n multiple=multiple,\n common_norm=common_norm,\n common_grid=common_grid,\n fill=fill,\n color=color,\n legend=legend,\n warn_singular=warn_singular,\n estimate_kws=estimate_kws,\n **plot_kws,\n )\n\n else:\n\n p.plot_bivariate_density(\n common_norm=common_norm,\n fill=fill,\n levels=levels,\n thresh=thresh,\n legend=legend,\n color=color,\n warn_singular=warn_singular,\n cbar=cbar,\n cbar_ax=cbar_ax,\n cbar_kws=cbar_kws,\n estimate_kws=estimate_kws,\n **kwargs,\n )\n\n return ax\n\n\nkdeplot.__doc__ = \"\"\"\\\nPlot univariate or bivariate distributions using kernel density estimation.\n\nA kernel density estimate (KDE) plot is a method for visualizing the\ndistribution of observations in a dataset, analogous to a histogram. KDE\nrepresents the data using a continuous probability density curve in one or\nmore dimensions.\n\nThe approach is explained further in the :ref:`user guide <tutorial_kde>`.\n\nRelative to a histogram, KDE can produce a plot that is less cluttered and\nmore interpretable, especially when drawing multiple distributions. But it\nhas the potential to introduce distortions if the underlying distribution is\nbounded or not smooth. Like a histogram, the quality of the representation\nalso depends on the selection of good smoothing parameters.\n\nParameters\n----------\n{params.core.xy}\nshade : bool\n Alias for ``fill``. Using ``fill`` is recommended.\nvertical : bool\n Orientation parameter.\n\n .. deprecated:: 0.11.0\n specify orientation by assigning the ``x`` or ``y`` variables.\n\nkernel : str\n Function that defines the kernel.\n\n .. deprecated:: 0.11.0\n support for non-Gaussian kernels has been removed.\n\nbw : str, number, or callable\n Smoothing parameter.\n\n .. deprecated:: 0.11.0\n see ``bw_method`` and ``bw_adjust``.\n\ngridsize : int\n Number of points on each dimension of the evaluation grid.\n{params.kde.cut}\n{params.kde.clip}\n{params.dist.legend}\n{params.kde.cumulative}\nshade_lowest : bool\n If False, the area below the lowest contour will be transparent\n\n .. deprecated:: 0.11.0\n see ``thresh``.\n\n{params.dist.cbar}\n{params.dist.cbar_ax}\n{params.dist.cbar_kws}\n{params.core.ax}\nweights : vector or key in ``data``\n If provided, weight the kernel density estimation using these values.\n{params.core.hue}\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n{params.dist.multiple}\ncommon_norm : bool\n If True, scale each conditional density by the number of observations\n such that the total area under all densities sums to 1. Otherwise,\n normalize each density independently.\ncommon_grid : bool\n If True, use the same evaluation grid for each kernel density estimate.\n Only relevant with univariate data.\nlevels : int or vector\n Number of contour levels or values to draw contours at. A vector argument\n must have increasing values in [0, 1]. Levels correspond to iso-proportions\n of the density: e.g., 20% of the probability mass will lie below the\n contour drawn for 0.2. Only relevant with bivariate data.\nthresh : number in [0, 1]\n Lowest iso-proportion level at which to draw a contour line. Ignored when\n ``levels`` is a vector. Only relevant with bivariate data.\n{params.kde.bw_method}\n{params.kde.bw_adjust}\n{params.dist.log_scale}\n{params.core.color}\nfill : bool or None\n If True, fill in the area under univariate density curves or between\n bivariate contours. If None, the default depends on ``multiple``.\n{params.core.data}\nwarn_singular : bool\n If True, issue a warning when trying to estimate the density of data\n with zero variance.\nkwargs\n Other keyword arguments are passed to one of the following matplotlib\n functions:\n\n - :meth:`matplotlib.axes.Axes.plot` (univariate, ``fill=False``),\n - :meth:`matplotlib.axes.Axes.fill_between` (univariate, ``fill=True``),\n - :meth:`matplotlib.axes.Axes.contour` (bivariate, ``fill=False``),\n - :meth:`matplotlib.axes.contourf` (bivariate, ``fill=True``).\n\nReturns\n-------\n{returns.ax}\n\nSee Also\n--------\n{seealso.displot}\n{seealso.histplot}\n{seealso.ecdfplot}\n{seealso.jointplot}\n{seealso.violinplot}\n\nNotes\n-----\n\nThe *bandwidth*, or standard deviation of the smoothing kernel, is an\nimportant parameter. Misspecification of the bandwidth can produce a\ndistorted representation of the data. Much like the choice of bin width in a\nhistogram, an over-smoothed curve can erase true features of a\ndistribution, while an under-smoothed curve can create false features out of\nrandom variability. The rule-of-thumb that sets the default bandwidth works\nbest when the true distribution is smooth, unimodal, and roughly bell-shaped.\nIt is always a good idea to check the default behavior by using ``bw_adjust``\nto increase or decrease the amount of smoothing.\n\nBecause the smoothing algorithm uses a Gaussian kernel, the estimated density\ncurve can extend to values that do not make sense for a particular dataset.\nFor example, the curve may be drawn over negative values when smoothing data\nthat are naturally positive. The ``cut`` and ``clip`` parameters can be used\nto control the extent of the curve, but datasets that have many observations\nclose to a natural boundary may be better served by a different visualization\nmethod.\n\nSimilar considerations apply when a dataset is naturally discrete or \"spiky\"\n(containing many repeated observations of the same value). Kernel density\nestimation will always produce a smooth curve, which would be misleading\nin these situations.\n\nThe units on the density axis are a common source of confusion. While kernel\ndensity estimation produces a probability distribution, the height of the curve\nat each point gives a density, not a probability. A probability can be obtained\nonly by integrating the density across a range. The curve is normalized so\nthat the integral over all possible values is 1, meaning that the scale of\nthe density axis depends on the data values.\n\nExamples\n--------\n\n.. include:: ../docstrings/kdeplot.rst\n\n\"\"\".format(\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\n\ndef ecdfplot(\n data=None, *,\n # Vector variables\n x=None, y=None, hue=None, weights=None,\n # Computation parameters\n stat=\"proportion\", complementary=False,\n # Hue mapping parameters\n palette=None, hue_order=None, hue_norm=None,\n # Axes information\n log_scale=None, legend=True, ax=None,\n # Other appearance keywords\n **kwargs,\n):\n\n p = _DistributionPlotter(\n data=data,\n variables=_DistributionPlotter.get_semantics(locals())\n )\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n\n # We could support other semantics (size, style) here fairly easily\n # But it would make distplot a bit more complicated.\n # It's always possible to add features like that later, so I am going to defer.\n # It will be even easier to wait until after there is a more general/abstract\n # way to go from semantic specs to artist attributes.\n\n if ax is None:\n ax = plt.gca()\n\n p._attach(ax, log_scale=log_scale)\n\n color = kwargs.pop(\"color\", kwargs.pop(\"c\", None))\n kwargs[\"color\"] = _default_color(ax.plot, hue, color, kwargs)\n\n if not p.has_xy_data:\n return ax\n\n # We could add this one day, but it's of dubious value\n if not p.univariate:\n raise NotImplementedError(\"Bivariate ECDF plots are not implemented\")\n\n estimate_kws = dict(\n stat=stat,\n complementary=complementary,\n )\n\n p.plot_univariate_ecdf(\n estimate_kws=estimate_kws,\n legend=legend,\n **kwargs,\n )\n\n return ax\n\n\necdfplot.__doc__ = \"\"\"\\\nPlot empirical cumulative distribution functions.\n\nAn ECDF represents the proportion or count of observations falling below each\nunique value in a dataset. Compared to a histogram or density plot, it has the\nadvantage that each observation is visualized directly, meaning that there are\nno binning or smoothing parameters that need to be adjusted. It also aids direct\ncomparisons between multiple distributions. A downside is that the relationship\nbetween the appearance of the plot and the basic properties of the distribution\n(such as its central tendency, variance, and the presence of any bimodality)\nmay not be as intuitive.\n\nMore information is provided in the :ref:`user guide <tutorial_ecdf>`.\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\n{params.core.hue}\nweights : vector or key in ``data``\n If provided, weight the contribution of the corresponding data points\n towards the cumulative distribution using these values.\n{params.ecdf.stat}\n{params.ecdf.complementary}\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n{params.dist.log_scale}\n{params.dist.legend}\n{params.core.ax}\nkwargs\n Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.plot`.\n\nReturns\n-------\n{returns.ax}\n\nSee Also\n--------\n{seealso.displot}\n{seealso.histplot}\n{seealso.kdeplot}\n{seealso.rugplot}\n\nExamples\n--------\n\n.. include:: ../docstrings/ecdfplot.rst\n\n\"\"\".format(\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\n\n@_deprecate_positional_args\ndef rugplot(\n x=None, # Allow positional x, because behavior won't change\n *,\n height=.025, axis=None, ax=None,\n\n # New parameters\n data=None, y=None, hue=None,\n palette=None, hue_order=None, hue_norm=None,\n expand_margins=True,\n legend=True, # TODO or maybe default to False?\n\n # Renamed parameter\n a=None,\n\n **kwargs\n):\n\n # A note: I think it would make sense to add multiple= to rugplot and allow\n # rugs for different hue variables to be shifted orthogonal to the data axis\n # But is this stacking, or dodging?\n\n # A note: if we want to add a style semantic to rugplot,\n # we could make an option that draws the rug using scatterplot\n\n # A note, it would also be nice to offer some kind of histogram/density\n # rugplot, since alpha blending doesn't work great in the large n regime\n\n # Handle deprecation of `a``\n if a is not None:\n msg = \"The `a` parameter is now called `x`. Please update your code.\"\n warnings.warn(msg, FutureWarning)\n x = a\n del a\n\n # Handle deprecation of \"axis\"\n if axis is not None:\n msg = (\n \"The `axis` variable is no longer used and will be removed. \"\n \"Instead, assign variables directly to `x` or `y`.\"\n )\n warnings.warn(msg, FutureWarning)\n\n # Handle deprecation of \"vertical\"\n if kwargs.pop(\"vertical\", axis == \"y\"):\n x, y = None, x\n msg = (\n \"Using `vertical=True` to control the orientation of the plot \"\n \"is deprecated. Instead, assign the data directly to `y`. \"\n )\n warnings.warn(msg, FutureWarning)\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #\n\n weights = None\n p = _DistributionPlotter(\n data=data,\n variables=_DistributionPlotter.get_semantics(locals()),\n )\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n\n if ax is None:\n ax = plt.gca()\n\n p._attach(ax)\n\n color = kwargs.pop(\"color\", kwargs.pop(\"c\", None))\n kwargs[\"color\"] = _default_color(ax.plot, hue, color, kwargs)\n\n if not p.has_xy_data:\n return ax\n\n p.plot_rug(height, expand_margins, legend, **kwargs)\n\n return ax\n\n\nrugplot.__doc__ = \"\"\"\\\nPlot marginal distributions by drawing ticks along the x and y axes.\n\nThis function is intended to complement other plots by showing the location\nof individual observations in an unobtrusive way.\n\nParameters\n----------\n{params.core.xy}\nheight : number\n Proportion of axes extent covered by each rug element.\naxis : {{\"x\", \"y\"}}\n Axis to draw the rug on.\n\n .. deprecated:: 0.11.0\n specify axis by assigning the ``x`` or ``y`` variables.\n\n{params.core.ax}\n{params.core.data}\n{params.core.hue}\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\nexpand_margins : bool\n If True, increase the axes margins by the height of the rug to avoid\n overlap with other elements.\nlegend : bool\n If False, do not add a legend for semantic variables.\nkwargs\n Other keyword arguments are passed to\n :meth:`matplotlib.collections.LineCollection`\n\nReturns\n-------\n{returns.ax}\n\nExamples\n--------\n\n.. include:: ../docstrings/rugplot.rst\n\n\"\"\".format(\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\n\ndef displot(\n data=None, *,\n # Vector variables\n x=None, y=None, hue=None, row=None, col=None, weights=None,\n # Other plot parameters\n kind=\"hist\", rug=False, rug_kws=None, log_scale=None, legend=True,\n # Hue-mapping parameters\n palette=None, hue_order=None, hue_norm=None, color=None,\n # Faceting parameters\n col_wrap=None, row_order=None, col_order=None,\n height=5, aspect=1, facet_kws=None,\n **kwargs,\n):\n\n p = _DistributionFacetPlotter(\n data=data,\n variables=_DistributionFacetPlotter.get_semantics(locals())\n )\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n\n _check_argument(\"kind\", [\"hist\", \"kde\", \"ecdf\"], kind)\n\n # --- Initialize the FacetGrid object\n\n # Check for attempt to plot onto specific axes and warn\n if \"ax\" in kwargs:\n msg = (\n \"`displot` is a figure-level function and does not accept \"\n \"the ax= parameter. You may wish to try {}plot.\".format(kind)\n )\n warnings.warn(msg, UserWarning)\n kwargs.pop(\"ax\")\n\n for var in [\"row\", \"col\"]:\n # Handle faceting variables that lack name information\n if var in p.variables and p.variables[var] is None:\n p.variables[var] = f\"_{var}_\"\n\n # Adapt the plot_data dataframe for use with FacetGrid\n grid_data = p.plot_data.rename(columns=p.variables)\n grid_data = grid_data.loc[:, ~grid_data.columns.duplicated()]\n\n col_name = p.variables.get(\"col\", None)\n row_name = p.variables.get(\"row\", None)\n\n if facet_kws is None:\n facet_kws = {}\n\n g = FacetGrid(\n data=grid_data, row=row_name, col=col_name,\n col_wrap=col_wrap, row_order=row_order,\n col_order=col_order, height=height,\n aspect=aspect,\n **facet_kws,\n )\n\n # Now attach the axes object to the plotter object\n if kind == \"kde\":\n allowed_types = [\"numeric\", \"datetime\"]\n else:\n allowed_types = None\n p._attach(g, allowed_types=allowed_types, log_scale=log_scale)\n\n # Check for a specification that lacks x/y data and return early\n if not p.has_xy_data:\n return g\n\n if color is None and hue is None:\n color = \"C0\"\n # XXX else warn if hue is not None?\n\n kwargs[\"legend\"] = legend\n\n # --- Draw the plots\n\n if kind == \"hist\":\n\n hist_kws = kwargs.copy()\n\n # Extract the parameters that will go directly to Histogram\n estimate_defaults = {}\n _assign_default_kwargs(estimate_defaults, Histogram.__init__, histplot)\n\n estimate_kws = {}\n for key, default_val in estimate_defaults.items():\n estimate_kws[key] = hist_kws.pop(key, default_val)\n\n # Handle derivative defaults\n if estimate_kws[\"discrete\"] is None:\n estimate_kws[\"discrete\"] = p._default_discrete()\n\n hist_kws[\"estimate_kws\"] = estimate_kws\n\n hist_kws.setdefault(\"color\", color)\n\n if p.univariate:\n\n _assign_default_kwargs(hist_kws, p.plot_univariate_histogram, histplot)\n p.plot_univariate_histogram(**hist_kws)\n\n else:\n\n _assign_default_kwargs(hist_kws, p.plot_bivariate_histogram, histplot)\n p.plot_bivariate_histogram(**hist_kws)\n\n elif kind == \"kde\":\n\n kde_kws = kwargs.copy()\n\n # Extract the parameters that will go directly to KDE\n estimate_defaults = {}\n _assign_default_kwargs(estimate_defaults, KDE.__init__, kdeplot)\n\n estimate_kws = {}\n for key, default_val in estimate_defaults.items():\n estimate_kws[key] = kde_kws.pop(key, default_val)\n\n kde_kws[\"estimate_kws\"] = estimate_kws\n kde_kws[\"color\"] = color\n\n if p.univariate:\n\n _assign_default_kwargs(kde_kws, p.plot_univariate_density, kdeplot)\n p.plot_univariate_density(**kde_kws)\n\n else:\n\n _assign_default_kwargs(kde_kws, p.plot_bivariate_density, kdeplot)\n p.plot_bivariate_density(**kde_kws)\n\n elif kind == \"ecdf\":\n\n ecdf_kws = kwargs.copy()\n\n # Extract the parameters that will go directly to the estimator\n estimate_kws = {}\n estimate_defaults = {}\n _assign_default_kwargs(estimate_defaults, ECDF.__init__, ecdfplot)\n for key, default_val in estimate_defaults.items():\n estimate_kws[key] = ecdf_kws.pop(key, default_val)\n\n ecdf_kws[\"estimate_kws\"] = estimate_kws\n ecdf_kws[\"color\"] = color\n\n if p.univariate:\n\n _assign_default_kwargs(ecdf_kws, p.plot_univariate_ecdf, ecdfplot)\n p.plot_univariate_ecdf(**ecdf_kws)\n\n else:\n\n raise NotImplementedError(\"Bivariate ECDF plots are not implemented\")\n\n # All plot kinds can include a rug\n if rug:\n # TODO with expand_margins=True, each facet expands margins... annoying!\n if rug_kws is None:\n rug_kws = {}\n _assign_default_kwargs(rug_kws, p.plot_rug, rugplot)\n rug_kws[\"legend\"] = False\n if color is not None:\n rug_kws[\"color\"] = color\n p.plot_rug(**rug_kws)\n\n # Call FacetGrid annotation methods\n # Note that the legend is currently set inside the plotting method\n g.set_axis_labels(\n x_var=p.variables.get(\"x\", g.axes.flat[0].get_xlabel()),\n y_var=p.variables.get(\"y\", g.axes.flat[0].get_ylabel()),\n )\n g.set_titles()\n g.tight_layout()\n\n if data is not None and (x is not None or y is not None):\n if not isinstance(data, pd.DataFrame):\n data = pd.DataFrame(data)\n g.data = pd.merge(\n data,\n g.data[g.data.columns.difference(data.columns)],\n left_index=True,\n right_index=True,\n )\n else:\n wide_cols = {\n k: f\"_{k}_\" if v is None else v for k, v in p.variables.items()\n }\n g.data = p.plot_data.rename(columns=wide_cols)\n\n return g\n\n\ndisplot.__doc__ = \"\"\"\\\nFigure-level interface for drawing distribution plots onto a FacetGrid.\n\nThis function provides access to several approaches for visualizing the\nunivariate or bivariate distribution of data, including subsets of data\ndefined by semantic mapping and faceting across multiple subplots. The\n``kind`` parameter selects the approach to use:\n\n- :func:`histplot` (with ``kind=\"hist\"``; the default)\n- :func:`kdeplot` (with ``kind=\"kde\"``)\n- :func:`ecdfplot` (with ``kind=\"ecdf\"``; univariate-only)\n\nAdditionally, a :func:`rugplot` can be added to any kind of plot to show\nindividual observations.\n\nExtra keyword arguments are passed to the underlying function, so you should\nrefer to the documentation for each to understand the complete set of options\nfor making plots with this interface.\n\nSee the :doc:`distribution plots tutorial <../tutorial/distributions>` for a more\nin-depth discussion of the relative strengths and weaknesses of each approach.\nThe distinction between figure-level and axes-level functions is explained\nfurther in the :doc:`user guide <../tutorial/function_overview>`.\n\nParameters\n----------\n{params.core.data}\n{params.core.xy}\n{params.core.hue}\n{params.facets.rowcol}\nkind : {{\"hist\", \"kde\", \"ecdf\"}}\n Approach for visualizing the data. Selects the underlying plotting function\n and determines the additional set of valid parameters.\nrug : bool\n If True, show each observation with marginal ticks (as in :func:`rugplot`).\nrug_kws : dict\n Parameters to control the appearance of the rug plot.\n{params.dist.log_scale}\n{params.dist.legend}\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n{params.core.color}\n{params.facets.col_wrap}\n{params.facets.rowcol_order}\n{params.facets.height}\n{params.facets.aspect}\n{params.facets.facet_kws}\nkwargs\n Other keyword arguments are documented with the relevant axes-level function:\n\n - :func:`histplot` (with ``kind=\"hist\"``)\n - :func:`kdeplot` (with ``kind=\"kde\"``)\n - :func:`ecdfplot` (with ``kind=\"ecdf\"``)\n\nReturns\n-------\n{returns.facetgrid}\n\nSee Also\n--------\n{seealso.histplot}\n{seealso.kdeplot}\n{seealso.rugplot}\n{seealso.ecdfplot}\n{seealso.jointplot}\n\nExamples\n--------\n\nSee the API documentation for the axes-level functions for more details\nabout the breadth of options available for each plot kind.\n\n.. include:: ../docstrings/displot.rst\n\n\"\"\".format(\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\n\n# =========================================================================== #\n# DEPRECATED FUNCTIONS LIVE BELOW HERE\n# =========================================================================== #\n\n\ndef _freedman_diaconis_bins(a):\n \"\"\"Calculate number of hist bins using Freedman-Diaconis rule.\"\"\"\n # From https://stats.stackexchange.com/questions/798/\n a = np.asarray(a)\n if len(a) < 2:\n return 1\n iqr = np.subtract.reduce(np.nanpercentile(a, [75, 25]))\n h = 2 * iqr / (len(a) ** (1 / 3))\n # fall back to sqrt(a) bins if iqr is 0\n if h == 0:\n return int(np.sqrt(a.size))\n else:\n return int(np.ceil((a.max() - a.min()) / h))\n\n\ndef distplot(a=None, bins=None, hist=True, kde=True, rug=False, fit=None,\n hist_kws=None, kde_kws=None, rug_kws=None, fit_kws=None,\n color=None, vertical=False, norm_hist=False, axlabel=None,\n label=None, ax=None, x=None):\n \"\"\"DEPRECATED: Flexibly plot a univariate distribution of observations.\n\n .. warning::\n This function is deprecated and will be removed in a future version.\n Please adapt your code to use one of two new functions:\n\n - :func:`displot`, a figure-level function with a similar flexibility\n over the kind of plot to draw\n - :func:`histplot`, an axes-level function for plotting histograms,\n including with kernel density smoothing\n\n This function combines the matplotlib ``hist`` function (with automatic\n calculation of a good default bin size) with the seaborn :func:`kdeplot`\n and :func:`rugplot` functions. It can also fit ``scipy.stats``\n distributions and plot the estimated PDF over the data.\n\n Parameters\n ----------\n a : Series, 1d-array, or list.\n Observed data. If this is a Series object with a ``name`` attribute,\n the name will be used to label the data axis.\n bins : argument for matplotlib hist(), or None, optional\n Specification of hist bins. If unspecified, as reference rule is used\n that tries to find a useful default.\n hist : bool, optional\n Whether to plot a (normed) histogram.\n kde : bool, optional\n Whether to plot a gaussian kernel density estimate.\n rug : bool, optional\n Whether to draw a rugplot on the support axis.\n fit : random variable object, optional\n An object with `fit` method, returning a tuple that can be passed to a\n `pdf` method a positional arguments following a grid of values to\n evaluate the pdf on.\n hist_kws : dict, optional\n Keyword arguments for :meth:`matplotlib.axes.Axes.hist`.\n kde_kws : dict, optional\n Keyword arguments for :func:`kdeplot`.\n rug_kws : dict, optional\n Keyword arguments for :func:`rugplot`.\n color : matplotlib color, optional\n Color to plot everything but the fitted curve in.\n vertical : bool, optional\n If True, observed values are on y-axis.\n norm_hist : bool, optional\n If True, the histogram height shows a density rather than a count.\n This is implied if a KDE or fitted density is plotted.\n axlabel : string, False, or None, optional\n Name for the support axis label. If None, will try to get it\n from a.name if False, do not set a label.\n label : string, optional\n Legend label for the relevant component of the plot.\n ax : matplotlib axis, optional\n If provided, plot on this axis.\n\n Returns\n -------\n ax : matplotlib Axes\n Returns the Axes object with the plot for further tweaking.\n\n See Also\n --------\n kdeplot : Show a univariate or bivariate distribution with a kernel\n density estimate.\n rugplot : Draw small vertical lines to show each observation in a\n distribution.\n\n Examples\n --------\n\n Show a default plot with a kernel density estimate and histogram with bin\n size determined automatically with a reference rule:\n\n .. plot::\n :context: close-figs\n\n >>> import seaborn as sns, numpy as np\n >>> sns.set_theme(); np.random.seed(0)\n >>> x = np.random.randn(100)\n >>> ax = sns.distplot(x)\n\n Use Pandas objects to get an informative axis label:\n\n .. plot::\n :context: close-figs\n\n >>> import pandas as pd\n >>> x = pd.Series(x, name=\"x variable\")\n >>> ax = sns.distplot(x)\n\n Plot the distribution with a kernel density estimate and rug plot:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.distplot(x, rug=True, hist=False)\n\n Plot the distribution with a histogram and maximum likelihood gaussian\n distribution fit:\n\n .. plot::\n :context: close-figs\n\n >>> from scipy.stats import norm\n >>> ax = sns.distplot(x, fit=norm, kde=False)\n\n Plot the distribution on the vertical axis:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.distplot(x, vertical=True)\n\n Change the color of all the plot elements:\n\n .. plot::\n :context: close-figs\n\n >>> sns.set_color_codes()\n >>> ax = sns.distplot(x, color=\"y\")\n\n Pass specific parameters to the underlying plot functions:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.distplot(x, rug=True, rug_kws={\"color\": \"g\"},\n ... kde_kws={\"color\": \"k\", \"lw\": 3, \"label\": \"KDE\"},\n ... hist_kws={\"histtype\": \"step\", \"linewidth\": 3,\n ... \"alpha\": 1, \"color\": \"g\"})\n\n \"\"\"\n\n if kde and not hist:\n axes_level_suggestion = (\n \"`kdeplot` (an axes-level function for kernel density plots).\"\n )\n else:\n axes_level_suggestion = (\n \"`histplot` (an axes-level function for histograms).\"\n )\n\n msg = (\n \"`distplot` is a deprecated function and will be removed in a future version. \"\n \"Please adapt your code to use either `displot` (a figure-level function with \"\n \"similar flexibility) or \" + axes_level_suggestion\n )\n warnings.warn(msg, FutureWarning)\n\n if ax is None:\n ax = plt.gca()\n\n # Intelligently label the support axis\n label_ax = bool(axlabel)\n if axlabel is None and hasattr(a, \"name\"):\n axlabel = a.name\n if axlabel is not None:\n label_ax = True\n\n # Support new-style API\n if x is not None:\n a = x\n\n # Make a a 1-d float array\n a = np.asarray(a, float)\n if a.ndim > 1:\n a = a.squeeze()\n\n # Drop null values from array\n a = remove_na(a)\n\n # Decide if the hist is normed\n norm_hist = norm_hist or kde or (fit is not None)\n\n # Handle dictionary defaults\n hist_kws = {} if hist_kws is None else hist_kws.copy()\n kde_kws = {} if kde_kws is None else kde_kws.copy()\n rug_kws = {} if rug_kws is None else rug_kws.copy()\n fit_kws = {} if fit_kws is None else fit_kws.copy()\n\n # Get the color from the current color cycle\n if color is None:\n if vertical:\n line, = ax.plot(0, a.mean())\n else:\n line, = ax.plot(a.mean(), 0)\n color = line.get_color()\n line.remove()\n\n # Plug the label into the right kwarg dictionary\n if label is not None:\n if hist:\n hist_kws[\"label\"] = label\n elif kde:\n kde_kws[\"label\"] = label\n elif rug:\n rug_kws[\"label\"] = label\n elif fit:\n fit_kws[\"label\"] = label\n\n if hist:\n if bins is None:\n bins = min(_freedman_diaconis_bins(a), 50)\n hist_kws.setdefault(\"alpha\", 0.4)\n hist_kws.setdefault(\"density\", norm_hist)\n\n orientation = \"horizontal\" if vertical else \"vertical\"\n hist_color = hist_kws.pop(\"color\", color)\n ax.hist(a, bins, orientation=orientation,\n color=hist_color, **hist_kws)\n if hist_color != color:\n hist_kws[\"color\"] = hist_color\n\n if kde:\n kde_color = kde_kws.pop(\"color\", color)\n kdeplot(a, vertical=vertical, ax=ax, color=kde_color, **kde_kws)\n if kde_color != color:\n kde_kws[\"color\"] = kde_color\n\n if rug:\n rug_color = rug_kws.pop(\"color\", color)\n axis = \"y\" if vertical else \"x\"\n rugplot(a, axis=axis, ax=ax, color=rug_color, **rug_kws)\n if rug_color != color:\n rug_kws[\"color\"] = rug_color\n\n if fit is not None:\n\n def pdf(x):\n return fit.pdf(x, *params)\n\n fit_color = fit_kws.pop(\"color\", \"#282828\")\n gridsize = fit_kws.pop(\"gridsize\", 200)\n cut = fit_kws.pop(\"cut\", 3)\n clip = fit_kws.pop(\"clip\", (-np.inf, np.inf))\n bw = gaussian_kde(a).scotts_factor() * a.std(ddof=1)\n x = _kde_support(a, bw, gridsize, cut, clip)\n params = fit.fit(a)\n y = pdf(x)\n if vertical:\n x, y = y, x\n ax.plot(x, y, color=fit_color, **fit_kws)\n if fit_color != \"#282828\":\n fit_kws[\"color\"] = fit_color\n\n if label_ax:\n if vertical:\n ax.set_ylabel(axlabel)\n else:\n ax.set_xlabel(axlabel)\n\n return ax\n"
] |
[
[
"numpy.take",
"numpy.linspace",
"pandas.Series",
"numpy.asarray",
"matplotlib.colors.to_rgba",
"numpy.sqrt",
"numpy.cumsum",
"pandas.DataFrame",
"numpy.zeros_like",
"numpy.searchsorted",
"matplotlib.pyplot.gca",
"pandas.Index",
"numpy.diff",
"numpy.ravel",
"numpy.repeat",
"numpy.zeros",
"numpy.power",
"matplotlib.collections.LineCollection",
"numpy.isnan",
"numpy.ndim",
"numpy.append",
"matplotlib.colors.ListedColormap",
"numpy.ma.masked_less_equal",
"numpy.nanpercentile",
"numpy.cos",
"numpy.sort",
"numpy.tile",
"matplotlib.transforms.blended_transform_factory"
]
] |
jlpearso/coastlines-at-risk-of-hypoxia-in-the-northern-indian-ocean
|
[
"dc70df36c2139a685c5f2cd7dc901e7b11bb0cc7"
] |
[
"data_processing/0_WOD/raw_data/get_data/concat_and_process.py"
] |
[
"inpath = 'individual/'\noutfn = 'all_casts_beginning_to_aug_2020_indian_ocean.nc'\n \n\n###############################################################################################################\n# No need to change anything below this line\n\nimport xarray as xr\nimport numpy as np\nimport pandas as pd\nimport os\nimport glob\nfrom tqdm import tqdm\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\ntoday = datetime.today()\nend_year = today.year\n\noutfn = 'concatenated/' + outfn\n\nfile = open(\"log.txt\",\"w\",1) \nfile.writelines('File: ' + outfn + ', Processing Date: ' + today.strftime(\"%m/%d/%Y\") + '\\n')\n\n# get all the datafiles\nfns = glob.glob(inpath + '*.nc')\n\n# can modify below to only get data to a certain depth, just remove what you don't need.\n# see https://www.ncei.noaa.gov/access/world-ocean-database-select/depth_definition.html\n# for depth definitions \nDEPTH = np.array([0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,\n 125,150,175,200,225,250,275,300,325,350,375,400,425,450,475,500,\n 550,600,650,700,750,800,850,900,950,1000,1050,1100,1150,1200,1250,1300,\n 1350,1400,1450,1500,1550,1600,1650,1700,1750,1800,1850,1900,1950,2000,\n 2100,2200,2300,2400,2500,2600,2700,2800,2900,3000,\n 3100,3200,3300,3400,3500,3600,3700,3800,3900,4000,\n 4100,4200,4300,4400,4500,4600,4700,4800,4900,5000])\n# loop through to get the total number of profiles for variable initialization\nno_profs = 0\nfor ff,fn in enumerate(fns):\n \n ds_in = xr.open_dataset(fn)\n no_profs = no_profs + len(ds_in.casts)\n \n\n# set up figure for plotting profiles\nfig = plt.figure(figsize=(16,10),dpi=200)\nax1 = fig.add_subplot(231)\nax1.set_title('Temperature Profiles')\nax1.set_ylabel('Depth (m)')\nax2 = fig.add_subplot(232)\nax2.set_title('Salinity Profiles')\nax3 = fig.add_subplot(233)\nax3.set_title('Oxygen Profiles')\nax4 = fig.add_subplot(234)\nax4.set_title('Nitrate Profiles')\nax4.set_ylabel('Depth (m)')\nax5 = fig.add_subplot(235)\nax5.set_title('Phosphate Profiles')\nax6 = fig.add_subplot(236)\nax6.set_title('Profile Locations')\n\n\n# initialize vars\nlat = []\nlon = []\nt = []\ncast_id = []\nTEMP = np.full([no_profs,len(DEPTH)],np.nan)\nDOXY = np.full([no_profs,len(DEPTH)],np.nan)\nSAL = np.full([no_profs,len(DEPTH)],np.nan)\nNITRATE = np.full([no_profs,len(DEPTH)],np.nan)\nPHOSPHATE = np.full([no_profs,len(DEPTH)],np.nan)\n\nvarlist = ['OSD','CTD','DRB','MRB','PFL','XBT','MBT','UOR','APB','GLD','SUR']\n# varlist = ['OSD']\n\npr = 0 # set profile counter to 0 and add 1 for each loop\n\n# loop through all datatypes APB, CTD, DRB, MRB, OSD, PFL, XBT\nfor vv, var in enumerate(varlist):\n\n fns = sorted(glob.glob(inpath + '*' + var + '*.nc'))\n \n # loop through all files of the same dataset\n for fn in fns:\n # add files to log file to keep track of progress if VPN closes while processing\n file.writelines('Processing: ' + fn + '\\n') \n\n # read in file\n ds_in = xr.open_dataset(fn)\n \n # for some reason it needs the cc:cc+1 instead of cc but it's the same thing.\n lat.extend(np.array(ds_in.lat))\n lon.extend(np.array(ds_in.lon))\n t.extend(np.array(ds_in.time))\n cast_id.extend([var + '_' + str(s) for s in list(np.array(ds_in.wod_unique_cast))])\n\n # initialize counters\n temp_row_count = 0\n sal_row_count = 0\n doxy_row_count = 0\n nitrate_row_count = 0\n phosphate_row_count = 0\n z_row_count = 0\n\n # loop through all casts and extract profiles\n for cc in tqdm(range(len(ds_in.casts)), position=0, leave=True, desc = 'Processing: ' + fn):\n# for cc in tqdm(range(30), position=0, leave=True, desc = 'Processing: ' + fn):\n\n # find the number of depths in the current cast cc\n z_sz = ds_in.z_row_size[cc]\n\n if ~np.isnan(z_sz): # no profile available for any variable if nan (this happens sometimes)\n\n # find the number of temp obs in the current cast profile\n \n if \"Temperature\" in ds_in:\n t_sz = ds_in.Temperature_row_size[cc]\n if \"Salinity\" in ds_in:\n s_sz = ds_in.Salinity_row_size[cc]\n if \"Oxygen\" in ds_in:\n d_sz = ds_in.Oxygen_row_size[cc]\n if \"Nitrate\" in ds_in:\n n_sz = ds_in.Nitrate_row_size[cc]\n if \"Phosphate\" in ds_in:\n p_sz = ds_in.Phosphate_row_size[cc]\n\n\n # get current depth\n z = ds_in.z[z_row_count:z_row_count + int(z_sz)]\n\n # find the indx of the current z values that are elements of DEPTH\n z_ind = [i for i, val in enumerate(DEPTH) if val in set(np.array(z))]\n\n # --------------------------------------------------------------\n # TEMP\n # --------------------------------------------------------------\n if \"Temperature\" in ds_in:\n # no profile available if nan and flag == 0 --> accepted profile\n t_sz = ds_in.Temperature_row_size[cc]\n if (~np.isnan(t_sz)) & (ds_in.Temperature_WODprofileflag[cc] == 0): \n if ~np.isnan(t_sz): \n # extract cast\n temp = ds_in.Temperature[temp_row_count:temp_row_count + int(t_sz)]\n TEMP[pr,z_ind] = temp[z_ind]\n ax1.plot(TEMP[pr,:],-1*DEPTH)\n\n # --------------------------------------------------------------\n # Salinity\n # --------------------------------------------------------------\n if \"Salinity\" in ds_in:\n # no profile available if nan and flag == 0 --> accepted profile\n s_sz = ds_in.Salinity_row_size[cc]\n if (~np.isnan(s_sz)) & (ds_in.Salinity_WODprofileflag[cc] == 0):\n if ~np.isnan(s_sz):\n # extract cast\n sal = ds_in.Salinity[sal_row_count:sal_row_count + int(s_sz)]\n SAL[pr,z_ind] = sal[z_ind]\n ax2.plot(SAL[pr,:],-1*DEPTH)\n\n\n # --------------------------------------------------------------\n # DOXY\n # --------------------------------------------------------------\n if \"Oxygen\" in ds_in:\n # no profile available if nan and flag == 0 --> accepted profile\n d_sz = ds_in.Oxygen_row_size[cc]\n if (~np.isnan(d_sz)) & (ds_in.Oxygen_WODprofileflag[cc] == 0): \n if ~np.isnan(d_sz):\n # extract cast\n doxy= ds_in.Oxygen[doxy_row_count:doxy_row_count + int(d_sz)]\n DOXY[pr,z_ind] = doxy[z_ind]\n ax3.plot(DOXY[pr,:],-1*DEPTH)\n\n # --------------------------------------------------------------\n # NITRATE\n # --------------------------------------------------------------\n if \"Nitrate\" in ds_in:\n # no profile available if nan and flag == 0 --> accepted profile\n n_sz = ds_in.Nitrate_row_size[cc]\n if (~np.isnan(n_sz)) & (ds_in.Nitrate_WODprofileflag[cc] == 0): \n if ~np.isnan(n_sz): \n # extract cast\n nitrate = ds_in.Nitrate[nitrate_row_count:nitrate_row_count + int(n_sz)]\n NITRATE[pr,z_ind] = nitrate[z_ind]\n ax4.plot(NITRATE[pr,:],-1*DEPTH)\n\n # --------------------------------------------------------------\n # PHOSPHATE\n # --------------------------------------------------------------\n if \"Phosphate\" in ds_in:\n # no profile available if nan and flag == 0 --> accepted profile\n p_sz = ds_in.Phosphate_row_size[cc]\n if (~np.isnan(p_sz)) & (ds_in.Phosphate_WODprofileflag[cc] == 0): \n if ~np.isnan(p_sz): \n # extract cast\n phosphate = ds_in.Phosphate[phosphate_row_count:phosphate_row_count + int(p_sz)]\n PHOSPHATE[pr,z_ind] = phosphate[z_ind]\n ax5.plot(PHOSPHATE[pr,:],-1*DEPTH) \n\n pr = pr + 1\n \n \n # move index up\n if \"Temperature\" in ds_in:\n if (~np.isnan(t_sz)):\n temp_row_count = temp_row_count + int(t_sz)\n if \"Salinity\" in ds_in:\n if (~np.isnan(s_sz)):\n sal_row_count = sal_row_count + int(s_sz)\n if \"Oxygen\" in ds_in:\n if (~np.isnan(d_sz)):\n doxy_row_count = doxy_row_count + int(d_sz)\n if \"Nitrate\" in ds_in:\n if (~np.isnan(n_sz)):\n nitrate_row_count = nitrate_row_count + int(n_sz)\n if \"Phosphate\" in ds_in:\n if (~np.isnan(p_sz)):\n phosphate_row_count = phosphate_row_count + int(p_sz)\n \n z_row_count = z_row_count + int(z_sz)\n\nfile.close()\nax6.scatter(lon,lat)\nprint('Saving Figure...')\nplt.savefig(outfn[:-3], dpi=300, bbox_inches='tight')\n\nprint('Saving Data...')\n# convert to xarray dataset\nds_out=xr.Dataset(\n coords={'cast': np.arange(no_profs),\n 'depth': DEPTH},\n attrs = {\n 'date_created': today.strftime(\"%m/%d/%Y\"),\n 'unmerged_data_url': 'https://www.ncei.noaa.gov/access/world-ocean-database-select/dbsearch.html',\n 'geospatial_lat_extent': 'decimal degrees north ' + '(' + str(np.min(lat)) + ',' + str(np.max(lat)) + ')',\n 'geospatial_lon_extent': 'decimal degrees east ' + '(' + str(np.min(lon)) + ',' + str(np.max(lon)) + ')',\n 'help_email': '[email protected]',\n 'history': 'Merged ../latest/*.nc',\n }\n )\n\n# add variables to dataset\nds_out[\"time\"]=xr.DataArray(t, dims = ['cast'], coords =[np.arange(no_profs)])\nds_out[\"lat\"]=xr.DataArray(lat, dims = ['cast'], coords =[np.arange(no_profs)])\nds_out[\"lon\"]=xr.DataArray(lon, dims = ['cast'], coords =[np.arange(no_profs)])\nds_out[\"cast_id\"]=xr.DataArray(cast_id, dims = ['cast'], coords =[np.arange(no_profs)])\n\nds_out[\"temp\"]=xr.DataArray(TEMP, dims = ['cast','depth'], coords =[np.arange(no_profs),DEPTH])\nds_out[\"sal\"]=xr.DataArray(SAL, dims = ['cast','depth'], coords =[np.arange(no_profs),DEPTH])\nds_out[\"doxy\"]=xr.DataArray(DOXY, dims = ['cast','depth'], coords =[np.arange(no_profs),DEPTH])\nds_out[\"nitrate\"]=xr.DataArray(NITRATE, dims = ['cast','depth'], coords =[np.arange(no_profs),DEPTH])\nds_out[\"phosphate\"]=xr.DataArray(PHOSPHATE, dims = ['cast','depth'], coords =[np.arange(no_profs),DEPTH])\n\n# delete if already present\nif os.path.isfile(outfn):\n os.remove(outfn)\n\nds_out.to_netcdf(outfn,mode='w',format = \"NETCDF4\")\nds_out\n\n"
] |
[
[
"numpy.min",
"numpy.isnan",
"numpy.arange",
"matplotlib.use",
"matplotlib.pyplot.savefig",
"numpy.max",
"numpy.array",
"matplotlib.pyplot.figure"
]
] |
Achuan-2/doubantop250
|
[
"a7da15a96277d02e9f5fd9d46134025ab1edae99"
] |
[
"douban250.py"
] |
[
"import requests\nimport pandas as pd\nimport bs4\nimport os\nfrom tqdm import tqdm\nfrom lxml import etree\nfrom bs4 import BeautifulSoup\n\"\"\"\n注意这个脚本是必须要有豆瓣登陆的cookie才能正常运行的,因为脚本会解析10+250=260个页面,会被豆瓣识别为异常访问,限制ip访问的\n\"\"\"\ndef find_page_num(res):\n soup = bs4.BeautifulSoup(res.text, 'html.parser')\n depth = soup.find(\n 'span', class_='next').previous_sibling.previous_sibling.text\n\n return int(depth)\n\n# 定义函数,用来处理User-Agent和Cookie\n\n\ndef ua_ck():\n '''\n 网站需要登录才能采集,需要从Network里复制User-Agent和Cookie,Cookie要转化为字典,否则会采集失败!!!!!\n '''\n\n user_agent = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36'}\n\n cookies = 'll=\"108304\"; bid=I4zqlTPs6Qg; douban-fav-remind=1; viewed=\"34432673\"; ap_v=0,6.0; push_noty_num=0; push_doumail_num=0; dbcl2=\"191491114:SlSLE5NfS/M\"; ck=6zCi'\n\n # Cookie转化为字典\n cookies = cookies.split('; ')\n cookies_dict = {}\n for i in cookies:\n cookies_dict[i.split('=')[0]] = i.split('=')[1]\n\n return user_agent, cookies_dict\n\n\ndef open_url(url):\n login = ua_ck()\n u_a = login[0]\n c_d = login[1]\n res = requests.get(url, headers=u_a, cookies=c_d)\n\n return res\n\n\ndef mkdir(path):\n flag = os.path.exists(path)\n if not flag:\n os.makedirs(path)\n\n\ndef download_pic(pic_url, filename):\n picture_response = requests.get(url=pic_url)\n with open(filename, 'wb') as f:\n f.write(picture_response.content)\n\n\ndef parse_movie(url):\n res = open_url(url)\n soup = BeautifulSoup(res.text, 'html.parser') # 用 html.parser 来解析网页\n item = soup.find('div', id='content')\n movie_info = {} # 新建字典,存放电影信息\n # 电影名称\n movie_info['电影名称'] = item.h1.span.text\n\n # 导演、类型、制片国家/地区、语言、上映时间、片长(部分电影这些信息不全,先全部采集,留待数据分析时处理)\n infos = item.find('div', id='info').text.replace(' ', '').split('\\n')\n for i in infos:\n if ':' in i:\n movie_info[i.split(':')[0]] = i.split(':')[1]\n else:\n continue\n return movie_info\n\n\ndef parse_page(html, table):\n # 为电影图片生成一个文件夹\n movie_pic = \"movie_pic\"\n mkdir(movie_pic)\n\n # 开始解析\n xp = etree.HTML(html)\n lis = xp.xpath('//*[@id=\"content\"]/div/div[1]/ol/li')\n for li in lis:\n rank = li.xpath('div/div[1]/em/text()')[0]\n link = li.xpath('div/div[2]/div[1]/a/@href')[0]\n rating = li.xpath('div/div[2]/div[2]/div/span[2]/text()')[0]\n people = li.xpath('div/div[2]/div[2]/div/span[4]/text()')[0][:-3]\n try:\n quote = li.xpath('div/div[2]/div[2]/p[2]/span/text()')[0]\n except:\n quote = None\n movie_info = parse_movie(link)\n # line = [rank, rating] + \\\n # list(movie_info.values())[:-1]+[people, quote, link]\n movie_dict = {\"排名\": rank, \"评分\": rating}\n movie_dict.update(movie_info)\n movie_dict.update({\"评分人数\": people, \"短评\": quote, \"豆瓣链接\": link})\n\n table.append(movie_dict)\n\n # 下载图片\n # pic_url = li.xpath('div/div[1]/a/img/@src')[0]\n # download_pic(pic_url, f\"{movie_pic}/{rank}-{title}_{rating}分.jpg\")\n return table\n\n\ndef main():\n\n # 解析并生成excel表格\n table = []\n host = \"https://movie.douban.com/top250\"\n # page_num = find_page_num(open_url(host))\n page_num = 10\n for i in tqdm(range(page_num), desc='解析进度'):\n url = host + '/?start=' + str(25*i)\n res = open_url(url)\n html = res.text\n table = parse_page(html, table)\n df = pd.DataFrame(table)\n df.to_excel('movies/豆瓣Top250_raw.xlsx', index=False)\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"pandas.DataFrame"
]
] |
Fabus1184/stonks-bot
|
[
"a98e0be699b10caffca8e0e5e5544d1d3e4fa18f"
] |
[
"stonks.py"
] |
[
"from matplotlib import markers\r\nimport requests\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.ticker as mticker \r\nimport matplotlib.dates as mdates\r\nimport pandas as pd\r\nimport numpy as np\r\nimport time\r\nimport json\r\nfrom discord_webhook import DiscordWebhook\r\n\r\n(a,b) = (time.time()-604800, time.time())\r\n\r\nurl = \"https://api.coingecko.com/api/v3/coins/ethereum/market_chart/range?vs_currency=eur&from=%s&to=%s\" % (a,b)\r\nresponse = requests.request(\"GET\", url)\r\n\r\ndata = json.loads(response.text)\r\n\r\ndate = []\r\nprice = []\r\nvol = []\r\ncap = []\r\n\r\nfor x in data['prices']:\r\n price.append(x[1])\r\n date.append(x[0])\r\n\r\nfor x in data['total_volumes']:\r\n vol.append(x[1]/10**9)\r\n\r\n# for x in data['market_caps']:\r\n# cap.append(x[1]/10**9)\r\n\r\ndate_raw = date\r\ndate = pd.to_datetime(date, unit='ms').to_numpy()\r\n\r\ntitle = \"ETH Stonks - \" + time.strftime(\"%d.%m\", time.localtime(a)) + \" - \" + time.strftime(\"%d.%m\", time.localtime(b))\r\n\r\nt = np.arange(0, len(date))\r\ntrend = np.poly1d(np.polyfit(t, price, 10))\r\n\r\ntrend = trend(t)\r\n\r\nfig,ax = plt.subplots()\r\nax2=ax.twinx()\r\nax3=ax2.twinx()\r\n\r\nstonks = (1-(trend[0]/trend[len(trend)-1])) * 100\r\nstonks = np.around(stonks, 2)\r\n\r\nif stonks > 0:\r\n stonks = \"+\" + str(stonks) + \"%\"\r\n color = \"green\"\r\nelse:\r\n stonks = str(stonks) + \"%\"\r\n color = \"red\"\r\n\r\nn = 1\r\npoi = np.array([])\r\npoi = np.append(poi, np.sort((price))[0:n])\r\npoi = np.append(poi, np.sort((price))[-n:])\r\n\r\npoi = poi.tolist()\r\nfor place, item in enumerate(poi):\r\n poi[place] = price.index(item)\r\n\r\n\r\nn = 3\r\nderv = np.array([])\r\nderv = np.append(derv, np.sort(np.diff(price))[0:n])\r\nderv = np.append(derv, np.sort(np.diff(price))[-n:])\r\n\r\nderv = derv.tolist()\r\nfor place, item in enumerate(derv):\r\n derv[place] = np.diff(price).tolist().index(item)\r\n\r\n\r\n\r\n#---------------------------------------------------------------------------\r\nax3.plot(date, vol, color=\"tomato\", linewidth=0.5, zorder=0, label=\"Volume\" )\r\nax3.set_ylabel(\"\", color=\"tomato\",fontsize=14)\r\n#---------------------------------------------------------------------------\r\n\r\nax2.plot(date, trend, color=color, linewidth=0.8, linestyle=\":\", label=stonks)\r\nax2.get_yaxis().set_visible(False)\r\n#---------------------------------------------------------------------------\r\n\r\nax.plot(date, price, color=\"cornflowerblue\", linewidth=0.7, label=\"Preis\")\r\nax.set_ylabel(\"\", color=\"cornflowerblue\", fontsize=14)\r\nax.get_yaxis().set_major_formatter(mticker.FormatStrFormatter('%i €'))\r\nax.grid(b=True, which='both', linestyle=\"--\", linewidth=0.3)\r\n\r\n\r\nax.plot(np.array(np.nan), np.array(np.nan), color=\"tomato\", linewidth=0.5, zorder=0, label=\"Volume\")\r\nax.plot(np.array(np.nan), np.array(np.nan), color=color, linewidth=0.8, linestyle=\":\", label=stonks)\r\nax.legend()\r\n\r\n# for p in derv:\r\n# ax.plot(date[p], price[p], marker=\".\", color=\"gold\")\r\n\r\nfor p in poi:\r\n ax.plot(date[p], price[p], color=\"darkorange\", marker=\".\")\r\n ax.text(date[p], price[p], str(int(price[p]))+\"€\")\r\n\r\nax3.get_yaxis().set_major_formatter(mticker.FormatStrFormatter('%i Mrd. €'))\r\nax3.get_xaxis().set_major_formatter(mdates.DateFormatter('%A'))\r\n\r\n#---------------------------------------------------------------------------\r\n\r\nfig.autofmt_xdate()\r\nplt.title(title)\r\nplt.tight_layout()\r\nplt.savefig(\"tmp.png\", dpi=600)\r\nplt.clf()\r\n\r\n# ..........................................................................\r\n\r\nurl = wbhk_url\r\n\r\nwebhook = DiscordWebhook(url=url)\r\n\r\nwith open(\"tmp.png\", \"rb\") as f:\r\n webhook.add_file(file=f.read(), filename='tmp.png')\r\n\r\nresponse = webhook.execute()\r\n"
] |
[
[
"numpy.polyfit",
"matplotlib.pyplot.tight_layout",
"matplotlib.dates.DateFormatter",
"pandas.to_datetime",
"matplotlib.pyplot.title",
"numpy.around",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"numpy.sort",
"matplotlib.pyplot.clf",
"numpy.diff",
"matplotlib.ticker.FormatStrFormatter",
"numpy.array"
]
] |
srio/paper-transfocators-resources
|
[
"917d8b4114056f62c84b295579e55bf5f0b56b6b"
] |
[
"monochromator/DCM_vibrational_study_v1.py"
] |
[
"#\n# Python script to run shadow3. Created automatically with ShadowTools.make_python_script_from_list().\n#\nimport Shadow\nimport numpy\nfrom srxraylib.plot.gol import plot, plot_image\nimport pandas as pd\n\n\ndef run_beamline(beam, x_rot1=2e-10, x_rot2=2e-10, DCM_pos=60):\n \"\"\"This function runs the beamline starting just after\n the hybrid widget, it takes the DCM crystal rotation misalignment \n and position\"\"\"\n # write (1) or not (0) SHADOW files start.xx end.xx star.xx\n iwrite = 0\n\n oe0 = Shadow.OE()\n oe1 = Shadow.OE()\n oe2 = Shadow.OE()\n oe3 = Shadow.OE()\n oe4 = Shadow.OE()\n oe5 = Shadow.OE()\n oe6 = Shadow.OE()\n oe7 = Shadow.OE()\n oe8 = Shadow.OE()\n oe9 = Shadow.OE()\n oe10 = Shadow.OE()\n oe11 = Shadow.OE()\n\n #\n # Define variables. See meaning of variables in:\n # https://raw.githubusercontent.com/srio/shadow3/master/docs/source.nml\n # https://raw.githubusercontent.com/srio/shadow3/master/docs/oe.nml\n #\n\n oe0.DUMMY = 100.0\n oe0.FILE_REFL = b'/mntdirect/_users/reyesher/OASYS/EBSL1-ID18/monochromator/Si_bragg_5_50.dat'\n oe0.FWRITE = 1\n oe0.F_CENTRAL = 1\n oe0.F_CRYSTAL = 1\n oe0.F_MOVE = 1\n oe0.PHOT_CENT = 7000.0\n oe0.R_LAMBDA = 5000.0\n oe0.T_IMAGE = 0.0\n oe0.T_INCIDENCE = 73.5910617052\n oe0.T_REFLECTION = 73.5910617052\n if DCM_pos == 38:\n oe0.T_SOURCE = 2.0\n elif DCM_pos == 60:\n oe0.T_SOURCE = 24.0\n else:\n raise RuntimeError(f'ERROR: Not DCM position has identified: {DCM_pos}')\n oe0.X_ROT = x_rot1 # = 2e-10 # pitch rotation\n\n oe1.DUMMY = 100.0\n oe1.FILE_REFL = b'/mntdirect/_users/reyesher/OASYS/EBSL1-ID18/monochromator/Si_bragg_5_50.dat'\n oe1.FWRITE = 1\n oe1.F_CENTRAL = 1\n oe1.F_CRYSTAL = 1\n oe1.F_MOVE = 1\n oe1.PHOT_CENT = 7000.0\n oe1.R_LAMBDA = 5000.0\n oe1.T_IMAGE = 0.0\n oe1.T_INCIDENCE = 73.5910617052\n oe1.T_REFLECTION = 73.5910617052\n oe1.T_SOURCE = 0.0\n oe1.X_ROT = x_rot2 # pitch rotation\n\n oe2.DUMMY = 100.0\n oe2.FWRITE = 3\n oe2.F_REFRAC = 2\n oe2.F_SCREEN = 1\n oe2.I_SLIT = numpy.array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n oe2.K_SLIT = numpy.array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n oe2.N_SCREEN = 1\n oe2.RX_SLIT = numpy.array([0.001, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n oe2.RZ_SLIT = numpy.array([0.001, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n oe2.T_IMAGE = 0.0\n oe2.T_INCIDENCE = 0.0\n oe2.T_REFLECTION = 180.0\n if DCM_pos == 38:\n oe2.T_SOURCE = 27.0 #For DCM @ 38 m\n elif DCM_pos == 60:\n oe2.T_SOURCE = 5.0 #For DCM @ 60 m\n else:\n raise RuntimeError(f'ERROR: Not DCM position has identified: {DCM_pos}')\n\n oe3.CCC = numpy.array([1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0011606, 0.0])\n oe3.CIL_ANG = 90.0\n oe3.DUMMY = 100.0\n oe3.FCYL = 1\n oe3.FHIT_C = 1\n oe3.FILE_R_IND_IMA = b'/mntdirect/_users/reyesher/OASYS/EBSL1-ID18/Be_lens.dat'\n oe3.FMIRR = 4\n oe3.FSHAPE = 2\n oe3.FWRITE = 3\n oe3.F_EXT = 1\n oe3.F_REFRAC = 1\n oe3.F_R_IND = 2\n oe3.PARAM = 0.0005803\n oe3.RLEN2 = 0.0005\n oe3.RWIDX2 = 0.0005\n oe3.T_IMAGE = 5e-06\n oe3.T_INCIDENCE = 0.0\n oe3.T_REFLECTION = 180.0\n oe3.T_SOURCE = 0.0\n\n oe4.CCC = numpy.array([1.0, 1.0, 0.0, 0.0, -0.0, -0.0, 0.0, 0.0, 0.0011606, 0.0])\n oe4.CIL_ANG = 90.0\n oe4.DUMMY = 100.0\n oe4.FCYL = 1\n oe4.FHIT_C = 1\n oe4.FILE_R_IND_OBJ = b'/mntdirect/_users/reyesher/OASYS/EBSL1-ID18/Be_lens.dat'\n oe4.FMIRR = 4\n oe4.FSHAPE = 2\n oe4.FWRITE = 3\n oe4.F_CONVEX = 1\n oe4.F_EXT = 1\n oe4.F_REFRAC = 1\n oe4.F_R_IND = 1\n oe4.PARAM = 0.0005803\n oe4.RLEN2 = 0.0005\n oe4.RWIDX2 = 0.0005\n oe4.T_IMAGE = 0.0\n oe4.T_INCIDENCE = 0.0\n oe4.T_REFLECTION = 180.0\n oe4.T_SOURCE = 5e-06\n\n oe5.CCC = numpy.array([1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0013842, 0.0])\n oe5.DUMMY = 100.0\n oe5.FCYL = 1\n oe5.FHIT_C = 1\n oe5.FILE_R_IND_IMA = b'/mntdirect/_users/reyesher/OASYS/EBSL1-ID18/Be_lens.dat'\n oe5.FMIRR = 4\n oe5.FSHAPE = 2\n oe5.FWRITE = 3\n oe5.F_EXT = 1\n oe5.F_REFRAC = 1\n oe5.F_R_IND = 2\n oe5.PARAM = 0.0006921\n oe5.RLEN2 = 0.0005\n oe5.RWIDX2 = 0.0005\n oe5.T_IMAGE = 5e-06\n oe5.T_INCIDENCE = 0.0\n oe5.T_REFLECTION = 180.0\n oe5.T_SOURCE = 0.0\n\n oe6.CCC = numpy.array([1.0, 1.0, 0.0, 0.0, -0.0, -0.0, 0.0, 0.0, 0.0013842, 0.0])\n oe6.DUMMY = 100.0\n oe6.FCYL = 1\n oe6.FHIT_C = 1\n oe6.FILE_R_IND_OBJ = b'/mntdirect/_users/reyesher/OASYS/EBSL1-ID18/Be_lens.dat'\n oe6.FMIRR = 4\n oe6.FSHAPE = 2\n oe6.FWRITE = 3\n oe6.F_CONVEX = 1\n oe6.F_EXT = 1\n oe6.F_REFRAC = 1\n oe6.F_R_IND = 1\n oe6.PARAM = 0.0006921\n oe6.RLEN2 = 0.0005\n oe6.RWIDX2 = 0.0005\n oe6.T_IMAGE = 0.0\n oe6.T_INCIDENCE = 0.0\n oe6.T_REFLECTION = 180.0\n oe6.T_SOURCE = 5e-06\n\n oe7.DUMMY = 100.0\n oe7.FWRITE = 3\n oe7.F_REFRAC = 2\n oe7.F_SCREEN = 1\n oe7.I_SLIT = numpy.array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n oe7.K_SLIT = numpy.array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n oe7.N_SCREEN = 1\n oe7.RX_SLIT = numpy.array([0.001, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n oe7.RZ_SLIT = numpy.array([0.001, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n oe7.T_IMAGE = 0.0\n oe7.T_INCIDENCE = 0.0\n oe7.T_REFLECTION = 180.0\n oe7.T_SOURCE = 105.0\n\n oe8.CCC = numpy.array([1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.000728, 0.0])\n oe8.CIL_ANG = 90.0\n oe8.DUMMY = 100.0\n oe8.FCYL = 1\n oe8.FHIT_C = 1\n oe8.FILE_R_IND_IMA = b'/mntdirect/_users/reyesher/OASYS/EBSL1-ID18/Be_lens.dat'\n oe8.FMIRR = 4\n oe8.FSHAPE = 2\n oe8.FWRITE = 3\n oe8.F_EXT = 1\n oe8.F_REFRAC = 1\n oe8.F_R_IND = 2\n oe8.PARAM = 0.000364\n oe8.RLEN2 = 0.0005\n oe8.RWIDX2 = 0.0005\n oe8.T_IMAGE = 5e-06\n oe8.T_INCIDENCE = 0.0\n oe8.T_REFLECTION = 180.0\n oe8.T_SOURCE = 0.0\n\n oe9.CCC = numpy.array([1.0, 1.0, 0.0, 0.0, -0.0, -0.0, 0.0, 0.0, 0.000728, 0.0])\n oe9.CIL_ANG = 90.0\n oe9.DUMMY = 100.0\n oe9.FCYL = 1\n oe9.FHIT_C = 1\n oe9.FILE_R_IND_OBJ = b'/mntdirect/_users/reyesher/OASYS/EBSL1-ID18/Be_lens.dat'\n oe9.FMIRR = 4\n oe9.FSHAPE = 2\n oe9.FWRITE = 3\n oe9.F_CONVEX = 1\n oe9.F_EXT = 1\n oe9.F_REFRAC = 1\n oe9.F_R_IND = 1\n oe9.PARAM = 0.000364\n oe9.RLEN2 = 0.0005\n oe9.RWIDX2 = 0.0005\n oe9.T_IMAGE = 0.0\n oe9.T_INCIDENCE = 0.0\n oe9.T_REFLECTION = 180.0\n oe9.T_SOURCE = 5e-06\n\n oe10.CCC = numpy.array([1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0011058, 0.0])\n oe10.DUMMY = 100.0\n oe10.FCYL = 1\n oe10.FHIT_C = 1\n oe10.FILE_R_IND_IMA = b'/mntdirect/_users/reyesher/OASYS/EBSL1-ID18/Be_lens.dat'\n oe10.FMIRR = 4\n oe10.FSHAPE = 2\n oe10.FWRITE = 3\n oe10.F_EXT = 1\n oe10.F_REFRAC = 1\n oe10.F_R_IND = 2\n oe10.PARAM = 0.0005529\n oe10.RLEN2 = 0.0005\n oe10.RWIDX2 = 0.0005\n oe10.T_IMAGE = 5e-06\n oe10.T_INCIDENCE = 0.0\n oe10.T_REFLECTION = 180.0\n oe10.T_SOURCE = 0.0\n\n oe11.CCC = numpy.array([1.0, 1.0, 0.0, 0.0, -0.0, -0.0, 0.0, 0.0, 0.0011058, 0.0])\n oe11.DUMMY = 100.0\n oe11.FCYL = 1\n oe11.FHIT_C = 1\n oe11.FILE_R_IND_OBJ = b'/mntdirect/_users/reyesher/OASYS/EBSL1-ID18/Be_lens.dat'\n oe11.FMIRR = 4\n oe11.FSHAPE = 2\n oe11.FWRITE = 3\n oe11.F_CONVEX = 1\n oe11.F_EXT = 1\n oe11.F_REFRAC = 1\n oe11.F_R_IND = 1\n oe11.PARAM = 0.0005529\n oe11.RLEN2 = 0.0005\n oe11.RWIDX2 = 0.0005\n oe11.T_IMAGE = 30.0\n oe11.T_INCIDENCE = 0.0\n oe11.T_REFLECTION = 180.0\n oe11.T_SOURCE = 5e-06\n\n # run optical element 0\n\n print(\" Running optical element: %d\" % (0))\n if iwrite:\n oe0.write(\"start.00\")\n\n beam.traceOE(oe0, 0)\n\n if iwrite:\n oe0.write(\"end.00\")\n beam.write(\"star.00\")\n\n #\n # run optical element 1\n #\n print(\" Running optical element: %d\" % (1))\n if iwrite:\n oe1.write(\"start.01\")\n\n beam.traceOE(oe1, 1)\n\n if iwrite:\n oe1.write(\"end.01\")\n beam.write(\"star.01\")\n\n #\n # run optical element 2\n #\n print(\" Running optical element: %d\" % (2))\n if iwrite:\n oe2.write(\"start.02\")\n\n beam.traceOE(oe2, 2)\n\n if iwrite:\n oe2.write(\"end.02\")\n beam.write(\"star.02\")\n\n #\n # run optical element 3\n #\n print(\" Running optical element: %d\" % (3))\n if iwrite:\n oe3.write(\"start.03\")\n\n beam.traceOE(oe3, 3)\n\n if iwrite:\n oe3.write(\"end.03\")\n beam.write(\"star.03\")\n\n #\n # run optical element 4\n #\n print(\" Running optical element: %d\" % (4))\n if iwrite:\n oe4.write(\"start.04\")\n\n beam.traceOE(oe4, 4)\n\n if iwrite:\n oe4.write(\"end.04\")\n beam.write(\"star.04\")\n\n #\n # run optical element 5\n #\n print(\" Running optical element: %d\" % (5))\n if iwrite:\n oe5.write(\"start.05\")\n\n beam.traceOE(oe5, 5)\n\n if iwrite:\n oe5.write(\"end.05\")\n beam.write(\"star.05\")\n\n #\n # run optical element 6\n #\n print(\" Running optical element: %d\" % (6))\n if iwrite:\n oe6.write(\"start.06\")\n\n beam.traceOE(oe6, 6)\n\n if iwrite:\n oe6.write(\"end.06\")\n beam.write(\"star.06\")\n\n #\n # run optical element 7\n #\n print(\" Running optical element: %d\" % (7))\n if iwrite:\n oe7.write(\"start.07\")\n\n beam.traceOE(oe7, 7)\n\n if iwrite:\n oe7.write(\"end.07\")\n beam.write(\"star.07\")\n\n #\n # run optical element 8\n #\n print(\" Running optical element: %d\" % (8))\n if iwrite:\n oe8.write(\"start.08\")\n\n beam.traceOE(oe8, 8)\n\n if iwrite:\n oe8.write(\"end.08\")\n beam.write(\"star.08\")\n\n #\n # run optical element 9\n #\n print(\" Running optical element: %d\" % (9))\n if iwrite:\n oe9.write(\"start.09\")\n\n beam.traceOE(oe9, 9)\n\n if iwrite:\n oe9.write(\"end.09\")\n beam.write(\"star.09\")\n\n #\n # run optical element 10\n #\n print(\" Running optical element: %d\" % (10))\n if iwrite:\n oe10.write(\"start.10\")\n\n beam.traceOE(oe10, 10)\n\n if iwrite:\n oe10.write(\"end.10\")\n beam.write(\"star.10\")\n\n #\n # run optical element 11\n #\n print(\" Running optical element: %d\" % (11))\n if iwrite:\n oe11.write(\"start.11\")\n\n beam.traceOE(oe11, 11)\n\n if iwrite:\n oe11.write(\"end.11\")\n beam.write(\"star.11\")\n\n\n return beam\n\n\ndef run_loop(sigma1_urad = 0.0, sigma2_urad = 0.0, DCM_pos=38):\n\n\n sigma1_deg = sigma1_urad * 1e-6 * 180 / numpy.pi\n sigma2_deg = sigma2_urad * 1e-6 * 180 / numpy.pi\n \n \n #random normal distributions\n r1 = numpy.random.normal(loc=0.0, scale=sigma1_deg, size=nruns)\n r2 = numpy.random.normal(loc=0.0, scale=sigma2_deg, size=nruns) # -r1 #\n\n sizes = numpy.zeros_like(distances)\n Sizes = numpy.zeros((nruns, distances.size))\n Centers = numpy.zeros((nruns, distances.size))\n RMSs = numpy.zeros((nruns, distances.size))\n\n HISTO_X = []\n HISTO_Y = []\n\n for i in range(nruns):\n beam = run_beamline(beam_source.duplicate(), x_rot1=r1[i], x_rot2=r2[i], DCM_pos=DCM_pos)\n\n for j,distance in enumerate(distances):\n tmp = beam.duplicate()\n tmp.retrace(distance)\n\n tkt = tmp.histo1(3, xrange=[-300e-6,300e-6], nbins=150, nolost=1, ref=0, write=None, factor=1.0, calculate_widths=1,\n calculate_hew=0)\n fwhm = tkt[\"fwhm\"]\n if i == 0:\n HISTO_X.append(tkt[\"bin_center\"])\n HISTO_Y.append(tkt[\"histogram\"])\n else:\n HISTO_X[j] = tkt[\"bin_center\"]\n HISTO_Y[j] += tkt[\"histogram\"]\n\n # plot(tkt[\"bin_center\"], tkt[\"histogram\"], title=\"%d %d \" % (i,j) )\n col3 = tmp.getshonecol(3, nolost=1)\n weight = numpy.ones_like(col3) # = tmp.getshonecol(23, nolost=1)\n sdev = tmp.get_standard_deviation(3, nolost=1, ref=0)\n center = numpy.average(col3, weights=weight)\n\n vv = numpy.average((col3) ** 2, weights=weight)\n rms = numpy.sqrt(vv)\n\n Sizes[i,j] = sdev\n Centers[i,j] = center\n RMSs[i,j] = rms\n\n\n return numpy.abs(RMSs).sum(axis=0) / nruns, HISTO_X, HISTO_Y\n\n\nif __name__ == \"__main__\":\n\n beam_source = Shadow.Beam()\n beam_source.load('Hy_screen_beam_1M.dat')\n\n\n nruns = 300 \n distances = numpy.linspace(-15, 15, 31)\n #@38 m or 60 m from the source\n DCM_pos = 38 #60 \n\n sizes0, hx0, hy0 = run_loop(sigma1_urad=0.0, sigma2_urad=0.0, DCM_pos=DCM_pos)\n sizes1, hx1, hy1 = run_loop(sigma1_urad=0.5, sigma2_urad=0.5, DCM_pos=DCM_pos) \n sizes2, hx2, hy2 = run_loop(sigma1_urad=1, sigma2_urad=1, DCM_pos=DCM_pos)\n \n # saving into a csv\n data = {'distances':distances,'0 urad RMS':sizes0,'0.5 urad RMS':sizes1,'1 urad RMS':sizes2}\n df = pd.DataFrame(data)\n df.to_csv(f'DCM_vibs_dist_to_focal_point_pos_{DCM_pos}.csv')\n\n # plotting options\n # plot(distances, 1e6 * sizes0,\n # distances, 1e6 * sizes1,\n # distances, 1e6 * sizes2,\n # legend=[\"0 urad RMS\", \"0.5 urad RMS\", \"1 urad RMS\"],\n # xtitle=\"Distance from focal point [m]\", ytitle=\"Beam size RMS\")\n\n # plot(numpy.array(hx0[0]), numpy.array(hy0[0]),\n # numpy.array(hx1[0]), numpy.array(hy1[0]),\n # numpy.array(hx2[0]), numpy.array(hy2[0]),\n # )\n\n # plot(numpy.array(hx0[distances.size // 2]), numpy.array(hy0[distances.size // 2]),\n # numpy.array(hx1[distances.size // 2]), numpy.array(hy1[distances.size // 2]),\n # numpy.array(hx2[distances.size // 2]), numpy.array(hy2[distances.size // 2]),\n # )\n\n # plot(numpy.array(hx0[-1]), numpy.array(hy0[-1]),\n # numpy.array(hx1[-1]), numpy.array(hy1[-1]),\n # numpy.array(hx2[-1]), numpy.array(hy2[-1]),\n # )\n\n\n # nx = distances.size\n # ny = len(hx0[0])\n\n # caustic0 = numpy.zeros((nx, ny))\n # for i in range(nx):\n # caustic0[i,:] = hy0[i]\n\n # caustic1 = numpy.zeros((nx, ny))\n # for i in range(nx):\n # caustic1[i,:] = hy1[i]\n\n # caustic2 = numpy.zeros((nx, ny))\n # for i in range(nx):\n # caustic2[i,:] = hy2[i]\n\n # plot_image(caustic0, distances, numpy.array(hx0[0]), aspect='auto', title=\"0\")\n # plot_image(caustic1, distances, numpy.array(hx1[0]), aspect='auto', title=\"0.5\")\n # plot_image(caustic2, distances, numpy.array(hx2[0]), aspect='auto', title=\"1.0\")\n"
] |
[
[
"numpy.ones_like",
"numpy.sqrt",
"numpy.linspace",
"numpy.abs",
"pandas.DataFrame",
"numpy.random.normal",
"numpy.zeros_like",
"numpy.average",
"numpy.array",
"numpy.zeros"
]
] |
lhq1208/object_detection
|
[
"ab3265e0f09b78415299c1a0b38254176a0565ed"
] |
[
"detection/YOLO_pytorch/train.py"
] |
[
"import torch\nfrom YOLO import config as cfg\nfrom torch import optim\nfrom torch.autograd import Variable\nfrom YOLO_pytorch import yolo_net\nfrom YOLO.pascal_voc import *\n\n\nclass Solver():\n def __init__(self, net, data, use_gpu=True):\n self.net = net\n self.data = data\n self.max_iter = cfg.MAX_ITER\n self.initial_learning_rate = cfg.LEARNING_RATE\n self.decay_steps = cfg.DECAY_STEPS\n self.decay_rate = cfg.DECAY_RATE\n self.staircase = cfg.STAIRCASE\n self.summary_iter = cfg.SUMMARY_ITER\n self.save_iter = cfg.SAVE_ITER\n\n self.optimizer = optim.SGD(self.net.model.parameters(), lr=self.initial_learning_rate)\n\n self.FloatTensor = torch.cuda.FloatTensor if use_gpu else torch.FloatTensor\n self.LongTensor = torch.cuda.LongTensor if use_gpu else torch.LongTensor\n self.ByteTensor = torch.cuda.ByteTensor if use_gpu else torch.ByteTensor\n\n def train(self):\n for ep in range(self.max_iter):\n images, labels = self.data.get()\n images = np.transpose(images, (0, 3, 1, 2))\n images, labels = Variable(torch.from_numpy(images)).type(self.FloatTensor), \\\n Variable(torch.from_numpy(labels)).type(self.FloatTensor)\n outputs = self.net.model(images)\n loss = self.net.get_loss(outputs, labels)\n loss = Variable(torch.FloatTensor([loss]), requires_grad=True).type(self.FloatTensor)\n self.optimizer.zero_grad()\n loss.backward(retain_graph=True)\n self.optimizer.step()\n\n print('epoch:',ep)\n print('loss:', loss.data.cpu().numpy())\n print('-' * 10)\n torch.save(self.net.model.state_dict(), 'model.pkl')\n\nif __name__ == '__main__':\n use_gpu = torch.cuda.is_available()\n yolo_net = yolo_net.YOLO(use_gpu=use_gpu)\n data = pascal_voc('train')\n solver = Solver(yolo_net, data, use_gpu)\n solver.train()\n\n"
] |
[
[
"torch.FloatTensor",
"torch.from_numpy",
"torch.cuda.is_available"
]
] |
nmichlo/disent
|
[
"c4fb871cdcdbf833e95e88a4637700c5b0e75613"
] |
[
"disent/dataset/util/stats.py"
] |
[
"# ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~\n# MIT License\n#\n# Copyright (c) 2021 Nathan Juraj Michlo\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n# ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~\n\nimport os\nfrom typing import Tuple\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import DataLoader\n\nfrom disent.util.function import wrapped_partial\n\n\n# ========================================================================= #\n# COMPUTE DATASET STATS #\n# ========================================================================= #\n\n\[email protected]_grad()\ndef compute_data_mean_std(\n data,\n batch_size: int = 256,\n num_workers: int = min(os.cpu_count(), 16),\n progress: bool = False,\n chn_is_last: bool = False\n) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Input data when collected using a DataLoader should return\n `torch.Tensor`s, output mean and std are an `np.ndarray`s\n \"\"\"\n loader = DataLoader(\n data,\n batch_size=batch_size,\n shuffle=False,\n num_workers=num_workers,\n drop_last=False,\n )\n if progress:\n from tqdm import tqdm\n loader = tqdm(loader, desc=f'{data.__class__.__name__} stats', total=(len(data) + batch_size - 1) // batch_size)\n # reduction dims\n dims = (1, 2) if chn_is_last else (2, 3)\n # collect obs means & stds\n img_means, img_stds = [], []\n for batch in loader:\n assert isinstance(batch, torch.Tensor), f'batch must be an instance of torch.Tensor, got: {type(batch)}'\n assert batch.ndim == 4, f'batch shape must be: (B, C, H, W), got: {tuple(batch.shape)}'\n batch = batch.to(torch.float64)\n img_means.append(torch.mean(batch, dim=dims))\n img_stds.append(torch.std(batch, dim=dims))\n # aggregate obs means & stds\n mean = torch.mean(torch.cat(img_means, dim=0), dim=0)\n std = torch.mean(torch.cat(img_stds, dim=0), dim=0)\n # checks!\n assert mean.ndim == 1\n assert std.ndim == 1\n # done!\n return mean.numpy(), std.numpy()\n\n\n# ========================================================================= #\n# HELPER #\n# ========================================================================= #\n\n\nif __name__ == '__main__':\n\n def main(progress=False):\n from disent.dataset import data\n from disent.dataset.transform import ToImgTensorF32\n\n for data_cls in [\n # groundtruth -- impl\n data.Cars3dData,\n data.DSpritesData,\n data.SmallNorbData,\n data.Shapes3dData,\n # groundtruth -- impl synthetic\n data.XYObjectData,\n data.XYObjectShadedData,\n # large datasets\n (data.Mpi3dData, dict(subset='toy', in_memory=True)),\n (data.Mpi3dData, dict(subset='realistic', in_memory=True)),\n (data.Mpi3dData, dict(subset='real', in_memory=True)),\n ]:\n from disent.dataset.transform import ToImgTensorF32\n # get arguments\n if isinstance(data_cls, tuple):\n data_cls, kwargs = data_cls\n else:\n data_cls, kwargs = data_cls, {}\n # Most common standardized way of computing the mean and std over observations\n # resized to 64px in size of dtype float32 in the range [0, 1].\n data = data_cls(transform=ToImgTensorF32(size=64), **kwargs)\n mean, std = compute_data_mean_std(data, progress=progress)\n # results!\n print(f'{data.__class__.__name__} - {data.name} - {kwargs}:\\n mean: {mean.tolist()}\\n std: {std.tolist()}')\n\n # RUN!\n main()\n\n\n# ========================================================================= #\n# RESULTS: 2021-11-12 #\n# ========================================================================= #\n\n\n# Cars3dData - cars3d - {}:\n# mean: [0.8976676149976628, 0.8891658020067508, 0.885147515814868]\n# std: [0.22503195531503034, 0.2399461278981261, 0.24792106319684404]\n# DSpritesData - dsprites - {}:\n# mean: [0.042494423521889584]\n# std: [0.19516645880626055]\n# SmallNorbData - smallnorb - {}:\n# mean: [0.7520918401088603]\n# std: [0.09563879016827263]\n# Shapes3dData - 3dshapes - {}:\n# mean: [0.502584966788819, 0.5787597566089667, 0.6034499731859578]\n# std: [0.2940814043555559, 0.34439790875172144, 0.3661685981524748]\n\n# XYBlocksData - xyblocks - {}:\n# mean: [0.10040509259259259, 0.10040509259259259, 0.10040509259259259]\n# std: [0.21689087652106678, 0.21689087652106676, 0.21689087652106678]\n# XYObjectData - xy_object - {}:\n# mean: [0.009818761549013288, 0.009818761549013288, 0.009818761549013288]\n# std: [0.052632363725245844, 0.05263236372524584, 0.05263236372524585]\n# XYObjectShadedData - xy_object - {}:\n# mean: [0.009818761549013288, 0.009818761549013288, 0.009818761549013288]\n# std: [0.052632363725245844, 0.05263236372524584, 0.05263236372524585]\n# XYSquaresData - xy_squares - {}:\n# mean: [0.015625, 0.015625, 0.015625]\n# std: [0.12403473458920855, 0.12403473458920854, 0.12403473458920854]\n# XYSquaresMinimalData - xy_squares_minimal - {}:\n# mean: [0.015625, 0.015625, 0.015625]\n# std: [0.12403473458920855, 0.12403473458920854, 0.12403473458920854]\n# XColumnsData - x_columns - {}:\n# mean: [0.125, 0.125, 0.125]\n# std: [0.33075929223788925, 0.3307592922378891, 0.3307592922378892]\n\n# XYSquaresData - xy_squares - {'grid_size': 8, 'grid_spacing': 8}:\n# mean: [0.015625, 0.015625, 0.015625]\n# std: [0.12403473458920855, 0.12403473458920854, 0.12403473458920854]\n# overlap between squares for reconstruction loss, 7 < 8\n# XYSquaresData - xy_squares - {'grid_size': 8, 'grid_spacing': 7}:\n# mean: [0.015625, 0.015625, 0.015625]\n# std: [0.12403473458920854, 0.12403473458920854, 0.12403473458920854]\n# overlap between squares for reconstruction loss, 6 < 8\n# XYSquaresData - xy_squares - {'grid_size': 8, 'grid_spacing': 6}:\n# mean: [0.015625, 0.015625, 0.015625]\n# std: [0.12403473458920854, 0.12403473458920854, 0.12403473458920855]\n# overlap between squares for reconstruction loss, 5 < 8\n# XYSquaresData - xy_squares - {'grid_size': 8, 'grid_spacing': 5}:\n# mean: [0.015625, 0.015625, 0.015625]\n# std: [0.12403473458920855, 0.12403473458920855, 0.12403473458920854]\n# overlap between squares for reconstruction loss, 4 < 8\n# XYSquaresData - xy_squares - {'grid_size': 8, 'grid_spacing': 4}:\n# mean: [0.015625, 0.015625, 0.015625]\n# std: [0.12403473458920855, 0.12403473458920854, 0.12403473458920854]\n# overlap between squares for reconstruction loss, 3 < 8\n# XYSquaresData - xy_squares - {'grid_size': 8, 'grid_spacing': 3}:\n# mean: [0.015625, 0.015625, 0.015625]\n# std: [0.12403473458920854, 0.12403473458920854, 0.12403473458920854]\n# overlap between squares for reconstruction loss, 2 < 8\n# XYSquaresData - xy_squares - {'grid_size': 8, 'grid_spacing': 2}:\n# mean: [0.015625, 0.015625, 0.015625]\n# std: [0.12403473458920854, 0.12403473458920854, 0.12403473458920854]\n# overlap between squares for reconstruction loss, 1 < 8\n# XYSquaresData - xy_squares - {'grid_size': 8, 'grid_spacing': 1}:\n# mean: [0.015625, 0.015625, 0.015625]\n# std: [0.12403473458920855, 0.12403473458920855, 0.12403473458920855]\n# XYSquaresData - xy_squares - {'rgb': False}:\n# mean: [0.046146392822265625]\n# std: [0.2096506119375896]\n\n# Mpi3dData - mpi3d_toy - {'subset': 'toy', 'in_memory': True}:\n# mean: [0.22681593831231503, 0.22353985202496676, 0.22666059934624702]\n# std: [0.07854112062669572, 0.07319301658077378, 0.0790763900050426]\n# Mpi3dData - mpi3d_realistic - {'subset': 'realistic', 'in_memory': True}:\n# mean: [0.18240164396358813, 0.20723063241107917, 0.1820551008003256]\n# std: [0.09511163559287175, 0.10128881101801782, 0.09428244469525177]\n# Mpi3dData - mpi3d_real - {'subset': 'real', 'in_memory': True}:\n# mean: [0.13111154099374112, 0.16746449372488892, 0.14051725201807627]\n# std: [0.10137409845578041, 0.10087824338375781, 0.10534121043187629]\n\n\n# ========================================================================= #\n# END #\n# ========================================================================= #\n"
] |
[
[
"torch.mean",
"torch.cat",
"torch.utils.data.DataLoader",
"torch.std",
"torch.no_grad"
]
] |
jpsteinb/svgpathtools
|
[
"2123fa085e0c400bd42e00af3e1b151c70fa9344"
] |
[
"test/test_parsing.py"
] |
[
"# Note: This file was taken mostly as is from the svg.path module (v 2.0)\nfrom __future__ import division, absolute_import, print_function\nimport unittest\nfrom svgpathtools import *\nimport svgpathtools\nimport numpy as np\n\n\ndef construct_rotation_tf(a, x, y):\n a = a * np.pi / 180.0\n tf_offset = np.identity(3)\n tf_offset[0:2, 2:3] = np.array([[x], [y]])\n tf_rotate = np.identity(3)\n tf_rotate[0:2, 0:2] = np.array([[np.cos(a), -np.sin(a)],\n [np.sin(a), np.cos(a)]])\n tf_offset_neg = np.identity(3)\n tf_offset_neg[0:2, 2:3] = np.array([[-x], [-y]])\n\n return tf_offset.dot(tf_rotate).dot(tf_offset_neg)\n\n\nclass TestParser(unittest.TestCase):\n def test_svg_examples(self):\n \"\"\"Examples from the SVG spec\"\"\"\n path1 = parse_path('M 100 100 L 300 100 L 200 300 z')\n self.assertEqual(path1, Subpath(Line(100 + 100j, 300 + 100j),\n Line(300 + 100j, 200 + 300j),\n Line(200 + 300j, 100 + 100j)).set_Z().path_of())\n\n self.assertTrue(path1.isloop())\n\n # for Z command behavior when there is multiple subpaths\n path1 = parse_path('M 0 0 L 50 20 M 100 100 L 300 100 L 200 300 z')\n self.assertEqual(path1, Path(Line(0 + 0j, 50 + 20j),\n Subpath(Line(100 + 100j, 300 + 100j),\n Line(300 + 100j, 200 + 300j),\n Line(200 + 300j, 100 + 100j)).set_Z()))\n\n path1 = parse_path('M 100 100 L 200 200')\n path2 = parse_path('M100 100L200 200')\n self.assertEqual(path1, path2)\n\n path1 = parse_path('M 100 200 L 200 100 L -100 -200')\n path2 = parse_path('M 100 200 L 200 100 -100 -200')\n self.assertEqual(path1, path2)\n\n path1 = parse_path(\"\"\"M100,200 C100,100 250,100 250,200\n S400,300 400,200\"\"\")\n self.assertEqual(path1, Path(CubicBezier(100 + 200j,\n 100 + 100j,\n 250 + 100j,\n 250 + 200j),\n CubicBezier(250 + 200j,\n 250 + 300j,\n 400 + 300j,\n 400 + 200j)))\n\n path1 = parse_path('M100,200 C100,100 400,100 400,200')\n self.assertEqual(path1, Path(CubicBezier(100 + 200j,\n 100 + 100j,\n 400 + 100j,\n 400 + 200j)))\n\n path1 = parse_path('M100,500 C25,400 475,400 400,500')\n self.assertEqual(path1, Path(CubicBezier(100 + 500j,\n 25 + 400j,\n 475 + 400j,\n 400 + 500j)))\n\n path1 = parse_path('M100,800 C175,700 325,700 400,800')\n self.assertEqual(path1, Path(CubicBezier(100 + 800j,\n 175 + 700j,\n 325 + 700j,\n 400 + 800j)))\n\n path1 = parse_path('M600,200 C675,100 975,100 900,200')\n self.assertEqual(path1, Path(CubicBezier(600 + 200j,\n 675 + 100j,\n 975 + 100j,\n 900 + 200j)))\n\n path1 = parse_path('M600,500 C600,350 900,650 900,500')\n self.assertEqual(path1, Path(CubicBezier(600 + 500j,\n 600 + 350j,\n 900 + 650j,\n 900 + 500j)))\n\n path1 = parse_path(\"\"\"M600,800 C625,700 725,700 750,800\n S875,900 900,800\"\"\")\n self.assertEqual(path1, Path(CubicBezier(600 + 800j,\n 625 + 700j,\n 725 + 700j,\n 750 + 800j),\n CubicBezier(750 + 800j,\n 775 + 900j,\n 875 + 900j,\n 900 + 800j)))\n\n path1 = parse_path('M200,300 Q400,50 600,300 T1000,300')\n self.assertEqual(path1, Path(QuadraticBezier(200 + 300j,\n 400 + 50j,\n 600 + 300j),\n QuadraticBezier(600 + 300j,\n 800 + 550j,\n 1000 + 300j)))\n\n path1 = parse_path('M300,200 h-150 a150,150 0 1,0 150,-150 z')\n self.assertEqual(path1, Subpath(Line(300 + 200j, 150 + 200j),\n Arc(150 + 200j, 150 + 150j, 0, 1, 0, 300 + 50j),\n Line(300 + 50j, 300 + 200j)).set_Z().path_of())\n\n path1 = parse_path('M275,175 v-150 a150,150 0 0,0 -150,150 z')\n self.assertEqual(path1,\n Subpath(Line(275 + 175j, 275 + 25j),\n Arc(275 + 25j, 150 + 150j, 0, 0, 0, 125 + 175j),\n Line(125 + 175j, 275 + 175j)).set_Z().path_of())\n\n path1 = parse_path(\"\"\"M600,350 l 50,-25\n a25,25 -30 0,1 50,-25 l 50,-25\n a25,50 -30 0,1 50,-25 l 50,-25\n a25,75 -30 0,1 50,-25 l 50,-25\n a25,100 -30 0,1 50,-25 l 50,-25\"\"\")\n self.assertEqual(path1,\n Path(Line(600 + 350j, 650 + 325j),\n Arc(650 + 325j, 25 + 25j, -30, 0, 1, 700 + 300j),\n Line(700 + 300j, 750 + 275j),\n Arc(750 + 275j, 25 + 50j, -30, 0, 1, 800 + 250j),\n Line(800 + 250j, 850 + 225j),\n Arc(850 + 225j, 25 + 75j, -30, 0, 1, 900 + 200j),\n Line(900 + 200j, 950 + 175j),\n Arc(950 + 175j, 25 + 100j, -30, 0, 1, 1000 + 150j),\n Line(1000 + 150j, 1050 + 125j)))\n\n def test_others(self):\n # Other paths that need testing:\n\n # Relative moveto:\n path1 = parse_path('M 0 0 L 50 20 m 50 80 L 300 100 L 200 300 z')\n\n self.assertEqual(path1, Path(Line(0j, 50 + 20j),\n Subpath(Line(100 + 100j, 300 + 100j),\n Line(300 + 100j, 200 + 300j),\n Line(200 + 300j, 100 + 100j)).set_Z()))\n\n # Initial smooth and relative CubicBezier\n path1 = parse_path(\"\"\"M100,200 s 150,-100 150,0\"\"\")\n self.assertEqual(path1,\n Path(CubicBezier(100 + 200j,\n 100 + 200j,\n 250 + 100j,\n 250 + 200j)))\n\n # Initial smooth and relative QuadraticBezier\n path1 = parse_path(\"\"\"M100,200 t 150,0\"\"\")\n self.assertEqual(path1,\n Path(QuadraticBezier(100 + 200j,\n 100 + 200j,\n 250 + 200j)))\n\n # Relative QuadraticBezier\n path1 = parse_path(\"\"\"M100,200 q 0,0 150,0\"\"\")\n self.assertEqual(path1,\n Path(QuadraticBezier(100 + 200j,\n 100 + 200j,\n 250 + 200j)))\n\n def test_negative(self):\n \"\"\"You don't need spaces before a minus-sign\"\"\"\n path1 = parse_path('M100,200c10-5,20-10,30-20')\n path2 = parse_path('M 100 200 c 10 -5 20 -10 30 -20')\n self.assertEqual(path1, path2)\n\n def test_numbers(self):\n \"\"\"Exponents and other number format cases\"\"\"\n # It can be e or E, the plus is optional, and a minimum of\n # +/-3.4e38 must be supported.\n path1 = parse_path('M-3.4e38 3.4E+38L-3.4E-38,3.4e-38')\n path2 = Path(Line(-3.4e+38 + 3.4e+38j, -3.4e-38 + 3.4e-38j))\n self.assertEqual(path1, path2)\n\n def test_errors(self):\n self.assertRaises(ValueError, parse_path,\n 'M 100 100 L 200 200 Z 100 200')\n\n def test_transform(self):\n tf_matrix = svgpathtools.transform_parser.parse_transform(\n 'matrix(1.0 2.0 3.0 4.0 5.0 6.0)')\n expected_tf_matrix = np.identity(3)\n expected_tf_matrix[0:2, 0:3] = np.array([[1.0, 3.0, 5.0],\n [2.0, 4.0, 6.0]])\n self.assertTrue(np.array_equal(expected_tf_matrix, tf_matrix))\n\n # Try a test with no y specified\n expected_tf_translate = np.identity(3)\n expected_tf_translate[0, 2] = -36\n self.assertTrue(np.array_equal(\n expected_tf_translate,\n svgpathtools.transform_parser.parse_transform('translate(-36)')\n ))\n\n # Now specify y\n expected_tf_translate[1, 2] = 45.5\n tf_translate = svgpathtools.transform_parser.parse_transform(\n 'translate(-36 45.5)')\n self.assertTrue(np.array_equal(expected_tf_translate, tf_translate))\n\n # Try a test with no y specified\n expected_tf_scale = np.identity(3)\n expected_tf_scale[0, 0] = 10\n expected_tf_scale[1, 1] = 10\n self.assertTrue(np.array_equal(\n expected_tf_scale,\n svgpathtools.transform_parser.parse_transform('scale(10)')\n ))\n\n # Now specify y\n expected_tf_scale[1, 1] = 0.5\n tf_scale = svgpathtools.transform_parser.parse_transform('scale(10 0.5)')\n self.assertTrue(np.array_equal(expected_tf_scale, tf_scale))\n\n tf_rotation = svgpathtools.transform_parser.parse_transform('rotate(-10 50 100)')\n expected_tf_rotation = construct_rotation_tf(-10, 50, 100)\n self.assertTrue(np.array_equal(expected_tf_rotation, tf_rotation))\n\n # Try a test with no offset specified\n self.assertTrue(np.array_equal(\n construct_rotation_tf(50, 0, 0),\n svgpathtools.transform_parser.parse_transform('rotate(50)')\n ))\n\n expected_tf_skewx = np.identity(3)\n expected_tf_skewx[0, 1] = np.tan(40.0 * np.pi / 180.0)\n tf_skewx = svgpathtools.transform_parser.parse_transform('skewX(40)')\n self.assertTrue(np.array_equal(expected_tf_skewx, tf_skewx))\n\n expected_tf_skewy = np.identity(3)\n expected_tf_skewy[1, 0] = np.tan(30.0 * np.pi / 180.0)\n tf_skewy = svgpathtools.transform_parser.parse_transform('skewY(30)')\n self.assertTrue(np.array_equal(expected_tf_skewy, tf_skewy))\n\n self.assertTrue(np.array_equal(\n tf_rotation.dot(tf_translate).dot(tf_skewx).dot(tf_scale),\n svgpathtools.transform_parser.parse_transform(\n \"\"\"rotate(-10 50 100)\n translate(-36 45.5)\n skewX(40)\n scale(10 0.5)\"\"\")\n ))\n\n\nif __name__ == '__main__':\n unittest.main()\n"
] |
[
[
"numpy.array_equal",
"numpy.cos",
"numpy.sin",
"numpy.tan",
"numpy.identity",
"numpy.array"
]
] |
Aliang-CN/DeepMatch
|
[
"ea69d9cc9aec3742ae70f487b3ec9491fdfb14a8"
] |
[
"tests/utils.py"
] |
[
"from __future__ import absolute_import, division, print_function\n\nimport inspect\nimport os\nimport sys\n\nimport numpy as np\nimport tensorflow as tf\nfrom numpy.testing import assert_allclose\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras.layers import Input, Masking\nfrom tensorflow.python.keras.models import Model, load_model, save_model\n\nfrom deepctr.inputs import SparseFeat, DenseFeat, VarLenSparseFeat,DEFAULT_GROUP_NAME\nfrom deepmatch.layers import custom_objects\n\nSAMPLE_SIZE = 8\nVOCABULARY_SIZE = 4\n\n\ndef gen_sequence(dim, max_len, sample_size):\n return np.array([np.random.randint(0, dim, max_len) for _ in range(sample_size)]), np.random.randint(1, max_len + 1,\n sample_size)\n\n\ndef get_test_data(sample_size=1000, embedding_size=4, sparse_feature_num=1, dense_feature_num=1,\n sequence_feature=['sum', 'mean', 'max', 'weight'], classification=True, include_length=False,\n hash_flag=False, prefix='', use_group=False):\n feature_columns = []\n model_input = {}\n\n if 'weight' in sequence_feature:\n feature_columns.append(\n VarLenSparseFeat(SparseFeat(prefix + \"weighted_seq\", vocabulary_size=2, embedding_dim=embedding_size),\n maxlen=3, length_name=prefix + \"weighted_seq\" + \"_seq_length\",\n weight_name=prefix + \"weight\"))\n s_input, s_len_input = gen_sequence(\n 2, 3, sample_size)\n\n model_input[prefix + \"weighted_seq\"] = s_input\n model_input[prefix + 'weight'] = np.random.randn(sample_size, 3, 1)\n model_input[prefix + \"weighted_seq\" + \"_seq_length\"] = s_len_input\n sequence_feature.pop(sequence_feature.index('weight'))\n\n for i in range(sparse_feature_num):\n if use_group:\n group_name = str(i%3)\n else:\n group_name = DEFAULT_GROUP_NAME\n dim = np.random.randint(1, 10)\n feature_columns.append(\n SparseFeat(prefix + 'sparse_feature_' + str(i), dim, embedding_size, use_hash=hash_flag, dtype=tf.int32,group_name=group_name))\n\n for i in range(dense_feature_num):\n feature_columns.append(DenseFeat(prefix + 'dense_feature_' + str(i), 1, dtype=tf.float32))\n for i, mode in enumerate(sequence_feature):\n dim = np.random.randint(1, 10)\n maxlen = np.random.randint(1, 10)\n feature_columns.append(\n VarLenSparseFeat(SparseFeat(prefix + 'sequence_' + mode, vocabulary_size=dim, embedding_dim=embedding_size),\n maxlen=maxlen, combiner=mode))\n\n for fc in feature_columns:\n if isinstance(fc, SparseFeat):\n model_input[fc.name] = np.random.randint(0, fc.vocabulary_size, sample_size)\n elif isinstance(fc, DenseFeat):\n model_input[fc.name] = np.random.random(sample_size)\n else:\n s_input, s_len_input = gen_sequence(\n fc.vocabulary_size, fc.maxlen, sample_size)\n model_input[fc.name] = s_input\n if include_length:\n fc.length_name = prefix + \"sequence_\" + str(i) + '_seq_length'\n model_input[prefix + \"sequence_\" + str(i) + '_seq_length'] = s_len_input\n\n if classification:\n y = np.random.randint(0, 2, sample_size)\n else:\n y = np.random.random(sample_size)\n\n return model_input, y, feature_columns\n\n\ndef layer_test(layer_cls, kwargs={}, input_shape=None, input_dtype=None,\n\n input_data=None, expected_output=None,\n\n expected_output_dtype=None, fixed_batch_size=False, supports_masking=False):\n # generate input data\n\n if input_data is None:\n\n if not input_shape:\n raise AssertionError()\n\n if not input_dtype:\n input_dtype = K.floatx()\n\n input_data_shape = list(input_shape)\n\n for i, e in enumerate(input_data_shape):\n\n if e is None:\n input_data_shape[i] = np.random.randint(1, 4)\n input_mask = []\n if all(isinstance(e, tuple) for e in input_data_shape):\n input_data = []\n\n for e in input_data_shape:\n input_data.append(\n (10 * np.random.random(e)).astype(input_dtype))\n if supports_masking:\n a = np.full(e[:2], False)\n a[:, :e[1] // 2] = True\n input_mask.append(a)\n\n else:\n\n input_data = (10 * np.random.random(input_data_shape))\n\n input_data = input_data.astype(input_dtype)\n if supports_masking:\n a = np.full(input_data_shape[:2], False)\n a[:, :input_data_shape[1] // 2] = True\n\n print(a)\n print(a.shape)\n input_mask.append(a)\n\n else:\n\n if input_shape is None:\n input_shape = input_data.shape\n\n if input_dtype is None:\n input_dtype = input_data.dtype\n\n if expected_output_dtype is None:\n expected_output_dtype = input_dtype\n\n # instantiation\n\n layer = layer_cls(**kwargs)\n\n # test get_weights , set_weights at layer level\n\n weights = layer.get_weights()\n\n layer.set_weights(weights)\n\n try:\n expected_output_shape = layer.compute_output_shape(input_shape)\n except Exception:\n expected_output_shape = layer._compute_output_shape(input_shape)\n\n # test in functional API\n if isinstance(input_shape, list):\n if fixed_batch_size:\n\n x = [Input(batch_shape=e, dtype=input_dtype) for e in input_shape]\n if supports_masking:\n mask = [Input(batch_shape=e[0:2], dtype=bool)\n for e in input_shape]\n\n else:\n\n x = [Input(shape=e[1:], dtype=input_dtype) for e in input_shape]\n if supports_masking:\n mask = [Input(shape=(e[1],), dtype=bool) for e in input_shape]\n\n else:\n if fixed_batch_size:\n\n x = Input(batch_shape=input_shape, dtype=input_dtype)\n if supports_masking:\n mask = Input(batch_shape=input_shape[0:2], dtype=bool)\n\n else:\n\n x = Input(shape=input_shape[1:], dtype=input_dtype)\n if supports_masking:\n mask = Input(shape=(input_shape[1],), dtype=bool)\n\n if supports_masking:\n\n y = layer(Masking()(x), mask=mask)\n else:\n y = layer(x)\n\n if not (K.dtype(y) == expected_output_dtype):\n raise AssertionError()\n\n # check with the functional API\n if supports_masking:\n model = Model([x, mask], y)\n\n actual_output = model.predict([input_data, input_mask[0]])\n else:\n model = Model(x, y)\n\n actual_output = model.predict(input_data)\n\n actual_output_shape = actual_output.shape\n for expected_dim, actual_dim in zip(expected_output_shape,\n\n actual_output_shape):\n\n if expected_dim is not None:\n\n if not (expected_dim == actual_dim):\n raise AssertionError(\"expected_shape\", expected_output_shape, \"actual_shape\", actual_output_shape)\n\n if expected_output is not None:\n assert_allclose(actual_output, expected_output, rtol=1e-3)\n\n # test serialization, weight setting at model level\n\n model_config = model.get_config()\n\n recovered_model = model.__class__.from_config(model_config)\n\n if model.weights:\n weights = model.get_weights()\n\n recovered_model.set_weights(weights)\n\n _output = recovered_model.predict(input_data)\n\n assert_allclose(_output, actual_output, rtol=1e-3)\n\n # test training mode (e.g. useful when the layer has a\n\n # different behavior at training and testing time).\n\n if has_arg(layer.call, 'training'):\n model.compile('rmsprop', 'mse')\n\n model.train_on_batch(input_data, actual_output)\n\n # test instantiation from layer config\n\n layer_config = layer.get_config()\n\n layer_config['batch_input_shape'] = input_shape\n\n layer = layer.__class__.from_config(layer_config)\n\n # for further checks in the caller function\n\n return actual_output\n\n\ndef has_arg(fn, name, accept_all=False):\n \"\"\"Checks if a callable accepts a given keyword argument.\n\n\n\n For Python 2, checks if there is an argument with the given name.\n\n\n\n For Python 3, checks if there is an argument with the given name, and\n\n also whether this argument can be called with a keyword (i.e. if it is\n\n not a positional-only argument).\n\n\n\n # Arguments\n\n fn: Callable to inspect.\n\n name: Check if `fn` can be called with `name` as a keyword argument.\n\n accept_all: What to return if there is no parameter called `name`\n\n but the function accepts a `**kwargs` argument.\n\n\n\n # Returns\n\n bool, whether `fn` accepts a `name` keyword argument.\n\n \"\"\"\n\n if sys.version_info < (3,):\n\n arg_spec = inspect.getargspec(fn)\n\n if accept_all and arg_spec.keywords is not None:\n return True\n\n return (name in arg_spec.args)\n\n elif sys.version_info < (3, 3):\n\n arg_spec = inspect.getfullargspec(fn)\n\n if accept_all and arg_spec.varkw is not None:\n return True\n\n return (name in arg_spec.args or\n\n name in arg_spec.kwonlyargs)\n\n else:\n\n signature = inspect.signature(fn)\n\n parameter = signature.parameters.get(name)\n\n if parameter is None:\n\n if accept_all:\n\n for param in signature.parameters.values():\n\n if param.kind == inspect.Parameter.VAR_KEYWORD:\n return True\n\n return False\n\n return (parameter.kind in (inspect.Parameter.POSITIONAL_OR_KEYWORD,\n\n inspect.Parameter.KEYWORD_ONLY))\n\n\ndef check_model(model, model_name, x, y, check_model_io=True):\n \"\"\"\n compile model,train and evaluate it,then save/load weight and model file.\n :param model:\n :param model_name:\n :param x:\n :param y:\n :param check_model_io: test save/load model file or not\n :return:\n \"\"\"\n\n model.fit(x, y, batch_size=10, epochs=2, validation_split=0.5)\n\n\n\n print(model_name + \" test train valid pass!\")\n\n\n user_embedding_model = Model(inputs=model.user_input, outputs=model.user_embedding)\n item_embedding_model = Model(inputs=model.item_input, outputs=model.item_embedding)\n\n user_embs = user_embedding_model.predict(x, batch_size=2 ** 12)\n # user_embs = user_embs[:, i, :] i in [0,k_max) if MIND\n print(model_name + \" user_emb pass!\")\n item_embs = item_embedding_model.predict(x, batch_size=2 ** 12)\n\n print(model_name + \" item_emb pass!\")\n\n model.save_weights(model_name + '_weights.h5')\n model.load_weights(model_name + '_weights.h5')\n os.remove(model_name + '_weights.h5')\n print(model_name + \" test save load weight pass!\")\n if check_model_io:\n save_model(model, model_name + '.h5')\n model = load_model(model_name + '.h5', custom_objects)\n os.remove(model_name + '.h5')\n print(model_name + \" test save load model pass!\")\n\n print(model_name + \" test pass!\")\n\n\ndef get_xy_fd(hash_flag=False):\n\n\n user_feature_columns = [SparseFeat('user',3),SparseFeat(\n 'gender', 2),VarLenSparseFeat(SparseFeat('hist_item', vocabulary_size=3 + 1,embedding_dim=4,embedding_name='item'), maxlen=4,length_name=\"hist_len\") ]\n item_feature_columns = [SparseFeat('item', 3 + 1,embedding_dim=4,)]\n\n\n uid = np.array([0, 1, 2,1])\n ugender = np.array([0, 1, 0,1])\n iid = np.array([1, 2, 3,1]) # 0 is mask value\n\n hist_iid = np.array([[1, 2, 3, 0], [1, 2, 3, 0], [1, 2, 0, 0],[3, 0, 0, 0]])\n hist_len = np.array([3,3,2,1])\n\n feature_dict = {'user': uid, 'gender': ugender, 'item': iid,\n 'hist_item': hist_iid, \"hist_len\":hist_len}\n\n #feature_names = get_feature_names(feature_columns)\n x = feature_dict\n y = np.array([1, 1, 1,1])\n return x, y, user_feature_columns,item_feature_columns\n\n\ndef get_xy_fd_sdm(hash_flag=False):\n\n user_feature_columns = [SparseFeat('user',3),\n SparseFeat('gender', 2),\n VarLenSparseFeat(SparseFeat('prefer_item', vocabulary_size=100,embedding_dim=8,\n embedding_name='item'), maxlen=6, length_name=\"prefer_sess_length\"),\n VarLenSparseFeat(SparseFeat('prefer_cate', vocabulary_size=100, embedding_dim=8,\n embedding_name='cate'), maxlen=6, length_name=\"prefer_sess_length\"),\n VarLenSparseFeat(SparseFeat('short_item', vocabulary_size=100,embedding_dim=8,\n embedding_name='item'), maxlen=4, length_name=\"short_sess_length\"),\n VarLenSparseFeat(SparseFeat('short_cate', vocabulary_size=100, embedding_dim=8,\n embedding_name='cate'), maxlen=4, length_name=\"short_sess_length\"),\n ]\n item_feature_columns = [SparseFeat('item', 100, embedding_dim=8,)]\n\n\n uid = np.array([0, 1, 2, 1])\n ugender = np.array([0, 1, 0, 1])\n iid = np.array([1, 2, 3, 1]) # 0 is mask value\n\n prefer_iid = np.array([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 0], [1, 2, 3, 3, 0, 0], [1, 2, 4, 0, 0, 0]])\n prefer_cate = np.array([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 0], [1, 2, 3, 3, 0, 0], [1, 2, 4, 0, 0, 0]])\n short_iid = np.array([[1, 2, 3, 0], [1, 2, 3, 0], [1, 2, 0, 0], [3, 0, 0, 0]])\n short_cate = np.array([[1, 2, 3, 0], [1, 2, 3, 0], [1, 2, 0, 0], [3, 0, 0, 0]])\n prefer_len = np.array([6, 5, 4, 3])\n short_len = np.array([3, 3, 2, 1])\n\n feature_dict = {'user': uid, 'gender': ugender, 'item': iid, 'prefer_item': prefer_iid, \"prefer_cate\":prefer_cate,\n 'short_item': short_iid, 'short_cate': short_cate, 'prefer_sess_length': prefer_len, 'short_sess_length':short_len}\n\n #feature_names = get_feature_names(feature_columns)\n x = feature_dict\n y = np.array([1, 1, 1, 0])\n history_feature_list = ['item', 'cate']\n\n return x, y, user_feature_columns, item_feature_columns, history_feature_list"
] |
[
[
"tensorflow.python.keras.models.save_model",
"numpy.random.random",
"tensorflow.python.keras.layers.Masking",
"tensorflow.python.keras.models.load_model",
"numpy.full",
"tensorflow.python.keras.backend.dtype",
"tensorflow.python.keras.models.Model",
"numpy.random.randn",
"tensorflow.python.keras.backend.floatx",
"numpy.testing.assert_allclose",
"numpy.array",
"tensorflow.python.keras.layers.Input",
"numpy.random.randint"
]
] |
BordensteinLaboratory/VMI-diet-challenge
|
[
"5e31a3fec3d481e2b62987d176e33ebf00279778"
] |
[
"Metagenome_shortread_analysis/merge_metaphlan_tables_readcount.py"
] |
[
"#!/usr/bin/env python3\n\n# This utility script is adapted from the Biobakery merge_metaphlan_tables.py utility script\n# Instead of merging the relative abundances for all matched tables, it merges the estimated read counts\n\nimport argparse\nimport os\nimport sys\nimport re\nimport pandas as pd\nfrom itertools import takewhile\n\ndef merge( aaastrIn, ostm ):\n \"\"\"\n Outputs the table join of the given pre-split string collection.\n\n :param aaastrIn: One or more split lines from which data are read.\n :type aaastrIn: collection of collections of string collections\n :param iCol: Data column in which IDs are matched (zero-indexed).\n :type iCol: int\n :param ostm: Output stream to which matched rows are written.\n :type ostm: output stream\n \"\"\"\n\n listmpaVersion = set()\n merged_tables = pd.DataFrame()\n\n for f in aaastrIn:\n with open(f) as fin:\n headers = [x.strip() for x in takewhile(lambda x: x.startswith('#'), fin)]\n if len(headers) == 1:\n names = ['clade_name', 'estimated_number_of_reads_from_the_clade']\n index_col = 0\n if len(headers) >= 4:\n names = headers[-1].split('#')[1].strip().split('\\t')\n index_col = [0,1]\n\n mpaVersion = list(filter(re.compile('#mpa_v[0-9]{2,}_CHOCOPhlAn\\w*/{0,3}_[0-9]{0,}').match, headers))\n if len(mpaVersion):\n listmpaVersion.add(mpaVersion[0])\n else:\n print('merge_metaphlan_tables found tables without a header including the database version. Exiting.\\n')\n return\n if len(listmpaVersion) > 1:\n print('merge_metaphlan_tables found tables made with different versions of the MetaPhlAn database.\\nPlease re-run MetaPhlAn with the same database.\\n')\n return\n\n iIn = pd.read_csv(f,\n sep='\\t',\n skiprows=len(headers),\n names = names,\n usecols=[0,1,4],\n ).fillna('')\n iIn = iIn.set_index(iIn.columns[index_col].to_list())\n if merged_tables.empty:\n merged_tables = iIn.iloc[:,0].rename(os.path.splitext(os.path.basename(f))[0]).to_frame()\n else:\n merged_tables = pd.merge(iIn.iloc[:,0].rename(os.path.splitext(os.path.basename(f))[0]).to_frame(),\n merged_tables,\n how='outer',\n left_index=True,\n right_index=True\n )\n if listmpaVersion:\n ostm.write(list(listmpaVersion)[0]+'\\n')\n merged_tables.fillna('0').reset_index().to_csv(ostm, index=False, sep = '\\t')\n\nargp = argparse.ArgumentParser( prog = \"merge_metaphlan_tables.py\",\n description = \"\"\"Performs a table join on one or more metaphlan output files.\"\"\")\nargp.add_argument( \"aistms\", metavar = \"input.txt\", nargs = \"+\",\n help = \"One or more tab-delimited text tables to join\" )\nargp.add_argument( '-o', metavar = \"output.txt\", nargs = 1,\n help = \"Name of output file in which joined tables are saved\" )\n\n__doc__ = \"::\\n\\n\\t\" + argp.format_help( ).replace( \"\\n\", \"\\n\\t\" )\n\nargp.usage = argp.format_usage()[7:]+\"\\n\\n\\tPlease make sure to supply file paths to the files to combine. If combining 3 files (Table1.txt, Table2.txt, and Table3.txt) the call should be:\\n\\n\\t\\tpython merge_metaphlan_tables.py Table1.txt Table2.txt Table3.txt > output.txt\\n\\n\\tA wildcard to indicate all .txt files that start with Table can be used as follows:\\n\\n\\t\\tpython merge_metaphlan_tables.py Table*.txt > output.txt\"\n\n\ndef main( ):\n args = argp.parse_args( )\n if args.o is None:\n merge(args.aistms, sys.stdout)\n else:\n with open(args.o[0], 'w') as fout:\n merge(args.aistms, fout)\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"pandas.DataFrame"
]
] |
morgenst/PyAnalysisTools
|
[
"f3b1f89870e7bbae1549c228a56d2c36bbba7af3"
] |
[
"tests/unit/TestMLHelpers.py"
] |
[
"import os\nimport unittest\nfrom builtins import range\n\nimport matplotlib\nimport mock\nimport numpy as np\nimport pandas as pd\nimport root_numpy\nfrom mock import MagicMock, patch, mock_open\nimport six\nfrom numpy.testing import assert_array_equal\nfrom pandas.util.testing import assert_frame_equal\n\nimport ROOT\nfrom PyAnalysisTools.AnalysisTools import MLHelper as mh\nfrom PyAnalysisTools.base import InvalidInputError\nfrom PyAnalysisTools.base.FileHandle import FileHandle\n\nif six.PY2:\n builtin = '__builtin__'\nelse:\n builtin = 'builtins'\n\ncwd = os.path.dirname(__file__)\nROOT.gROOT.SetBatch(True)\n\n\nclass TestMLHelpers(unittest.TestCase):\n def setUp(self):\n pass\n\n def tearDown(self):\n pass\n\n def test_print_classification(self):\n model = MagicMock()\n model.predict_classes = MagicMock(return_value=[1])\n mh.print_classification(model, 1, [2], 3, [4])\n\n @mock.patch.object(matplotlib.pyplot, 'savefig', lambda x: None)\n def test_plot_scoring(self):\n class Object(object):\n pass\n history = Object()\n history.history = {'foo': [(100, 100), (200, 200)]}\n history.history['val_foo'] = history.history['foo']\n mh.plot_scoring(history, 'foo', ['foo'], 'foo')\n\n\nclass TestMLConfig(unittest.TestCase):\n def test_ctor_default(self):\n self.assertRaises(KeyError, mh.MLConfig)\n\n def test_ctor(self):\n cfg = mh.MLConfig(branch_name='foo', variable_list=[], selection=None)\n self.assertEqual('foo', cfg.score_name)\n self.assertEqual([], cfg.varset)\n self.assertIsNone(cfg.scaler)\n self.assertIsNone(cfg.scale_algo)\n self.assertIsNone(cfg.selection)\n\n def test_equality(self):\n cfg = mh.MLConfig(branch_name='foo', variable_list=[], selection=None)\n cfg2 = mh.MLConfig(branch_name='foo', variable_list=[], selection=None)\n self.assertEqual(cfg, cfg2)\n\n def test_inequality(self):\n cfg = mh.MLConfig(branch_name='foo', variable_list=[], selection=None)\n cfg2 = mh.MLConfig(branch_name='bar', variable_list=[], selection=None)\n self.assertNotEqual(cfg, cfg2)\n\n def test_inequality_scaler(self):\n scaler = mh.DataScaler()\n cfg = mh.MLConfig(branch_name='foo', variable_list=[], selection=None, scaler=scaler)\n cfg2 = mh.MLConfig(branch_name='bar', variable_list=[], selection=None)\n self.assertNotEqual(cfg, cfg2)\n self.assertNotEqual(cfg2, cfg)\n\n def test_inequality_scaler_algo(self):\n scaler_def = mh.DataScaler()\n scaler = mh.DataScaler('foo')\n cfg = mh.MLConfig(branch_name='foo', variable_list=[], selection=None, scaler=scaler)\n cfg2 = mh.MLConfig(branch_name='bar', variable_list=[], selection=None, scaler=scaler_def)\n self.assertNotEqual(cfg, cfg2)\n self.assertNotEqual(cfg2, cfg)\n\n def test_inequality_type(self):\n cfg = mh.MLConfig(branch_name='foo', variable_list=[], selection=None)\n self.assertNotEqual(cfg, 5.)\n\n def test_handle_ctor(self):\n handle = mh.MLConfigHandle(branch_name='foo', variable_list=[], selection=None)\n cfg = mh.MLConfig(branch_name='foo', variable_list=[], selection=None)\n self.assertEqual(cfg, handle.config)\n self.assertEqual('.', handle.output_path)\n self.assertEqual('./ml_config_summary.pkl', handle.file_name)\n\n def test_print(self):\n handle = mh.MLConfig(branch_name='foo', variable_list=['foo'], selection=['bar'])\n print_out = 'Attached ML branch foo was created with the following configuration \\nvariables: \\n\\t foo\\n' \\\n 'selection: \\n\\t bar\\nscaler: None\\n'\n self.assertEqual(print_out, handle.__str__())\n\n\nclass TestRootNumpyConverter(unittest.TestCase):\n def test_ctor(self):\n converter = mh.Root2NumpyConverter(['foo'])\n self.assertEqual(['foo'], converter.branches)\n\n def test_ctor_no_list(self):\n converter = mh.Root2NumpyConverter('foo')\n self.assertEqual(['foo'], converter.branches)\n\n def test_merge(self):\n arr1 = np.array([1, 2])\n arr2 = np.array([3, 4])\n arr3 = np.array([5, 6])\n arr4 = np.array([7, 8])\n converter = mh.Root2NumpyConverter('foo')\n data, labels = converter.merge([arr1, arr2], [arr3, arr4])\n np.testing.assert_array_equal(np.array([i+1 for i in range(8)]), data)\n np.testing.assert_array_equal(np.array([1]*4+[0]*4), labels)\n\n @patch.object(root_numpy, 'tree2array', lambda x, **kwargs: (x, kwargs))\n def test_convert(self):\n converter = mh.Root2NumpyConverter(['foo'])\n data = converter.convert_to_array(None, 'sel', 1000)\n self.assertIsNone(data[0])\n self.assertEqual({'branches': ['foo'], 'selection': 'sel', 'start': 0, 'stop': 1000}, data[1])\n\n\nclass TestTrainingReader(unittest.TestCase):\n def test_default_ctor(self):\n reader = mh.TrainingReader()\n self.assertEqual('', reader.mode)\n self.assertFalse(reader.numpy_input)\n\n @mock.patch.object(pd, 'read_json', lambda _: None)\n @patch(builtin + \".open\", new_callable=mock_open)\n def test_ctor_json(self, _):\n reader = mh.TrainingReader(input_file_list=['foo.json'])\n self.assertEqual('pandas', reader.mode)\n self.assertFalse(reader.numpy_input)\n self.assertEqual({'foo.json': None}, reader.data)\n\n def test_ctor_numpy_list(self):\n reader = mh.TrainingReader(input_file=['foo.npy', 'bar.npy'])\n self.assertEqual('', reader.mode)\n self.assertTrue(reader.numpy_input)\n\n def test_ctor_numpy(self):\n reader = mh.TrainingReader(input_file='foo.npy', signal_tree_names=['sig'], bkg_tree_names=['bkg'])\n self.assertEqual('', reader.mode)\n self.assertFalse(reader.numpy_input)\n self.assertEqual(['sig'], reader.signal_tree_names)\n self.assertEqual(['bkg'], reader.bkg_tree_names)\n\n def test_parse_tree_names(self):\n reader = mh.TrainingReader(input_file='foo.npy', signal_tree_names=['sig'], bkg_tree_names=['bkg'])\n sig_train, bkg_train, sig_eval, bkg_eval = reader.parse_tree_names()\n self.assertEqual(['train_sig'], sig_train)\n self.assertEqual(['eval_sig'], sig_eval)\n self.assertEqual(['train_bkg'], bkg_train)\n self.assertEqual(['eval_bkg'], bkg_eval)\n\n @mock.patch.object(FileHandle, 'get_object_by_name', lambda _, x: x)\n def test_get_trees(self):\n reader = mh.TrainingReader(input_file='foo.npy', signal_tree_names=['sig'], bkg_tree_names=['bkg'])\n sig_train, bkg_train, sig_eval, bkg_eval = reader.get_trees()\n self.assertEqual(['train_sig'], sig_train)\n self.assertEqual(['eval_sig'], sig_eval)\n self.assertEqual(['train_bkg'], bkg_train)\n self.assertEqual(['eval_bkg'], bkg_eval)\n\n def test_prepare_data(self):\n reader = mh.TrainingReader()\n reader.mode = 'pandas'\n reader.data = {'_foo': pd.DataFrame({'var1': [1., 2.]}), '_bar': pd.DataFrame({'var1': [3., 4.]})}\n cfg = mh.MLTrainConfig(signals=['foo'], backgrounds=['bar'])\n signal, bkg, labels = reader.prepare_data(cfg)\n assert_frame_equal(pd.DataFrame({'var1': [1., 2.]}), signal)\n assert_frame_equal(pd.DataFrame({'var1': [3., 4.]}), bkg)\n assert_array_equal(np.array([1, 1, 0, 0]), labels)\n\n def test_prepare_data_unsupported_mode(self):\n reader = mh.TrainingReader(mode='foo')\n cfg = mh.MLTrainConfig(signals=['foo'], backgrounds=['bar'])\n self.assertEqual((None, None, None), reader.prepare_data(cfg))\n\n\nclass TestMLAnalyser(unittest.TestCase):\n def test_default_ctor(self):\n analyser = mh.MLAnalyser(input_files=[])\n self.assertEqual([], analyser.file_handles)\n self.assertIsNone(analyser.process_config_file)\n self.assertIsNone(analyser.process_configs)\n self.assertIsNone(analyser.tree_name)\n self.assertIsNone(analyser.branch_name)\n\n @mock.patch.object(mh.MLAnalyser, 'read_score', lambda x, y: [np.array([1, 2, 3]), np.array([4, 5, 6])])\n def test_plot_roc(self):\n analyser = mh.MLAnalyser(input_files=[])\n analyser.plot_roc()\n\n # def test_read_score(self):\n # analyser = mh.MLAnalyser(input_files=[])\n # analyser.process_configs\n # sig, bkg = analyser.read_score()\n\n\nclass TestDataScaler(unittest.TestCase):\n def test_default_ctor(self):\n scaler = mh.DataScaler()\n self.assertEqual('default', scaler.scale_algo)\n self.assertIsNone(scaler.scaler)\n\n def test_equality(self):\n scaler = mh.DataScaler()\n scaler2 = mh.DataScaler()\n self.assertEqual(scaler, scaler2)\n self.assertEqual(scaler, scaler)\n self.assertEqual(scaler2, scaler)\n\n def test_inequality(self):\n scaler = mh.DataScaler()\n scaler2 = mh.DataScaler(algo='foo')\n self.assertNotEqual(scaler, scaler2)\n self.assertNotEqual(scaler2, scaler)\n self.assertNotEqual(scaler, 5)\n\n def test_get_algos(self):\n self.assertEqual([\"default\", \"standard\", \"min_max\"], mh.DataScaler.get_algos())\n\n def test_apply_scaling_default(self):\n scaler = mh.DataScaler()\n res = scaler.apply_scaling(np.array([1, 2, 3]).reshape(-1, 1), np.array([1, 2, 3]).reshape(-1, 1))\n expected = (np.array([0., 0.5, 1.]).reshape(3, 1), np.array([0, 1, 2]))\n self.assertIsNone(np.testing.assert_array_equal(expected[0], res[0]))\n self.assertIsNone(np.testing.assert_array_equal(expected[1], res[1]))\n\n def test_apply_scaling_min_max(self):\n scaler = mh.DataScaler(algo='min_max')\n res = scaler.apply_scaling(np.array([1, 2, 3]).reshape(-1, 1), np.array([1, 2, 3]).reshape(-1, 1))\n expected = (np.array([0., 0.5, 1.]).reshape(3, 1), np.array([0, 1, 2]))\n self.assertIsNone(np.testing.assert_array_equal(expected[0], res[0]))\n self.assertIsNone(np.testing.assert_array_equal(expected[1], res[1]))\n\n def test_apply_scaling_standard(self):\n scaler = mh.DataScaler(algo='standard')\n X = np.array([1, 2, 3]).reshape(-1, 1)\n res = scaler.apply_scaling(X, np.array([1, 2, 3]).reshape(-1, 1))\n expected = ((X - np.mean(X)) / np.std(X), np.array([0, 1, 2]))\n self.assertIsNone(np.testing.assert_array_equal(expected[0], res[0]))\n self.assertIsNone(np.testing.assert_array_equal(expected[1], res[1]))\n\n def test_apply_scaling_exception(self):\n scaler = mh.DataScaler(algo='foo')\n self.assertRaises(InvalidInputError, scaler.apply_scaling, X=1, y=None)\n"
] |
[
[
"pandas.DataFrame",
"numpy.testing.assert_array_equal",
"numpy.std",
"numpy.mean",
"numpy.array"
]
] |
willi-z/msys-opt
|
[
"2054931737893b4ea77a4ba2dbfb6a3e2bce7779"
] |
[
"src/msys_opt/types/vector.py"
] |
[
"from ..core import OptimizableType\nimport numpy as np\nfrom ..core.generator import Limiter\n\n\nclass VectorType(OptimizableType):\n def __init__(self, default_value):\n super().__init__(np.array([0]), Limiter())\n self.set_value(default_value)\n\n def is_same(self, value) -> bool:\n return list(self.value) == list(value)\n\n def set_value(self, value) -> bool:\n if isinstance(value, np.ndarray):\n return super().set_value(value)\n elif isinstance(value, list):\n return super().set_value(np.array(value))\n elif isinstance(value, int) or isinstance(value, float):\n return super().set_value(np.array([value]))\n return False\n\n def to_dict(self) -> dict:\n res = super().to_dict()\n res[\"value\"] = self.value.tolist()\n return res\n\n def from_dict(self, json: dict) -> bool:\n super().from_dict(json)\n if \"value\" in json.keys():\n self.value = np.array(json[\"value\"])\n return True\n"
] |
[
[
"numpy.array"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.